aozora 0.5.0

Aozora Bunko notation parser with incremental document snapshots
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
//! Canonical slug catalogue for Aozora annotation bodies (Phase 1.2 of
//! the editor-integration sprint).
//!
//! `classify::BODY_PATTERNS` is the *parser-side* aho-corasick
//! table — its goal is exhaustive matching, including every digit a
//! `{N}字下げ` form can start with. This module is the *editor-side*
//! mirror: the public, stable list of slugs an LSP completion menu
//! offers and the LSP `canonicalize` code action snaps user input to.
//!
//! The two tables must stay in sync: every `SLUGS` entry has to be one the
//! classifier dispatches without leaking a residual annotation marker.
//!
//! ## Why a separate table
//!
//! - **Granularity**: the editor wants `{N}字下げ` (one entry, accepts
//!   a parameter), not ten distinct rows for each digit prefix.
//! - **Documentation**: each entry carries a Japanese `doc` string that
//!   becomes the LSP completion item's `documentation` field.
//! - **Stability**: `BODY_PATTERNS`'s exact shape is tied to classify-stage
//!   internals (`LeftmostLongest` dispatch order, `BodyFamily` variants);
//!   downstream editor consumers should not depend on it.
//!
//! ## Canonicalisation
//!
//! [`canonicalise_slug`] maps a known orthographic *variant* (typically
//! a hiragana-only spelling — `ぼうてん`, `にぼうてん`) to the canonical
//! form (`傍点`). The variant table is intentionally small: it covers
//! the highest-frequency author-side abbreviations the editor surface
//! treats as a one-keystroke-quick-fix. Any input that is already
//! canonical short-circuits with `Some(canonical)` so callers can
//! always trust the return value.

use crate::spec::PairKind;

/// Family / coarse category a slug belongs to. Used by the LSP
/// completion UI to group entries (`CompletionItem::sort_text`) and
/// pick an appropriate `CompletionItemKind` icon.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "json", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum SlugFamily {
    /// `[#改ページ]` and other section-level page breaks.
    PageBreak,
    /// `[#改丁]`, `[#改段]`, `[#改見開き]`.
    Section,
    /// Block container open marker (`[#ここから...]`). Pairs with
    /// the corresponding [`SlugFamily::BlockContainerClose`] slug.
    BlockContainerOpen,
    /// Block container close marker (`[#ここで...終わり]`).
    BlockContainerClose,
    /// Leaf-line layout slug applied to the immediately preceding
    /// paragraph (`地付き`, `{N}字下げ`, `地から{N}字上げ`).
    LeafAlign,
    /// Forward-reference bouten / underline (`[#「target」に傍点]`).
    Bouten,
    /// Inline figure (`[#挿絵(path)入る]`).
    Illustration,
    /// Framed rule frame (open / close).
    Framed,
    /// Warichu inline-break (open / close).
    Warichu,
    /// Forward-reference 縦中横 (`[#「target」は縦中横]`).
    CombineUpright,
    /// Kaeriten single mark (一, 二, 三, 上, 中, 下, 甲, 乙, 丙, 丁,
    /// 四, レ).
    KaeritenSingle,
    /// Kaeriten compound mark (一レ, 二レ, …).
    KaeritenCompound,
}

impl SlugFamily {
    /// Every variant in declaration order. Lets the wire-tag
    /// exhaustiveness test and codegen enumerate the families without a
    /// hand-maintained parallel.
    pub const ALL: [Self; 12] = [
        Self::PageBreak,
        Self::Section,
        Self::BlockContainerOpen,
        Self::BlockContainerClose,
        Self::LeafAlign,
        Self::Bouten,
        Self::Illustration,
        Self::Framed,
        Self::Warichu,
        Self::CombineUpright,
        Self::KaeritenSingle,
        Self::KaeritenCompound,
    ];

    /// Stable camelCase identifier used by the driver wire formats.
    /// Centralised in the enum's own crate so the wire spelling has a
    /// single authority and the `match` is exhaustiveness-checked at
    /// compile time (no `_` fallback — a new family must declare its tag).
    #[must_use]
    pub const fn as_json_tag(self) -> &'static str {
        match self {
            Self::PageBreak => "pageBreak",
            Self::Section => "section",
            Self::BlockContainerOpen => "blockContainerOpen",
            Self::BlockContainerClose => "blockContainerClose",
            Self::LeafAlign => "leafAlign",
            Self::Bouten => "bouten",
            Self::Illustration => "illustration",
            Self::Framed => "framed",
            Self::Warichu => "warichu",
            Self::CombineUpright => "combineUpright",
            Self::KaeritenSingle => "kaeritenSingle",
            Self::KaeritenCompound => "kaeritenCompound",
        }
    }
}

/// One row of the slug catalogue.
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "json", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct SlugEntry {
    /// Canonical body text (without the surrounding `[#` / `]`).
    pub canonical: &'static str,
    /// Coarse category / family.
    pub family: SlugFamily,
    /// Whether the slug expects a numeric parameter (or, for `Illustration`,
    /// a path) following the canonical text.
    pub accepts_param: bool,
    /// Short Japanese description shown in LSP `CompletionItem.detail`
    /// / `documentation` fields. Single sentence, no surrounding
    /// punctuation, terminating period.
    pub doc: &'static str,
    /// For `BlockContainerOpen` / `BlockContainerClose` slugs, the
    /// canonical text of the partner slug — so the editor can link
    /// them together (insert close on accept, jump to partner, …).
    /// `None` for non-paired families.
    pub partner: Option<&'static str>,
    /// Always [`PairKind::Bracket`] for the slugs in this table — the
    /// surrounding `[# … ]` is a bracket pair. Carried so editor
    /// snippets can render the wrapper bracket pair without having to
    /// re-derive it.
    pub wrapper: PairKind,
}

/// Canonical slug catalogue. See module docs.
///
/// Order is irrelevant for behavior; entries are grouped by family for
/// readability. The `every_canonical_resolves_through_canonicalise_slug`
/// test pins identity round-trip for every entry.
pub(crate) const SLUGS: &[SlugEntry] = &[
    // --- Section / page break ----------------------------------------------
    SlugEntry {
        canonical: "改ページ",
        family: SlugFamily::PageBreak,
        accepts_param: false,
        doc: "ページを改める",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "改丁",
        family: SlugFamily::Section,
        accepts_param: false,
        doc: "改丁(次の奇数ページから)",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "改段",
        family: SlugFamily::Section,
        accepts_param: false,
        doc: "改段(段組を改める)",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "改見開き",
        family: SlugFamily::Section,
        accepts_param: false,
        doc: "改見開き(次の見開きへ)",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    // --- Block containers (open / close pairs) -----------------------------
    SlugEntry {
        canonical: "ここから字下げ",
        family: SlugFamily::BlockContainerOpen,
        accepts_param: false,
        doc: "1字下げを開始(終わりまで)",
        partner: Some("ここで字下げ終わり"),
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "ここから{N}字下げ",
        family: SlugFamily::BlockContainerOpen,
        accepts_param: true,
        doc: "N字下げを開始(終わりまで)",
        partner: Some("ここで字下げ終わり"),
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "ここで字下げ終わり",
        family: SlugFamily::BlockContainerClose,
        accepts_param: false,
        doc: "字下げブロックを閉じる",
        partner: Some("ここから字下げ"),
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "ここから地付き",
        family: SlugFamily::BlockContainerOpen,
        accepts_param: false,
        doc: "地付きを開始",
        partner: Some("ここで地付き終わり"),
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "ここから地から{N}字上げ",
        family: SlugFamily::BlockContainerOpen,
        accepts_param: true,
        doc: "地からN字上げを開始",
        partner: Some("ここで地付き終わり"),
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "ここで地付き終わり",
        family: SlugFamily::BlockContainerClose,
        accepts_param: false,
        doc: "地付きブロックを閉じる",
        partner: Some("ここから地付き"),
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "罫囲み",
        family: SlugFamily::Framed,
        accepts_param: false,
        doc: "罫線で囲む(終わりまで)",
        partner: Some("罫囲み終わり"),
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "罫囲み終わり",
        family: SlugFamily::Framed,
        accepts_param: false,
        doc: "罫囲みを閉じる",
        partner: Some("罫囲み"),
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "割り注",
        family: SlugFamily::Warichu,
        accepts_param: false,
        doc: "割り注を開始(終わりまで)",
        partner: Some("割り注終わり"),
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "割り注終わり",
        family: SlugFamily::Warichu,
        accepts_param: false,
        doc: "割り注を閉じる",
        partner: Some("割り注"),
        wrapper: PairKind::Bracket,
    },
    // --- Leaf alignment (single-paragraph) ---------------------------------
    SlugEntry {
        canonical: "地付き",
        family: SlugFamily::LeafAlign,
        accepts_param: false,
        doc: "前の段落を地付きに揃える",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "地から{N}字上げ",
        family: SlugFamily::LeafAlign,
        accepts_param: true,
        doc: "前の段落を地からN字上げて揃える",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "{N}字下げ",
        family: SlugFamily::LeafAlign,
        accepts_param: true,
        doc: "前の段落をN字下げる(単発)",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    // --- Bouten / underline (forward-ref via 「target」に...) --------------
    SlugEntry {
        canonical: "傍点",
        family: SlugFamily::Bouten,
        accepts_param: false,
        doc: "ゴマ傍点([#「対象」に傍点])",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "白ゴマ傍点",
        family: SlugFamily::Bouten,
        accepts_param: false,
        doc: "白ゴマ傍点",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "丸傍点",
        family: SlugFamily::Bouten,
        accepts_param: false,
        doc: "丸傍点",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "白丸傍点",
        family: SlugFamily::Bouten,
        accepts_param: false,
        doc: "白丸傍点",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "二重丸傍点",
        family: SlugFamily::Bouten,
        accepts_param: false,
        doc: "二重丸傍点",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "蛇の目傍点",
        family: SlugFamily::Bouten,
        accepts_param: false,
        doc: "蛇の目傍点",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "ばつ傍点",
        family: SlugFamily::Bouten,
        accepts_param: false,
        doc: "ばつ傍点",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "白三角傍点",
        family: SlugFamily::Bouten,
        accepts_param: false,
        doc: "白三角傍点",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "波線",
        family: SlugFamily::Bouten,
        accepts_param: false,
        doc: "波線(傍線の波形)",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "傍線",
        family: SlugFamily::Bouten,
        accepts_param: false,
        doc: "傍線(下線)",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "二重傍線",
        family: SlugFamily::Bouten,
        accepts_param: false,
        doc: "二重傍線(二重下線)",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    // --- Other inline -----------------------------------------------------
    SlugEntry {
        canonical: "挿絵({path})入る",
        family: SlugFamily::Illustration,
        accepts_param: true,
        doc: "挿絵を埋め込む",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "縦中横",
        family: SlugFamily::CombineUpright,
        accepts_param: false,
        doc: "縦中横([#「対象」は縦中横])",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    // --- Kaeriten single (12) ---------------------------------------------
    SlugEntry {
        canonical: "",
        family: SlugFamily::KaeritenSingle,
        accepts_param: false,
        doc: "返り点 一",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "",
        family: SlugFamily::KaeritenSingle,
        accepts_param: false,
        doc: "返り点 二",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "",
        family: SlugFamily::KaeritenSingle,
        accepts_param: false,
        doc: "返り点 三",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "",
        family: SlugFamily::KaeritenSingle,
        accepts_param: false,
        doc: "返り点 四",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "",
        family: SlugFamily::KaeritenSingle,
        accepts_param: false,
        doc: "返り点 上",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "",
        family: SlugFamily::KaeritenSingle,
        accepts_param: false,
        doc: "返り点 中",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "",
        family: SlugFamily::KaeritenSingle,
        accepts_param: false,
        doc: "返り点 下",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "",
        family: SlugFamily::KaeritenSingle,
        accepts_param: false,
        doc: "返り点 甲",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "",
        family: SlugFamily::KaeritenSingle,
        accepts_param: false,
        doc: "返り点 乙",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "",
        family: SlugFamily::KaeritenSingle,
        accepts_param: false,
        doc: "返り点 丙",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "",
        family: SlugFamily::KaeritenSingle,
        accepts_param: false,
        doc: "返り点 丁",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "",
        family: SlugFamily::KaeritenSingle,
        accepts_param: false,
        doc: "返り点 レ",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    // --- Kaeriten compound (6) --------------------------------------------
    SlugEntry {
        canonical: "一レ",
        family: SlugFamily::KaeritenCompound,
        accepts_param: false,
        doc: "返り点 一レ",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "二レ",
        family: SlugFamily::KaeritenCompound,
        accepts_param: false,
        doc: "返り点 二レ",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "三レ",
        family: SlugFamily::KaeritenCompound,
        accepts_param: false,
        doc: "返り点 三レ",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "上レ",
        family: SlugFamily::KaeritenCompound,
        accepts_param: false,
        doc: "返り点 上レ",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "中レ",
        family: SlugFamily::KaeritenCompound,
        accepts_param: false,
        doc: "返り点 中レ",
        partner: None,
        wrapper: PairKind::Bracket,
    },
    SlugEntry {
        canonical: "下レ",
        family: SlugFamily::KaeritenCompound,
        accepts_param: false,
        doc: "返り点 下レ",
        partner: None,
        wrapper: PairKind::Bracket,
    },
];

/// Variant → canonical mapping for [`canonicalise_slug`]. Each row
/// covers one common abbreviation or hiragana spelling that the LSP
/// snaps to the canonical form. Identity rows (`canonical → canonical`)
/// are inserted automatically by [`canonicalise_slug`] so this table
/// only needs the *non-trivial* variants.
const VARIANTS: &[(&str, &str)] = &[
    // Bouten — hiragana variants commonly typed in drafts.
    ("ぼうてん", "傍点"),
    ("にぼうてん", "傍点"),
    ("しろぼうてん", "白ゴマ傍点"),
    ("しろごまぼうてん", "白ゴマ傍点"),
    ("まるぼうてん", "丸傍点"),
    ("にまるぼうてん", "丸傍点"),
    ("しろまるぼうてん", "白丸傍点"),
    ("にしろまるぼうてん", "白丸傍点"),
    ("にじゅうまるぼうてん", "二重丸傍点"),
    ("じゃのめぼうてん", "蛇の目傍点"),
    ("ばつぼうてん", "ばつ傍点"),
    ("しろさんかくぼうてん", "白三角傍点"),
    ("はせん", "波線"),
    ("ぼうせん", "傍線"),
    ("にじゅうぼうせん", "二重傍線"),
    // Page break.
    ("かいぺーじ", "改ページ"),
    ("ページかえ", "改ページ"),
    ("かいちょう", "改丁"),
    ("かいだん", "改段"),
    ("かいみひらき", "改見開き"),
    // Block container open / close.
    ("ここからじさげ", "ここから字下げ"),
    ("ここでじさげおわり", "ここで字下げ終わり"),
    ("ここからじつき", "ここから地付き"),
    ("ここでじつきおわり", "ここで地付き終わり"),
    // Leaf align.
    ("じつき", "地付き"),
    // Other inline.
    ("たてちゅうよこ", "縦中横"),
    ("たて中横", "縦中横"),
    ("そうにゅうえ", "挿絵({path})入る"),
    // Framed / warichu.
    ("けいがこみ", "罫囲み"),
    ("けいがこみおわり", "罫囲み終わり"),
    ("わりちゅう", "割り注"),
    ("わりちゅうおわり", "割り注終わり"),
];

/// Snap an input slug body (with the surrounding `[# … ]` already
/// stripped) to the canonical form, if one is recognised.
///
/// Returns:
/// - `Some(s)` — `s` is the canonical text. `s` is `&'static str`
///   pointing into [`SLUGS`]'s `canonical` field, so callers can use
///   it as a stable key.
/// - `None` — no recognised slug. Callers may still parse `input` as a
///   `{N}字下げ` parametric form (which intentionally has no fixed
///   variant).
///
/// Identity rows are accepted: passing a canonical string back returns
/// the same pointer. This lets the LSP's `canonicalize` code action
/// short-circuit safely.
#[must_use]
pub(crate) fn canonicalise_slug(input: &str) -> Option<&'static str> {
    // Identity short-circuit. SLUGS is small (~40 entries) and the
    // strings are short, so a linear scan beats hashing on cache cost.
    for entry in SLUGS {
        if entry.canonical == input {
            return Some(entry.canonical);
        }
    }
    for &(variant, canonical) in VARIANTS {
        if variant == input {
            return Some(canonical);
        }
    }
    None
}

/// One row of the *render* slug table.
///
/// The single source of truth for the romaji CSS slug emitted for a
/// given annotation. Kept separate from the completion catalogue
/// catalogue) because render slugs key on the enum *keyword* (傍点 kind
/// / emphasis kind / section kind), a vocabulary the completion table
/// does not carry.
///
/// `roman` is the stable kebab-case CSS slug. `reading` is the kana the
/// slug romanises (Hepburn, long vowels dropped — 改丁/かいちょう →
/// `kaicho`); `None` marks a loanword kept in English (改ページ →
/// `page-break`, キャプション → `caption`) which has no reading-derived
/// spelling to check. `jis` cites the JIS Z 8125:2004 clause the term
/// is reconciled against, where one exists.
///
/// The `render_slug_matches_reading` test re-derives Hepburn from
/// `reading` and asserts it agrees with `roman`, so a slug that drifts
/// from its reading — 小書き is こがき (→ `kogaki`), not the over-long
/// spelling once shipped — cannot reappear.
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "json", derive(serde::Serialize, serde::Deserialize))]
pub(crate) struct RenderSlug {
    /// Canonical Japanese keyword (matches the enum→keyword tables in
    /// the syntax layer), used as the lookup key.
    pub canonical: &'static str,
    /// Kana the slug romanises, or `None` for an English loanword slug.
    #[cfg_attr(
        all(not(test), not(feature = "json")),
        expect(
            dead_code,
            reason = "reading metadata is consumed by wire generation and catalogue validation"
        )
    )]
    pub reading: Option<&'static str>,
    /// Stable kebab-case CSS slug.
    pub roman: &'static str,
    /// JIS Z 8125:2004 clause, where the term is standardised.
    #[cfg_attr(
        all(not(test), not(feature = "json")),
        expect(
            dead_code,
            reason = "standards metadata is consumed by wire generation and catalogue validation"
        )
    )]
    pub jis: Option<&'static str>,
}

/// The render slug catalogue — the single source of truth for romaji
/// CSS slugs. See [`RenderSlug`].
pub(crate) const RENDER_SLUGS: &[RenderSlug] = &[
    // --- Section / page break (JIS Z 8125:2004 §07.24) ---------------------
    RenderSlug {
        canonical: "改丁",
        reading: Some("かいちょう"),
        roman: "kaicho",
        jis: Some("07.24.12"),
    },
    RenderSlug {
        canonical: "改段",
        reading: Some("かいだん"),
        roman: "kaidan",
        jis: Some("07.24.14"),
    },
    RenderSlug {
        canonical: "改見開き",
        reading: Some("かいみひらき"),
        roman: "kaimihiraki",
        jis: Some("07.24.01"),
    },
    RenderSlug {
        canonical: "改ページ",
        reading: None,
        roman: "page-break",
        jis: Some("07.24.13"),
    },
    // --- Bouten kinds (圏点 JIS Z 8125:2004 §07.16) ------------------------
    RenderSlug {
        canonical: "傍点",
        reading: Some("ごま"),
        roman: "goma",
        jis: Some("07.16"),
    },
    RenderSlug {
        canonical: "白ゴマ傍点",
        reading: Some("しろごま"),
        roman: "shirogoma",
        jis: Some("07.16"),
    },
    RenderSlug {
        canonical: "丸傍点",
        reading: Some("まる"),
        roman: "maru",
        jis: Some("07.16"),
    },
    RenderSlug {
        canonical: "白丸傍点",
        reading: Some("しろまる"),
        roman: "shiromaru",
        jis: Some("07.16"),
    },
    RenderSlug {
        canonical: "二重丸傍点",
        reading: Some("にじゅうまる"),
        roman: "nijumaru",
        jis: Some("07.16"),
    },
    RenderSlug {
        canonical: "蛇の目傍点",
        reading: Some("じゃのめ"),
        roman: "janome",
        jis: Some("07.16"),
    },
    RenderSlug {
        canonical: "ばつ傍点",
        reading: Some("ばつ"),
        roman: "batsu",
        jis: Some("07.16"),
    },
    RenderSlug {
        canonical: "白三角傍点",
        reading: Some("しろさんかく"),
        roman: "shirosankaku",
        jis: Some("07.16"),
    },
    RenderSlug {
        canonical: "波線",
        reading: Some("なみせん"),
        roman: "namisen",
        jis: None,
    },
    RenderSlug {
        canonical: "傍線",
        reading: Some("ぼうせん"),
        roman: "bosen",
        jis: None,
    },
    RenderSlug {
        canonical: "二重傍線",
        reading: Some("にじゅうぼうせん"),
        roman: "nijubosen",
        jis: None,
    },
    RenderSlug {
        canonical: "鎖線",
        reading: Some("くさりせん"),
        roman: "kusarisen",
        jis: None,
    },
    RenderSlug {
        canonical: "破線",
        reading: Some("はせん"),
        roman: "hasen",
        jis: None,
    },
    RenderSlug {
        canonical: "黒三角傍点",
        reading: Some("くろさんかく"),
        roman: "kurosankaku",
        jis: Some("07.16"),
    },
    // --- Emphasis / inline ---------------------------------------------------
    // The emphasis family now uses reading-based romaji slugs (#115),
    // matching the bouten kinds (#114): the slug is `hepburn(reading)`,
    // enforced by `render_slug_matches_reading`. Two stay on their existing
    // slugs deliberately — `caption` (a loanword, キャプション) and
    // `keigakomi` (罫囲み=けいがこみ, a valid reading already serving as the
    // wire/API identifier). The slug is the CSS class only (`aozora-<slug>`);
    // the wire `as_json_tag` is a separate, frozen vocabulary.
    RenderSlug {
        canonical: "斜体",
        reading: Some("しゃたい"),
        roman: "shatai",
        jis: None,
    },
    RenderSlug {
        canonical: "太字",
        reading: Some("ふとじ"),
        roman: "futoji",
        jis: None,
    },
    // ゴシック体 — gothic typeface, distinct from 太字 (#435). ゴシック is a
    // loanword (gothic), so `reading: None` opts out of the Hepburn check like
    // `caption`; the slug is the fixed CSS class `aozora-goshikku`.
    RenderSlug {
        canonical: "ゴシック体",
        reading: None,
        roman: "goshikku",
        jis: None,
    },
    RenderSlug {
        canonical: "上付き小文字",
        reading: Some("うわつき"),
        roman: "uwatsuki",
        jis: Some("07.12.01"),
    },
    RenderSlug {
        canonical: "下付き小文字",
        reading: Some("したつき"),
        roman: "shitatsuki",
        jis: Some("07.12.02"),
    },
    // 分数 (`「a/b」は分数`). `reading: None` opts out of the Hepburn
    // re-derivation check — ぶんすう romanises with a long vowel (bunsū),
    // which would not match the stable `bunsu` slug.
    RenderSlug {
        canonical: "分数",
        reading: None,
        roman: "bunsu",
        jis: None,
    },
    // 絶対サイズ (特大 / 大 / 中 / 小文字). Semantic English slugs (not Hepburn,
    // so `reading: None`), distinct from the relative `font-larger`/`smaller`.
    RenderSlug {
        canonical: "特大文字",
        reading: None,
        roman: "font-extra-large",
        jis: None,
    },
    RenderSlug {
        canonical: "大文字",
        reading: None,
        roman: "font-large",
        jis: None,
    },
    RenderSlug {
        canonical: "中文字",
        reading: None,
        roman: "font-medium",
        jis: None,
    },
    RenderSlug {
        canonical: "小文字",
        reading: None,
        roman: "font-small",
        jis: None,
    },
    RenderSlug {
        canonical: "行右小書き",
        reading: Some("こがき"),
        roman: "kogaki-right",
        jis: None,
    },
    RenderSlug {
        canonical: "行左小書き",
        reading: Some("こがき"),
        roman: "kogaki-left",
        jis: None,
    },
    RenderSlug {
        canonical: "罫囲み",
        reading: None,
        roman: "keigakomi-inline",
        jis: None,
    },
    RenderSlug {
        canonical: "横組み",
        reading: Some("よこぐみ"),
        roman: "yokogumi",
        jis: None,
    },
    RenderSlug {
        canonical: "キャプション",
        reading: None,
        roman: "caption",
        jis: None,
    },
];

/// Look up the romaji CSS slug for an annotation `canonical` keyword.
/// Returns `None` for an unknown keyword (callers fall back to a
/// neutral slug).
#[must_use]
pub(crate) fn roman_slug(canonical: &str) -> Option<&'static str> {
    RENDER_SLUGS
        .iter()
        .find(|e| e.canonical == canonical)
        .map(|e| e.roman)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pipeline::lex;
    use crate::spec::codes;

    #[test]
    fn slug_family_wire_tags_complete_and_distinct() {
        assert_eq!(
            SlugFamily::ALL.len(),
            12,
            "every SlugFamily variant listed in ALL"
        );
        let mut tags: Vec<&str> = SlugFamily::ALL.iter().map(|&f| f.as_json_tag()).collect();
        for t in &tags {
            assert!(!t.is_empty(), "empty wire tag");
            assert_ne!(*t, "unknown", "wire tag must not be a fallback");
        }
        let total = tags.len();
        tags.sort_unstable();
        tags.dedup();
        assert_eq!(tags.len(), total, "duplicate wire tag in SlugFamily::ALL");
    }

    /// Minimal Hepburn romaniser (long vowel お/う段 + う dropped,
    /// matching the slug convention 改丁→`kaicho`). Test-only — the
    /// production slugs are hand-written in [`RENDER_SLUGS`]; this
    /// re-derives them from `reading` to catch a misspelling.
    #[expect(
        clippy::too_many_lines,
        reason = "exhaustive kana→romaji morae tables read clearest inline"
    )]
    fn hepburn(kana: &str) -> String {
        const TWO: &[(&str, &str)] = &[
            ("きゃ", "kya"),
            ("きゅ", "kyu"),
            ("きょ", "kyo"),
            ("しゃ", "sha"),
            ("しゅ", "shu"),
            ("しょ", "sho"),
            ("ちゃ", "cha"),
            ("ちゅ", "chu"),
            ("ちょ", "cho"),
            ("にゃ", "nya"),
            ("にゅ", "nyu"),
            ("にょ", "nyo"),
            ("ひゃ", "hya"),
            ("ひゅ", "hyu"),
            ("ひょ", "hyo"),
            ("みゃ", "mya"),
            ("みゅ", "myu"),
            ("みょ", "myo"),
            ("りゃ", "rya"),
            ("りゅ", "ryu"),
            ("りょ", "ryo"),
            ("ぎゃ", "gya"),
            ("ぎゅ", "gyu"),
            ("ぎょ", "gyo"),
            ("じゃ", "ja"),
            ("じゅ", "ju"),
            ("じょ", "jo"),
            ("びゃ", "bya"),
            ("びゅ", "byu"),
            ("びょ", "byo"),
            ("ぴゃ", "pya"),
            ("ぴゅ", "pyu"),
            ("ぴょ", "pyo"),
        ];
        const ONE: &[(&str, &str)] = &[
            ("", "a"),
            ("", "i"),
            ("", "u"),
            ("", "e"),
            ("", "o"),
            ("", "ka"),
            ("", "ki"),
            ("", "ku"),
            ("", "ke"),
            ("", "ko"),
            ("", "ga"),
            ("", "gi"),
            ("", "gu"),
            ("", "ge"),
            ("", "go"),
            ("", "sa"),
            ("", "shi"),
            ("", "su"),
            ("", "se"),
            ("", "so"),
            ("", "za"),
            ("", "ji"),
            ("", "zu"),
            ("", "ze"),
            ("", "zo"),
            ("", "ta"),
            ("", "chi"),
            ("", "tsu"),
            ("", "te"),
            ("", "to"),
            ("", "da"),
            ("", "ji"),
            ("", "zu"),
            ("", "de"),
            ("", "do"),
            ("", "na"),
            ("", "ni"),
            ("", "nu"),
            ("", "ne"),
            ("", "no"),
            ("", "ha"),
            ("", "hi"),
            ("", "fu"),
            ("", "he"),
            ("", "ho"),
            ("", "ba"),
            ("", "bi"),
            ("", "bu"),
            ("", "be"),
            ("", "bo"),
            ("", "pa"),
            ("", "pi"),
            ("", "pu"),
            ("", "pe"),
            ("", "po"),
            ("", "ma"),
            ("", "mi"),
            ("", "mu"),
            ("", "me"),
            ("", "mo"),
            ("", "ya"),
            ("", "yu"),
            ("", "yo"),
            ("", "ra"),
            ("", "ri"),
            ("", "ru"),
            ("", "re"),
            ("", "ro"),
            ("", "wa"),
            ("", "o"),
            ("", "n"),
        ];
        let mut out = String::new();
        let mut rest = kana;
        'outer: while !rest.is_empty() {
            // Long-vowel う after an o/u sound collapses (ちょう→cho).
            if let Some(r) = rest.strip_prefix('')
                && (out.ends_with('o') || out.ends_with('u'))
            {
                rest = r;
                continue;
            }
            for (k, v) in TWO {
                if let Some(r) = rest.strip_prefix(k) {
                    out.push_str(v);
                    rest = r;
                    continue 'outer;
                }
            }
            for (k, v) in ONE {
                if let Some(r) = rest.strip_prefix(k) {
                    out.push_str(v);
                    rest = r;
                    continue 'outer;
                }
            }
            // Unknown kana — surface it so the test fails loudly.
            return format!("{out}?{rest}");
        }
        out
    }

    #[test]
    fn render_slugs_are_kebab_ascii() {
        for e in RENDER_SLUGS {
            assert!(
                !e.roman.is_empty()
                    && e.roman
                        .bytes()
                        .all(|b| b.is_ascii_lowercase() || b == b'-' || b.is_ascii_digit()),
                "non-kebab render slug: {:?}",
                e.roman
            );
        }
    }

    #[test]
    fn render_slugs_are_unique() {
        let mut seen: Vec<&'static str> = Vec::with_capacity(RENDER_SLUGS.len());
        for e in RENDER_SLUGS {
            assert!(
                !seen.contains(&e.roman),
                "duplicate render slug: {}",
                e.roman
            );
            seen.push(e.roman);
        }
    }

    #[test]
    fn render_slug_readings_are_hiragana() {
        for e in RENDER_SLUGS {
            if let Some(r) = e.reading {
                assert!(
                    r.chars().all(|c| ('\u{3040}'..='\u{309F}').contains(&c)),
                    "reading not hiragana: {r} ({})",
                    e.canonical
                );
            }
        }
    }

    #[test]
    fn render_slug_matches_reading() {
        for e in RENDER_SLUGS {
            let Some(reading) = e.reading else { continue };
            let h = hepburn(reading);
            let ok = e.roman == h
                || e.roman
                    .strip_prefix(&h)
                    .is_some_and(|rest| rest.starts_with('-'));
            assert!(
                ok,
                "render slug {:?} (canonical {}) inconsistent with reading {reading} → hepburn {h}",
                e.roman, e.canonical
            );
        }
    }

    #[test]
    fn render_slug_jis_clauses_are_numeric() {
        for entry in RENDER_SLUGS {
            if let Some(clause) = entry.jis {
                assert!(
                    clause.split('.').all(|component| !component.is_empty()
                        && component.bytes().all(|b| b.is_ascii_digit())),
                    "invalid JIS clause: {clause}"
                );
            }
        }
    }

    #[test]
    fn roman_slug_looks_up_and_misses() {
        assert_eq!(roman_slug("行右小書き"), Some("kogaki-right"));
        assert_eq!(roman_slug("白ゴマ傍点"), Some("shirogoma"));
        assert_eq!(roman_slug("改丁"), Some("kaicho"));
        assert_eq!(roman_slug("nonsense"), None);
    }

    #[test]
    fn slugs_table_is_non_empty() {
        assert!(!SLUGS.is_empty());
    }

    #[test]
    fn slugs_have_unique_canonical_strings() {
        let mut seen: Vec<&'static str> = Vec::with_capacity(SLUGS.len());
        for entry in SLUGS {
            assert!(
                !seen.contains(&entry.canonical),
                "duplicate canonical: {}",
                entry.canonical
            );
            seen.push(entry.canonical);
        }
    }

    #[test]
    fn every_canonical_is_self_canonical() {
        for entry in SLUGS {
            let resolved = canonicalise_slug(entry.canonical)
                .unwrap_or_else(|| panic!("canonical {} did not resolve", entry.canonical));
            assert_eq!(resolved, entry.canonical);
        }
    }

    #[test]
    fn known_hiragana_variants_resolve_to_canonical() {
        assert_eq!(canonicalise_slug("ぼうてん"), Some("傍点"));
        assert_eq!(canonicalise_slug("にぼうてん"), Some("傍点"));
        assert_eq!(canonicalise_slug("しろまるぼうてん"), Some("白丸傍点"));
        assert_eq!(canonicalise_slug("ここからじさげ"), Some("ここから字下げ"));
    }

    #[test]
    fn unknown_input_returns_none() {
        assert_eq!(canonicalise_slug("nonsense"), None);
        assert_eq!(canonicalise_slug(""), None);
    }

    #[test]
    fn paired_slugs_reference_existing_partner() {
        for entry in SLUGS {
            if let Some(partner) = entry.partner {
                let found = SLUGS.iter().any(|e| e.canonical == partner);
                assert!(
                    found,
                    "partner {partner} not in SLUGS for {}",
                    entry.canonical
                );
            }
        }
    }

    #[test]
    fn block_container_open_pairs_with_close() {
        // Every BlockContainerOpen entry must point at a partner whose
        // family is BlockContainerClose, and vice versa.
        for entry in SLUGS {
            match entry.family {
                SlugFamily::BlockContainerOpen => {
                    let partner_canonical = entry
                        .partner
                        .unwrap_or_else(|| panic!("open {} has no partner", entry.canonical));
                    let partner = SLUGS
                        .iter()
                        .find(|e| e.canonical == partner_canonical)
                        .expect("partner exists");
                    assert!(matches!(
                        partner.family,
                        SlugFamily::BlockContainerClose | SlugFamily::Framed | SlugFamily::Warichu
                    ));
                }
                SlugFamily::BlockContainerClose => {
                    let partner_canonical = entry
                        .partner
                        .unwrap_or_else(|| panic!("close {} has no partner", entry.canonical));
                    let partner = SLUGS
                        .iter()
                        .find(|e| e.canonical == partner_canonical)
                        .expect("partner exists");
                    assert!(matches!(
                        partner.family,
                        SlugFamily::BlockContainerOpen | SlugFamily::Framed | SlugFamily::Warichu
                    ));
                }
                _ => {}
            }
        }
    }

    #[test]
    fn accepts_param_aligns_with_brace_in_canonical() {
        // Every entry whose canonical contains `{` must have
        // accepts_param == true, and vice versa.
        for entry in SLUGS {
            let has_brace = entry.canonical.contains('{');
            assert_eq!(
                entry.accepts_param, has_brace,
                "accepts_param/brace mismatch on {}",
                entry.canonical
            );
        }
    }

    #[test]
    fn variant_table_resolves_to_strings_in_slugs() {
        for &(variant, canonical) in VARIANTS {
            assert!(
                SLUGS.iter().any(|e| e.canonical == canonical),
                "variant {variant} maps to unknown canonical {canonical}"
            );
        }
    }

    /// Substitute placeholder tokens in a slug's canonical text with a
    /// concrete value, so the wrapped body actually parses.
    fn instantiate(canonical: &str) -> String {
        canonical.replace("{N}", "2").replace("{path}", "fig01.png")
    }

    /// Wrap an instantiated slug body in the source form a real document
    /// would carry, picked by family. Forward-reference families
    /// ([`SlugFamily::Bouten`] / [`SlugFamily::CombineUpright`]) attach to
    /// a preceding inline target, so they need the `[#「対象」に…]` /
    /// `[#「対象」は…]` shape rather than a bare `[#…]`.
    fn wrap_for_family(family: SlugFamily, body: &str) -> String {
        match family {
            SlugFamily::Bouten => format!("対象[#「対象」に{body}"),
            SlugFamily::CombineUpright => format!("対象[#「対象」は{body}"),
            _ => format!("[#{body}"),
        }
    }

    /// SLUGS ↔ classifier sync guard: every canonical slug in the
    /// editor-side [`SLUGS`] table must round-trip through the live
    /// classify stage without leaving a residual annotation marker — i.e.
    /// the classifier recognises the slug and lands it in the placeholder
    /// registry rather than leaking it through as plain text. A
    /// [`codes::RESIDUAL_ANNOTATION_MARKER`] diagnostic on any entry means
    /// [`SLUGS`] has drifted out of sync with `classify::BODY_PATTERNS`.
    #[test]
    fn every_canonical_slug_parses_without_residual_marker() {
        for entry in SLUGS {
            let body = instantiate(entry.canonical);
            let source = wrap_for_family(entry.family, &body);
            let out = lex(&source);
            for diag in &out.diagnostics {
                assert!(
                    diag.code() != codes::RESIDUAL_ANNOTATION_MARKER,
                    "canonical slug {} (instantiated: {body}) leaked through as a residual \
                     annotation marker; source = {source}",
                    entry.canonical
                );
            }
        }
    }
}