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
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
//! Source-driven projection from a [`Snapshot`] to a
//! [`pandoc_ast::Pandoc`] document.
//!
//! Walks the source linearly, slicing it into spans by the owned
//! `source_nodes` side-table. Plain runs flow into Pandoc inlines
//! verbatim (with `\n\n` paragraph splits and single `\n` →
//! `SoftBreak`). Each classified node lifts to a Pandoc inline /
//! block construct as documented in [`crate`]. Payload text is resolved
//! through the output's [`NodeStore`].

use pandoc_ast::{Attr, Block, Inline, Pandoc};

use crate::pandoc::AOZORA_CLASS_PREFIX;
use crate::spec::roman_slug;
#[cfg(test)]
use crate::syntax::ast::ForwardPayload;
use crate::syntax::ast::{
    AngleQuote, Content, ContentRange, Directive, ForwardFormat, Gaiji, Heading, HeadingHint,
    Illustration, Kaeriten, MarginNote, Node, NodeRef, NodeStore, Ruby, Segment, SourceNode,
};
use crate::syntax::format::Format;
use crate::syntax::{
    AbsoluteSize, AccentMark, BoutenPosition, DirectiveKind, EnclosureKind, FontShift, ForwardAttr,
    ForwardOrigin, HeadingKind, HeadingStyle, IndentBlock, IndentLayout, LineFormat, RegionFormat,
    SectionKind,
};
use crate::{Snapshot, Span};

/// Lift a parsed [`Snapshot`] to a [`pandoc_ast::Pandoc`] document.
///
/// See the crate-level docs for the projection rules.
#[must_use]
pub fn to_pandoc(snapshot: &Snapshot) -> Pandoc {
    let out = snapshot.output();
    // `source_nodes` index into the sanitize-stage buffer, not the raw
    // user-supplied source. The owned lex output carries exactly that buffer
    // in `sanitized`, so the slice base already matches the source-node
    // coordinate system — no re-sanitize is needed.
    let mut converter = Converter::new(&out.sanitized, &out.source_nodes, &out.store);
    converter.run();
    Pandoc {
        meta: pandoc_ast::Map::new(),
        blocks: converter.blocks,
        // The pandoc 3.x JSON API version. `pandoc_ast` accepts 1.20 or
        // newer, so an older reader still parses this output.
        pandoc_api_version: vec![1, 23],
    }
}

// ---------------------------------------------------------------------
// Walker
// ---------------------------------------------------------------------

/// Block-context frame. The implicit outermost frame is the document
/// root; each container open pushes a new frame, container close
/// pops and wraps the accumulated blocks in a Pandoc Div.
struct Frame {
    /// Closed blocks accumulated under this container (Para nodes
    /// emitted as inline runs flush, plus block-leaf children).
    blocks: Vec<Block>,
    /// In-flight inline accumulator for the current paragraph.
    /// `None` means "no open paragraph" (after a flush).
    inlines: Option<Vec<Inline>>,
    /// Container kind for the wrapping `Div` (if any). The root
    /// frame carries `None`.
    container: Option<RegionFormat>,
}

impl Frame {
    fn root() -> Self {
        Self {
            blocks: Vec::new(),
            inlines: None,
            container: None,
        }
    }

    fn child(kind: RegionFormat) -> Self {
        Self {
            blocks: Vec::new(),
            inlines: None,
            container: Some(kind),
        }
    }

    fn paragraph(&mut self) -> &mut Vec<Inline> {
        self.inlines.get_or_insert_with(Vec::new)
    }

    /// Close the in-flight paragraph (if any). Trailing whitespace
    /// is trimmed by Pandoc's writer; we keep the Inline list as-is.
    fn flush_paragraph(&mut self) {
        if let Some(inlines) = self.inlines.take()
            && !inlines.is_empty()
        {
            self.blocks.push(Block::Para(inlines));
        }
    }
}

struct Converter<'src> {
    source: &'src str,
    nodes: &'src [SourceNode],
    /// Backing store the owned nodes' `StrId` / range payloads resolve against.
    store: &'src NodeStore,
    /// Stack of block frames. Always non-empty; the bottom frame is
    /// the document root.
    stack: Vec<Frame>,
    /// Cursor into `source` (byte offset).
    cursor: usize,
    /// Final document blocks, populated by [`Converter::run`] from
    /// the root frame on completion.
    blocks: Vec<Block>,
}

impl<'src> Converter<'src> {
    fn new(source: &'src str, nodes: &'src [SourceNode], store: &'src NodeStore) -> Self {
        Self {
            source,
            nodes,
            store,
            stack: vec![Frame::root()],
            cursor: 0,
            blocks: Vec::new(),
        }
    }

    fn run(&mut self) {
        for entry in self.nodes {
            // Plain run between previous cursor and this node.
            self.flush_plain(entry.source_span.start as usize);
            self.dispatch_node(entry);
            self.cursor = entry.source_span.end as usize;
        }
        self.flush_plain(self.source.len());
        // Pop any unclosed containers (defensive — well-formed input
        // never reaches here, but unclosed-bracket diagnostics let
        // the document still parse).
        while self.stack.len() > 1 {
            let frame = self.stack.pop().expect("non-empty stack");
            self.close_frame(frame);
        }
        let mut root = self.stack.pop().expect("root frame");
        root.flush_paragraph();
        self.blocks = root.blocks;
    }

    /// Push the slice of plain text between `cursor` and `end` into
    /// the current paragraph. `\n\n` boundaries close the paragraph
    /// and open a fresh one; single `\n` becomes a `SoftBreak`.
    fn flush_plain(&mut self, end: usize) {
        if end <= self.cursor {
            return;
        }
        let chunk = &self.source[self.cursor..end];
        for (idx, line) in chunk.split('\n').enumerate() {
            if idx > 0 {
                // Blank line (preceded by another `\n`) closes the
                // paragraph; non-blank line emits a soft break.
                if line.is_empty() {
                    self.current_frame_mut().flush_paragraph();
                } else {
                    self.current_frame_mut().paragraph().push(Inline::SoftBreak);
                }
            }
            if !line.is_empty() {
                self.current_frame_mut()
                    .paragraph()
                    .push(Inline::Str(line.to_owned()));
            }
        }
        self.cursor = end;
    }

    fn current_frame_mut(&mut self) -> &mut Frame {
        self.stack.last_mut().expect("stack always non-empty")
    }

    fn dispatch_node(&mut self, entry: &SourceNode) {
        match entry.node {
            NodeRef::Inline(node) => self.dispatch_inline_node(node, entry.source_span),
            NodeRef::BlockLeaf(node) => self.dispatch_block_leaf(node, entry.source_span),
            NodeRef::BlockOpen(kind) => self.open_container(kind),
            NodeRef::BlockClose(_) => self.close_container(),
        }
    }

    fn dispatch_inline_node(&mut self, node: Node, _span: Span) {
        if let Some(inline) = node_inline(node, self.store) {
            self.current_frame_mut().paragraph().push(inline);
        }
    }

    fn dispatch_block_leaf(&mut self, node: Node, _span: Span) {
        use Node as N;
        // Block-leaf nodes close any in-flight paragraph and emit a
        // standalone block.
        self.current_frame_mut().flush_paragraph();
        let store = self.store;
        let block = match node {
            N::PageBreak => Block::HorizontalRule,
            // 本文終わり — a distinct structural marker Div (a colophon follows).
            N::BodyEnd => Block::Div(
                (
                    String::new(),
                    vec![format!("{AOZORA_CLASS_PREFIX}body-end")],
                    Vec::new(),
                ),
                Vec::new(),
            ),
            N::SectionBreak(k) => section_break_block(k),
            N::Heading(h) => aozora_heading_block(h, store),
            N::Illustration(s) => sashie_block(s, store),
            // Inline-typed variants here would mean the pipeline tagged
            // an inline node as a block leaf; emit them inside a singleton
            // Para so the document stays renderable.
            other => Block::Para(vec![Inline::Span(
                Attr::default(),
                vec![Inline::Str(format!("{other:?}"))],
            )]),
        };
        self.current_frame_mut().blocks.push(block);
    }

    fn open_container(&mut self, kind: RegionFormat) {
        // A new container starts a new block context; flush any
        // in-flight paragraph in the current frame first.
        self.current_frame_mut().flush_paragraph();
        self.stack.push(Frame::child(kind));
    }

    fn close_container(&mut self) {
        // Adversarial / malformed input can emit a BlockClose without
        // a matching open (the lex pipeline emits a diagnostic but
        // still surfaces the close in `source_nodes`). Popping the
        // root frame would leave the converter with an empty stack
        // and panic on the next `current_frame_mut`. Bottom-of-stack
        // is the document root, so we keep at least one frame.
        if self.stack.len() <= 1 {
            return;
        }
        let frame = self.stack.pop().expect("len > 1 above ⇒ pop yields Some");
        self.close_frame(frame);
    }

    fn close_frame(&mut self, mut frame: Frame) {
        frame.flush_paragraph();
        if let Some(kind) = frame.container {
            let div = Block::Div(container_attr(kind), frame.blocks);
            self.current_frame_mut().blocks.push(div);
        } else {
            // Closing the root frame is handled in `run` — getting
            // here means a stack-balance bug.
            self.current_frame_mut().blocks.extend(frame.blocks);
        }
    }
}

// ---------------------------------------------------------------------
// Per-variant inline / block builders
// ---------------------------------------------------------------------

fn class_attr(class: &str) -> Attr {
    (
        String::new(),
        vec![format!("{AOZORA_CLASS_PREFIX}{class}")],
        Vec::new(),
    )
}

fn class_attr_kv(class: &str, kvs: Vec<(String, String)>) -> Attr {
    (
        String::new(),
        vec![format!("{AOZORA_CLASS_PREFIX}{class}")],
        kvs,
    )
}

/// Resolve a [`ContentRange`] payload field (ruby base/reading, forward
/// target, …) to its Pandoc inlines.
fn content_range_to_inlines(range: ContentRange, store: &NodeStore) -> Vec<Inline> {
    let mut buf = Vec::new();
    for &content in store.resolve_content_range(range) {
        push_content_inlines(content, store, &mut buf);
    }
    buf
}

/// Resolve a bare [`Content`] payload field (warichu upper/lower,
/// sashie caption) to its Pandoc inlines.
fn content_to_inlines(content: Content, store: &NodeStore) -> Vec<Inline> {
    let mut buf = Vec::new();
    push_content_inlines(content, store, &mut buf);
    buf
}

fn push_content_inlines(content: Content, store: &NodeStore, buf: &mut Vec<Inline>) {
    match content {
        Content::Plain(id) => buf.push(Inline::Str(store.resolve_str(id).to_owned())),
        Content::Segments(range) => {
            for &seg in store.resolve_seg_range(range) {
                match seg {
                    Segment::Text(id) => {
                        buf.push(Inline::Str(store.resolve_str(id).to_owned()));
                    }
                    Segment::Gaiji(g) => buf.push(gaiji_inline(g, store)),
                    Segment::Directive(a) => buf.push(annotation_inline(a, store)),
                }
            }
        }
    }
}

fn node_inline(node: Node, store: &NodeStore) -> Option<Inline> {
    use Node as N;
    if let N::Format(f) = node
        && matches!(f.origin, ForwardOrigin::Referenced)
    {
        return None;
    }
    Some(match node {
        N::Ruby(r) => ruby_inline(r, store),
        N::MarginNote(s) => side_note_inline(s, store),
        N::Format(f) => format_inline(f, store),
        N::Gaiji(g) => gaiji_inline(g, store),
        N::Line(lf) => line_inline(lf),
        N::Directive(a) => annotation_inline(a, store),
        N::Kaeriten(k) => kaeriten_inline(k, store),
        N::AngleQuote(d) => angle_quote_inline(d, store),
        N::HeadingHint(h) => heading_hint_inline(h, store),
        N::ForcedBreak => Inline::LineBreak,
        other => Inline::Span(Attr::default(), vec![Inline::Str(format!("{other:?}"))]),
    })
}

fn ruby_inline(r: Ruby, store: &NodeStore) -> Inline {
    let base_inlines = content_range_to_inlines(r.base, store);
    let reading_inlines = content_range_to_inlines(r.reading, store);
    let inner = vec![
        Inline::Span(class_attr("ruby-base"), base_inlines),
        Inline::Span(class_attr("ruby-reading"), reading_inlines),
    ];
    Inline::Span(class_attr("ruby"), inner)
}

fn side_note_inline(s: MarginNote, store: &NodeStore) -> Inline {
    let base_inlines = content_range_to_inlines(s.base, store);
    let note_inlines = content_range_to_inlines(s.note, store);
    let inner = vec![
        Inline::Span(class_attr("sidenote-base"), base_inlines),
        Inline::Span(class_attr("sidenote-note"), note_inlines),
    ];
    Inline::Span(class_attr("sidenote"), inner)
}

/// Project a forward-reference emphasis node to its Pandoc inline.
///
/// Each `ForwardAttr` maps to the closest native Pandoc construct — 太字 →
/// [`Inline::Strong`], 斜体 → [`Inline::Emph`], 上付き / 下付き小文字 →
/// [`Inline::Superscript`] / [`Inline::Subscript`] — and every attribute with
/// no native equivalent (傍点 / 縦中横 / font size / 囲み / 小書き / accent / …)
/// to a classed [`Inline::Span`] carrying the structured data as key/value
/// attributes. Both cases resolve the decorated run's real text from
/// `f.target`, so no emphasis ever discards its content.
///
/// The match is exhaustive (no `_` arm): a new [`ForwardAttr`] variant is
/// compiler-flagged here rather than silently falling through to an empty or
/// debug placeholder.
fn format_inline(f: ForwardFormat, store: &NodeStore) -> Inline {
    let target = content_range_to_inlines(f.target, store);
    match f.attr {
        ForwardAttr::Bold => Inline::Strong(target),
        ForwardAttr::Italic => Inline::Emph(target),
        ForwardAttr::SuperScript => Inline::Superscript(target),
        ForwardAttr::SubScript => Inline::Subscript(target),
        // ゴシック体 is a typeface, not a weight; Pandoc has no native gothic, so
        // it stays a classed span distinct from 太字's `Strong`.
        ForwardAttr::Gothic => Inline::Span(class_attr("gothic"), target),
        ForwardAttr::Bouten { kind, position } => Inline::Span(
            class_attr_kv(
                "bouten",
                vec![
                    (
                        "kind".to_owned(),
                        roman_slug(kind.keyword()).unwrap_or("unknown").to_owned(),
                    ),
                    (
                        "position".to_owned(),
                        bouten_position_slug(position).to_owned(),
                    ),
                ],
            ),
            target,
        ),
        ForwardAttr::CombineUpright => Inline::Span(class_attr("tate-chu-yoko"), target),
        ForwardAttr::SmallScript(position) => Inline::Span(
            class_attr_kv(
                "small-script",
                vec![(
                    "position".to_owned(),
                    bouten_position_slug(position).to_owned(),
                )],
            ),
            target,
        ),
        ForwardAttr::Framed(kind) => Inline::Span(
            class_attr_kv(
                "enclosure",
                vec![("kind".to_owned(), enclosure_kind_slug(kind).to_owned())],
            ),
            target,
        ),
        ForwardAttr::Horizontal => Inline::Span(class_attr("horizontal"), target),
        ForwardAttr::Caption => Inline::Span(class_attr("caption"), target),
        // 文字サイズ carries a signed magnitude: the class names the direction
        // (larger / smaller) and the `steps` kv the stage count.
        ForwardAttr::FontSize(shift) => Inline::Span(
            class_attr_kv(
                font_size_class(shift),
                vec![("steps".to_owned(), shift.magnitude().to_string())],
            ),
            target,
        ),
        ForwardAttr::FontSizeAbsolute(size) => Inline::Span(
            class_attr_kv(
                "font-absolute",
                vec![("size".to_owned(), absolute_size_slug(size).to_owned())],
            ),
            target,
        ),
        ForwardAttr::Fraction => Inline::Span(class_attr("fraction"), target),
        ForwardAttr::AccentDot => Inline::Span(class_attr("accent-dot"), target),
        ForwardAttr::Accent(mark) => Inline::Span(
            class_attr_kv(
                "accent",
                vec![("mark".to_owned(), accent_mark_slug(mark).to_owned())],
            ),
            target,
        ),
        ForwardAttr::AlignEnd { offset } => Inline::Span(
            class_attr_kv("align-end", vec![("offset".to_owned(), offset.to_string())]),
            target,
        ),
    }
}

fn bouten_position_slug(p: BoutenPosition) -> &'static str {
    match p {
        BoutenPosition::Right => "right",
        BoutenPosition::Left => "left",
        BoutenPosition::Both => "both",
    }
}

/// `aozora-font-larger` / `aozora-font-smaller` — the class body for a relative
/// [`FontShift`], keyed on its sign (the magnitude rides a `steps` kv).
fn font_size_class(shift: FontShift) -> &'static str {
    if shift.larger() {
        "font-larger"
    } else {
        "font-smaller"
    }
}

fn enclosure_kind_slug(kind: EnclosureKind) -> &'static str {
    match kind {
        EnclosureKind::Rule => "rule",
        EnclosureKind::Box => "box",
        EnclosureKind::Circle => "circle",
        EnclosureKind::CircleDotted => "circle-dotted",
        EnclosureKind::DoubleRule => "double-rule",
    }
}

fn absolute_size_slug(size: AbsoluteSize) -> &'static str {
    match size {
        AbsoluteSize::ExtraLarge => "extra-large",
        AbsoluteSize::Large => "large",
        AbsoluteSize::Medium => "medium",
        AbsoluteSize::Small => "small",
    }
}

fn accent_mark_slug(mark: AccentMark) -> &'static str {
    match mark {
        AccentMark::Acute => "acute",
        AccentMark::Umlaut => "umlaut",
        AccentMark::Grave => "grave",
    }
}

fn gaiji_inline(g: Gaiji, store: &NodeStore) -> Inline {
    let mut kvs = vec![(
        "description".to_owned(),
        store.resolve_str(g.hint).to_owned(),
    )];
    if g.canonical.has_mencode() {
        let mut mencode = String::new();
        g.canonical
            .write_mencode(store, &mut mencode)
            .expect("write_mencode into String is infallible");
        kvs.push(("mencode".to_owned(), mencode));
    }
    let inner = g.resolve(store).map_or_else(
        || vec![Inline::Str("".to_owned())],
        |resolved| vec![Inline::Str(format!("{resolved:?}"))],
    );
    Inline::Span(class_attr_kv("gaiji", kvs), inner)
}

/// Project a single-line layout directive.
fn line_inline(lf: LineFormat) -> Inline {
    let attr = match lf {
        LineFormat::Indent { amount, end_offset } => {
            let mut kvs = vec![("amount".to_owned(), amount.to_string())];
            if let Some(offset) = end_offset {
                kvs.push(("offset".to_owned(), offset.to_string()));
            }
            class_attr_kv("indent", kvs)
        }
        LineFormat::AlignEnd { offset } => {
            class_attr_kv("align-end", vec![("offset".to_owned(), offset.to_string())])
        }
        LineFormat::Center { .. } => class_attr_kv("center", Vec::new()),
        _ => Attr::default(),
    };
    Inline::Span(attr, Vec::new())
}

fn annotation_inline(a: Directive, store: &NodeStore) -> Inline {
    Inline::Span(
        class_attr_kv(
            "annotation",
            vec![
                ("kind".to_owned(), annotation_kind_slug(a.kind).to_owned()),
                ("raw".to_owned(), store.resolve_str(a.raw).to_owned()),
            ],
        ),
        Vec::new(),
    )
}

fn annotation_kind_slug(k: DirectiveKind) -> &'static str {
    match k {
        DirectiveKind::NonCanonical => "non-canonical",
        DirectiveKind::Editorial => "editorial",
        DirectiveKind::Sic => "sic",
        DirectiveKind::BaseTextVariant => "base-text-variant",
        DirectiveKind::EditorNote => "editor-note",
        DirectiveKind::RubyAttached => "ruby-attached",
        DirectiveKind::RubyRetarget => "ruby-retarget",
        DirectiveKind::RubyPairOpen => "ruby-pair-open",
        DirectiveKind::RubyPairClose => "ruby-pair-close",
        DirectiveKind::MarginNotePairOpen => "margin-note-pair-open",
        DirectiveKind::MarginNotePairClose => "margin-note-pair-close",
        _ => "other",
    }
}

fn kaeriten_inline(k: Kaeriten, store: &NodeStore) -> Inline {
    Inline::Span(
        class_attr_kv(
            "kaeriten",
            vec![("mark".to_owned(), store.resolve_str(k.mark).to_owned())],
        ),
        Vec::new(),
    )
}

fn angle_quote_inline(d: AngleQuote, store: &NodeStore) -> Inline {
    Inline::Span(
        class_attr("angle-quote"),
        content_range_to_inlines(d.content, store),
    )
}

fn heading_hint_inline(h: HeadingHint, store: &NodeStore) -> Inline {
    let target = store.resolve_str(h.target).to_owned();
    // A self-contained (no-referent) hint shows its quoted target as the heading
    // text; a referent-present hint stays an empty marker.
    let content = if h.self_contained {
        vec![Inline::Str(target.clone())]
    } else {
        Vec::new()
    };
    Inline::Span(
        class_attr_kv(
            "heading-hint",
            vec![
                ("level".to_owned(), h.level.outline_level().to_string()),
                ("target".to_owned(), target),
            ],
        ),
        content,
    )
}

fn section_break_block(k: SectionKind) -> Block {
    let slug = roman_slug(k.keyword()).unwrap_or("other");
    Block::Div(
        (
            String::new(),
            vec![
                format!("{AOZORA_CLASS_PREFIX}section-break"),
                format!("{AOZORA_CLASS_PREFIX}section-break-{slug}"),
            ],
            Vec::new(),
        ),
        Vec::new(),
    )
}

fn aozora_heading_block(h: Heading, store: &NodeStore) -> Block {
    let level: i64 = match h.kind {
        HeadingKind::Large => 1,
        HeadingKind::Medium => 2,
        HeadingKind::Small => 3,
    };
    // `kind` (level) is always carried; `style` only for a non-standard
    // style, so a standard heading's projection is unchanged.
    let mut kv = vec![("kind".to_owned(), heading_kind_slug(h.kind).to_owned())];
    if let Some(style) = heading_style_slug(h.style) {
        kv.push(("style".to_owned(), style.to_owned()));
    }
    Block::Header(
        level,
        class_attr_kv("heading", kv),
        content_range_to_inlines(h.text, store),
    )
}

fn heading_kind_slug(k: HeadingKind) -> &'static str {
    match k {
        HeadingKind::Large => "large",
        HeadingKind::Medium => "medium",
        HeadingKind::Small => "small",
    }
}

/// Style modifier slug, or `None` for the standard style (which adds no
/// `style` attribute, keeping a standard heading's projection unchanged).
fn heading_style_slug(s: HeadingStyle) -> Option<&'static str> {
    match s {
        HeadingStyle::SameLine => Some("same-line"),
        HeadingStyle::Window => Some("window"),
        // Standard (and any future `#[non_exhaustive]` style) adds no attr.
        _ => None,
    }
}

fn sashie_block(s: Illustration, store: &NodeStore) -> Block {
    // The general form's leading description is the alt; otherwise the
    // keyword 挿絵 form's trailing 「caption」 is the next-best alt text.
    let alt = s.description.map_or_else(
        || {
            s.caption
                .map(|c| content_to_inlines(c, store))
                .unwrap_or_default()
        },
        |description| vec![Inline::Str(store.resolve_str(description).to_owned())],
    );
    let target = (store.resolve_str(s.file).to_owned(), String::new());
    Block::Para(vec![Inline::Image(class_attr("sashie"), alt, target)])
}

fn container_attr(kind: RegionFormat) -> Attr {
    let (slug, kvs): (&str, Vec<(String, String)>) = match kind {
        RegionFormat::Indent(IndentBlock {
            amount,
            wrap,
            center,
            layout,
            styles,
        }) => {
            let mut kvs = vec![("amount".to_owned(), amount.to_string())];
            if let Some(w) = wrap {
                kvs.push(("wrap".to_owned(), w.to_string()));
            }
            if center {
                kvs.push(("center".to_owned(), "true".to_owned()));
            }
            match layout {
                IndentLayout::Kumi(kumi) => {
                    kvs.push(("kumi-lines".to_owned(), kumi.lines.to_string()));
                    kvs.push(("kumi-width".to_owned(), kumi.width.to_string()));
                }
                IndentLayout::LineWidth(width) => {
                    kvs.push(("width".to_owned(), width.0.to_string()));
                }
                IndentLayout::None => {}
            }
            // #78 co-applied styles — a space-joined `modifiers` value (the
            // Format identity tags, canonical order), mirroring the HTML
            // class list. Open-ended: a new style adds a token, not a kv key.
            let modifiers: Vec<&str> = styles.iter_formats().map(Format::as_json_tag).collect();
            if !modifiers.is_empty() {
                kvs.push(("modifiers".to_owned(), modifiers.join(" ")));
            }
            ("container-indent", kvs)
        }
        RegionFormat::Warichu => ("container-warichu", Vec::new()),
        RegionFormat::Framed(_) => ("container-keigakomi", Vec::new()),
        RegionFormat::AlignEnd { offset } => (
            "container-align-end",
            vec![("offset".to_owned(), offset.to_string())],
        ),
        RegionFormat::Bouten { kind, position } => {
            let mut kvs = vec![(
                "variant".to_owned(),
                roman_slug(kind.keyword()).unwrap_or("unknown").to_owned(),
            )];
            match position {
                BoutenPosition::Left => {
                    kvs.push(("position".to_owned(), "left".to_owned()));
                }
                BoutenPosition::Both => {
                    kvs.push(("position".to_owned(), "both".to_owned()));
                }
                _ => {}
            }
            ("container-bouten", kvs)
        }
        _ => ("container-unknown", Vec::new()),
    };
    (
        String::new(),
        vec![format!("{AOZORA_CLASS_PREFIX}{slug}")],
        kvs,
    )
}

// ---------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Document;
    use crate::syntax::{BlockStyles, BoutenKind};

    #[test]
    fn wire_slugs_cover_every_projected_variant() {
        for (kind, expected) in [
            (EnclosureKind::Rule, "rule"),
            (EnclosureKind::Box, "box"),
            (EnclosureKind::Circle, "circle"),
            (EnclosureKind::CircleDotted, "circle-dotted"),
            (EnclosureKind::DoubleRule, "double-rule"),
        ] {
            assert_eq!(enclosure_kind_slug(kind), expected);
        }
        for (size, expected) in [
            (AbsoluteSize::ExtraLarge, "extra-large"),
            (AbsoluteSize::Large, "large"),
            (AbsoluteSize::Medium, "medium"),
            (AbsoluteSize::Small, "small"),
        ] {
            assert_eq!(absolute_size_slug(size), expected);
        }
        for (mark, expected) in [
            (AccentMark::Acute, "acute"),
            (AccentMark::Umlaut, "umlaut"),
            (AccentMark::Grave, "grave"),
        ] {
            assert_eq!(accent_mark_slug(mark), expected);
        }
    }

    /// Plain text round-trips into a single Pandoc Para of `Inline::Str`.
    #[test]
    fn plain_text_becomes_para() {
        let doc = Document::new("Hello, world.");
        let pandoc = to_pandoc(&doc.snapshot());
        assert_eq!(pandoc.blocks.len(), 1, "{:?}", pandoc.blocks);
        match &pandoc.blocks[0] {
            Block::Para(inlines) => match inlines.as_slice() {
                [Inline::Str(s)] => assert_eq!(s, "Hello, world."),
                other => panic!("expected single Str, got {other:?}"),
            },
            other => panic!("expected Para, got {other:?}"),
        }
    }

    /// `\n\n` splits into two Para blocks; single `\n` yields `SoftBreak`.
    #[test]
    fn double_newline_splits_paragraphs() {
        let doc = Document::new("One\nstill one.\n\nTwo.");
        let pandoc = to_pandoc(&doc.snapshot());
        let para_count = pandoc
            .blocks
            .iter()
            .filter(|b| matches!(b, Block::Para(_)))
            .count();
        assert_eq!(para_count, 2, "expected two paragraphs");
        if let Block::Para(inlines) = &pandoc.blocks[0] {
            assert!(
                inlines.iter().any(|i| matches!(i, Inline::SoftBreak)),
                "first para should carry a SoftBreak"
            );
        }
    }

    /// Ruby with explicit delimiter projects to a Span.aozora-ruby
    /// carrying base / reading sub-spans.
    #[test]
    fn ruby_projects_to_span() {
        let doc = Document::new("|青梅《おうめ》");
        let pandoc = to_pandoc(&doc.snapshot());
        let para = match &pandoc.blocks[0] {
            Block::Para(inlines) => inlines,
            other => panic!("expected Para, got {other:?}"),
        };
        let ruby = para
            .iter()
            .find_map(|i| match i {
                Inline::Span(attr, inlines)
                    if attr.1.iter().any(|c| c.contains("aozora-ruby"))
                        && !attr.1.iter().any(|c| c.contains("ruby-")) =>
                {
                    Some(inlines)
                }
                _ => None,
            })
            .expect("ruby span present");
        assert_eq!(ruby.len(), 2, "ruby span has base + reading children");
    }

    /// Page break closes the in-flight paragraph and emits an
    /// `HorizontalRule` block.
    #[test]
    fn page_break_emits_horizontal_rule() {
        let doc = Document::new("before\n[#改ページ]\nafter");
        let pandoc = to_pandoc(&doc.snapshot());
        assert!(
            pandoc
                .blocks
                .iter()
                .any(|b| matches!(b, Block::HorizontalRule)),
            "expected HorizontalRule for page break: {:?}",
            pandoc.blocks
        );
    }

    /// Container open / close wraps inner blocks in a Pandoc Div.
    #[test]
    fn indent_container_wraps_in_div() {
        let doc = Document::new(
            "outside\n\n\
             [#ここから2字下げ]\n\
             indented body\n\
             [#ここで字下げ終わり]\n\n\
             after",
        );
        let pandoc = to_pandoc(&doc.snapshot());
        let has_indent_div = pandoc.blocks.iter().any(|b| {
            matches!(
                b,
                Block::Div(attr, _)
                    if attr.1.iter().any(|c| c.contains("aozora-container-indent"))
            )
        });
        assert!(has_indent_div, "no indent Div: {:?}", pandoc.blocks);
    }

    // -----------------------------------------------------------------
    // Test helpers
    // -----------------------------------------------------------------

    /// Project `src` through the full pipeline and return the doc blocks.
    fn project(src: &str) -> Vec<Block> {
        let doc = Document::new(src);
        to_pandoc(&doc.snapshot()).blocks
    }

    /// Whether any class in `attr` ends with `suffix` (the `aozora-`
    /// prefix is constant; matching the tail keeps assertions stable).
    fn has_class(attr: &Attr, suffix: &str) -> bool {
        attr.1.iter().any(|c| c == &format!("aozora-{suffix}"))
    }

    /// Look up a key in an `Attr`'s key/value list.
    fn kv<'a>(attr: &'a Attr, key: &str) -> Option<&'a str> {
        attr.2
            .iter()
            .find(|(k, _)| k == key)
            .map(|(_, v)| v.as_str())
    }

    /// Find the first inline `Span` (recursively) whose class list carries
    /// `aozora-{suffix}`. Walks into nested inlines so a span buried in a
    /// `Para` is found.
    fn find_span<'a>(blocks: &'a [Block], suffix: &str) -> Option<(&'a Attr, &'a [Inline])> {
        fn walk_inlines<'a>(
            inlines: &'a [Inline],
            suffix: &str,
        ) -> Option<(&'a Attr, &'a [Inline])> {
            for inline in inlines {
                if let Inline::Span(attr, inner) = inline {
                    if has_class(attr, suffix) {
                        return Some((attr, inner.as_slice()));
                    }
                    if let Some(found) = walk_inlines(inner, suffix) {
                        return Some(found);
                    }
                }
            }
            None
        }
        fn walk_blocks<'a>(blocks: &'a [Block], suffix: &str) -> Option<(&'a Attr, &'a [Inline])> {
            for block in blocks {
                let found = match block {
                    Block::Para(inlines) | Block::Header(_, _, inlines) => {
                        walk_inlines(inlines, suffix)
                    }
                    Block::Div(_, inner) => walk_blocks(inner, suffix),
                    _ => None,
                };
                if found.is_some() {
                    return found;
                }
            }
            None
        }
        walk_blocks(blocks, suffix)
    }

    /// Find the first inline (recursively, into nested spans) satisfying
    /// `pred`. Walks `Para` / `Header` / `Div` blocks and every inline's
    /// children so a construct buried in a styled span is still found.
    fn find_inline(blocks: &[Block], pred: impl Fn(&Inline) -> bool + Copy) -> Option<&Inline> {
        fn walk_inlines(
            inlines: &[Inline],
            pred: impl Fn(&Inline) -> bool + Copy,
        ) -> Option<&Inline> {
            for inline in inlines {
                if pred(inline) {
                    return Some(inline);
                }
                let children = match inline {
                    Inline::Span(_, inner)
                    | Inline::Strong(inner)
                    | Inline::Emph(inner)
                    | Inline::Superscript(inner)
                    | Inline::Subscript(inner) => Some(inner.as_slice()),
                    _ => None,
                };
                if let Some(found) = children.and_then(|c| walk_inlines(c, pred)) {
                    return Some(found);
                }
            }
            None
        }
        fn walk_blocks(blocks: &[Block], pred: impl Fn(&Inline) -> bool + Copy) -> Option<&Inline> {
            for block in blocks {
                let found = match block {
                    Block::Para(inlines) | Block::Header(_, _, inlines) => {
                        walk_inlines(inlines, pred)
                    }
                    Block::Div(_, inner) => walk_blocks(inner, pred),
                    _ => None,
                };
                if found.is_some() {
                    return found;
                }
            }
            None
        }
        walk_blocks(blocks, pred)
    }

    /// Find the first top-level `Div` whose class list carries
    /// `aozora-{suffix}`.
    fn find_div<'a>(blocks: &'a [Block], suffix: &str) -> Option<(&'a Attr, &'a [Block])> {
        blocks.iter().find_map(|b| match b {
            Block::Div(attr, inner) if has_class(attr, suffix) => Some((attr, inner.as_slice())),
            _ => None,
        })
    }

    // -----------------------------------------------------------------
    // Inline nodes (source-driven)
    // -----------------------------------------------------------------

    #[test]
    fn implicit_ruby_projects_base_and_reading() {
        let blocks = project("青梅《おうめ》という地名。\n");
        let (_, inner) = find_span(&blocks, "ruby").expect("ruby span");
        assert_eq!(inner.len(), 2, "ruby has base + reading children");
    }

    #[test]
    fn explicit_ruby_projects_as_ruby_span() {
        let blocks = project("|青梅《おうめ》\n");
        let (_, inner) = find_span(&blocks, "ruby").expect("ruby span");
        assert_eq!(inner.len(), 2, "ruby has base + reading children");
    }

    #[test]
    fn left_ruby_projects_as_ruby_span() {
        let blocks = project("未[#「未」の左に「ザル」のルビ]んとす。\n");
        let (_, inner) = find_span(&blocks, "ruby").expect("left ruby span");
        let (_, base) = inner
            .iter()
            .find_map(|i| match i {
                Inline::Span(a, c) if has_class(a, "ruby-base") => Some((a, c)),
                _ => None,
            })
            .expect("ruby-base sub-span");
        assert_eq!(base, &[Inline::Str("".to_owned())], "left ruby base text");
    }

    #[test]
    fn side_note_projects_base_and_note_subspans() {
        let blocks = project("未来[#「未来」の左に「みらい」の注記]を見る。\n");
        let (_, inner) = find_span(&blocks, "sidenote").expect("sidenote span");
        assert!(
            inner.iter().any(|i| matches!(
                i,
                Inline::Span(a, _) if has_class(a, "sidenote-base")
            )),
            "sidenote has base sub-span: {inner:?}"
        );
        assert!(
            inner.iter().any(|i| matches!(
                i,
                Inline::Span(a, _) if has_class(a, "sidenote-note")
            )),
            "sidenote has note sub-span: {inner:?}"
        );
    }

    #[test]
    fn bouten_carries_kind_and_position() {
        let blocks = project("青空[#「青空」に傍点]を見上げる。\n");
        let (attr, inner) = find_span(&blocks, "bouten").expect("bouten span");
        assert_eq!(kv(attr, "kind"), Some("goma"), "goma bouten kind slug");
        assert_eq!(
            kv(attr, "position"),
            Some("right"),
            "default right position"
        );
        assert_eq!(
            inner,
            &[Inline::Str("青空".to_owned())],
            "bouten target text"
        );
    }

    #[test]
    fn bouten_black_triangle_kind_slug() {
        let blocks = project("規範[#「規範」に黒三角傍点]を説く。\n");
        let (attr, _) = find_span(&blocks, "bouten").expect("bouten span");
        assert_eq!(
            kv(attr, "kind"),
            Some("kurosankaku"),
            "black-triangle bouten slug"
        );
    }

    #[test]
    fn tate_chu_yoko_projects_to_tcy_span() {
        // The directive sits immediately after 33, so the literal folds into
        // the node (`Reclaimed`) and the tcy span is the sole copy. (The
        // non-adjacent `明治33年[#…]` form splices a `Detached` decoration —
        // covered by `non_adjacent_forward_styles_referent_once`.)
        let blocks = project("明治33[#「33」は縦中横]年に。\n");
        let (_, inner) = find_span(&blocks, "tate-chu-yoko").expect("tcy span");
        assert_eq!(
            inner,
            &[Inline::Str("33".to_owned())],
            "tcy embedded text"
        );
    }

    #[test]
    fn non_adjacent_forward_styles_referent_once() {
        // #333: the non-adjacent referent 青空 is styled in place (a `Detached`
        // decoration projected as a bouten span), while the bracket stays
        // `Referenced` and projects nothing. 青空 appears exactly once — the
        // styling is added, the #231/#228 no-double-projection invariant holds.
        let blocks = project("青空の下を歩く[#「青空」に傍点]");
        let (_, inner) = find_span(&blocks, "bouten").expect("styled referent span");
        assert_eq!(
            inner,
            &[Inline::Str("青空".to_owned())],
            "the decoration styles 青空"
        );
        let Some(Block::Para(inlines)) = blocks.first() else {
            panic!("expected a single Para, got {blocks:?}");
        };
        assert_eq!(inlines.len(), 2, "styled span + plain tail: {inlines:?}");
        assert_eq!(
            inlines[1],
            Inline::Str("の下を歩く".to_owned()),
            "the tail after the referent stays plain"
        );
    }

    #[test]
    fn resolved_gaiji_emits_resolved_char() {
        let blocks = project("珍しき木※[#「木+吶のつくり」、第3水準1-85-54]が立つ。\n");
        let (attr, inner) = find_span(&blocks, "gaiji").expect("gaiji span");
        assert_eq!(
            kv(attr, "description"),
            Some("木+吶のつくり"),
            "gaiji description"
        );
        assert_eq!(kv(attr, "mencode"), Some("第3水準1-85-54"), "gaiji mencode");
        match inner {
            [Inline::Str(s)] => assert!(
                s.starts_with("Char("),
                "resolved gaiji renders the debug Char(...) form, got {s:?}"
            ),
            other => panic!("expected single Str for resolved gaiji, got {other:?}"),
        }
    }

    #[test]
    fn unresolved_gaiji_emits_geta_placeholder() {
        let blocks = project("※[#「架空の外字」、第3水準99-99-99]");
        let (_, inner) = find_span(&blocks, "gaiji").expect("gaiji span");
        assert_eq!(
            inner,
            &[Inline::Str("".to_owned())],
            "unresolved gaiji → 〓 placeholder"
        );
    }

    #[test]
    fn angle_quote_projects_to_span() {
        let blocks = project("≪重要≫な記述。\n");
        let (_, inner) = find_span(&blocks, "angle-quote").expect("angle-quote span");
        assert_eq!(inner, &[Inline::Str("重要".to_owned())], "angle-quote text");
    }

    #[test]
    fn kaeriten_re_mark_projects_to_span() {
        let blocks = project("天[#(レ)]地\n");
        let (attr, _) = find_span(&blocks, "kaeriten").expect("kaeriten span");
        assert_eq!(kv(attr, "mark"), Some("(レ)"), "kaeriten mark text");
    }

    #[test]
    fn center_page_projects_to_center_span() {
        let blocks = project("[#ページの左右中央]題名\n");
        let (_, inner) = find_span(&blocks, "center").expect("center span");
        assert!(
            inner.is_empty(),
            "center is an empty marker span: {inner:?}"
        );
    }

    #[test]
    fn heading_hint_carries_level_and_target() {
        let blocks = project("序章\n本文\n[#「序章」は中見出し]\n");
        let (attr, _) = find_span(&blocks, "heading-hint").expect("heading-hint span");
        assert_eq!(kv(attr, "level"), Some("2"), "中見出し → level 2");
        assert_eq!(kv(attr, "target"), Some("序章"), "heading-hint target");
    }

    #[test]
    fn same_line_heading_emits_heading_hint() {
        let blocks = project("萩原朔太郎[#「萩原朔太郎」は同行中見出し]\u{3000}二十年の友。\n");
        let (attr, _) = find_span(&blocks, "heading-hint").expect("heading-hint span");
        assert_eq!(kv(attr, "target"), Some("萩原朔太郎"), "same-line target");
    }

    #[test]
    fn editorial_annotation_kind_slug() {
        let blocks = project("[#見出し]序章[#見出し終わり]\n");
        let (attr, _) = find_span(&blocks, "annotation").expect("annotation span");
        assert_eq!(kv(attr, "kind"), Some("editorial"), "annotation kind");
        assert!(
            kv(attr, "raw").is_some_and(|r| r.contains("見出し")),
            "annotation carries raw text"
        );
    }

    #[test]
    fn sic_annotation_kind_slug() {
        let blocks = project("そういう風[#「いう風」はママ]だ\n");
        let (attr, _) = find_span(&blocks, "annotation").expect("annotation span");
        assert_eq!(kv(attr, "kind"), Some("sic"), "ママ → sic kind");
    }

    #[test]
    fn base_text_variant_annotation_kind_slug() {
        let blocks = project("間違い[#「間違い」は底本では「間違ひ」]です\n");
        let (attr, _) = find_span(&blocks, "annotation").expect("annotation span");
        assert_eq!(
            kv(attr, "kind"),
            Some("base-text-variant"),
            "底本では → base-text-variant kind"
        );
    }

    #[test]
    fn other_annotation_kind_slug() {
        // `[#割り注]` inline classifies as a non-Unknown, non-correction
        // annotation → the `other` slug arm.
        let blocks = project("[#割り注]上の段/下の段[#割り注終わり]\n");
        let (attr, _) = find_span(&blocks, "annotation").expect("annotation span");
        assert_eq!(kv(attr, "kind"), Some("other"), "割り注 → other kind");
    }

    // -----------------------------------------------------------------
    // Forward-reference emphasis projection (WS-5)
    // -----------------------------------------------------------------

    #[test]
    fn emphasis_bold_projects_to_strong() {
        let blocks = project("甲[#「甲」は太字]\n");
        let strong = find_inline(&blocks, |i| matches!(i, Inline::Strong(_)))
            .expect("bold projects to a Strong inline");
        assert_eq!(
            strong,
            &Inline::Strong(vec![Inline::Str("".to_owned())]),
            "Strong carries the real target text"
        );
    }

    #[test]
    fn emphasis_italic_projects_to_emph() {
        let blocks = project("乙[#「乙」は斜体]\n");
        let emph = find_inline(&blocks, |i| matches!(i, Inline::Emph(_)))
            .expect("italic projects to an Emph inline");
        assert_eq!(
            emph,
            &Inline::Emph(vec![Inline::Str("".to_owned())]),
            "Emph carries the real target text"
        );
    }

    #[test]
    fn emphasis_font_size_projects_to_font_span() {
        let blocks = project("甲[#「甲」は2段階大きな文字]\n");
        let (attr, inner) = find_span(&blocks, "font-larger").expect("font-larger span");
        assert_eq!(kv(attr, "steps"), Some("2"), "font shift magnitude");
        assert_eq!(
            inner,
            &[Inline::Str("".to_owned())],
            "font-size span carries the real target text, not a Debug dump"
        );
    }

    #[test]
    fn emphasis_superscript_projects_to_superscript() {
        let blocks = project("e2[#「2」は上付き小文字]\n");
        let sup = find_inline(&blocks, |i| matches!(i, Inline::Superscript(_)))
            .expect("superscript projects to a Superscript inline");
        assert_eq!(
            sup,
            &Inline::Superscript(vec![Inline::Str("".to_owned())]),
            "Superscript carries the real target text"
        );
    }

    #[test]
    fn emphasis_subscript_projects_to_subscript() {
        let blocks = project("e2[#「2」は下付き小文字]\n");
        let sub = find_inline(&blocks, |i| matches!(i, Inline::Subscript(_)))
            .expect("subscript projects to a Subscript inline");
        assert_eq!(
            sub,
            &Inline::Subscript(vec![Inline::Str("".to_owned())]),
            "Subscript carries the real target text"
        );
    }

    /// The whole point of WS-5: a document mixing bold / italic / font-size /
    /// superscript projects to the native Pandoc constructs carrying the real
    /// text, and no `ForwardFormat` Debug dump survives anywhere in the JSON.
    #[test]
    fn mixed_emphasis_projection_carries_text_and_drops_debug() {
        let blocks = project(
            "甲[#「甲」は太字]\n乙[#「乙」は斜体]\n\
             丙[#「丙」は2段階大きな文字]\ne2[#「2」は上付き小文字]\n",
        );
        let json = serde_json::to_string(&blocks).expect("serialise blocks");
        for tag in ["Strong", "Emph", "Superscript"] {
            assert!(
                json.contains(tag),
                "expected a {tag} inline in the projection: {json}"
            );
        }
        for text in ["", "", "", ""] {
            assert!(
                json.contains(text),
                "target text {text} must survive: {json}"
            );
        }
        assert!(
            !json.contains("ForwardFormat"),
            "no ForwardFormat Debug dump may remain: {json}"
        );
    }

    /// Compile-time exhaustiveness guard. Every [`ForwardAttr`] and [`Segment`]
    /// variant must be matched with no `_` fall-through, so adding a variant
    /// breaks this test's build — forcing a deliberate projection rather than a
    /// silent empty `Str` / debug span. The runtime assertion then pins that the
    /// live [`format_inline`] never emits an empty-class placeholder for any
    /// forward attribute.
    #[test]
    fn forward_attr_and_segment_projection_is_exhaustive() {
        // Naming the discriminants with no wildcard is the guard; the body is
        // irrelevant.
        fn cover_forward_attr(a: ForwardAttr) {
            match a {
                ForwardAttr::Bold
                | ForwardAttr::Gothic
                | ForwardAttr::Italic
                | ForwardAttr::SuperScript
                | ForwardAttr::SubScript
                | ForwardAttr::SmallScript(_)
                | ForwardAttr::Framed(_)
                | ForwardAttr::Horizontal
                | ForwardAttr::Caption
                | ForwardAttr::FontSize(_)
                | ForwardAttr::FontSizeAbsolute(_)
                | ForwardAttr::Bouten { .. }
                | ForwardAttr::CombineUpright
                | ForwardAttr::Fraction
                | ForwardAttr::AccentDot
                | ForwardAttr::Accent(_)
                | ForwardAttr::AlignEnd { .. } => {}
            }
        }
        fn cover_segment(s: Segment) {
            match s {
                Segment::Text(_) | Segment::Gaiji(_) | Segment::Directive(_) => {}
            }
        }

        use std::num::NonZeroI8;
        let nz = |n: i8| FontShift(NonZeroI8::new(n).expect("nonzero"));
        let attrs = [
            ForwardAttr::Bold,
            ForwardAttr::Gothic,
            ForwardAttr::Italic,
            ForwardAttr::SuperScript,
            ForwardAttr::SubScript,
            ForwardAttr::SmallScript(BoutenPosition::Right),
            ForwardAttr::Framed(EnclosureKind::Rule),
            ForwardAttr::Horizontal,
            ForwardAttr::Caption,
            ForwardAttr::FontSize(nz(2)),
            ForwardAttr::FontSize(nz(-1)),
            ForwardAttr::FontSizeAbsolute(AbsoluteSize::Large),
            ForwardAttr::Bouten {
                kind: BoutenKind::Goma,
                position: BoutenPosition::Right,
            },
            ForwardAttr::CombineUpright,
            ForwardAttr::Fraction,
            ForwardAttr::AccentDot,
            ForwardAttr::Accent(AccentMark::Acute),
            ForwardAttr::AlignEnd { offset: 3 },
        ];
        for attr in attrs {
            cover_forward_attr(attr);
            let mut store = NodeStore::new();
            let text_id = store.intern("X");
            let target = store.push_contents(&[Content::Plain(text_id)]);
            let f = ForwardFormat {
                attr,
                target,
                origin: ForwardOrigin::SelfContained,
                payload: ForwardPayload::None,
            };
            let inline = format_inline(f, &store);
            // Every attribute resolves its target text; none returns an
            // empty-class placeholder span.
            let json = serde_json::to_string(&inline).expect("serialise inline");
            assert!(
                json.contains('X'),
                "{attr:?} must project the real target text: {json}"
            );
            assert!(
                !json.contains("ForwardFormat"),
                "{attr:?} must not emit a ForwardFormat Debug dump: {json}"
            );
        }
        let mut store = NodeStore::new();
        cover_segment(Segment::Text(store.intern("x")));
    }

    // -----------------------------------------------------------------
    // Block-leaf nodes
    // -----------------------------------------------------------------

    #[test]
    fn section_break_emits_classed_div() {
        let blocks = project("前章。\n[#改丁]\n次章。\n");
        let (attr, inner) = find_div(&blocks, "section-break").expect("section-break div");
        assert!(
            attr.1.iter().any(|c| c.contains("section-break-")),
            "section-break carries a kind-specific class: {:?}",
            attr.1
        );
        assert!(inner.is_empty(), "section-break div is empty: {inner:?}");
    }

    #[test]
    fn page_break_closes_paragraph_and_emits_rule() {
        let blocks = project("第一章\n本文。\n[#改ページ]\n第二章\n");
        let rule_idx = blocks
            .iter()
            .position(|b| matches!(b, Block::HorizontalRule))
            .expect("HorizontalRule present");
        assert!(
            matches!(&blocks[rule_idx - 1], Block::Para(_)),
            "page break flushes the preceding paragraph"
        );
    }

    #[test]
    fn large_heading_projects_to_header_level_1() {
        let blocks = project("第一章\n[#「第一章」は大見出し]\n本文。\n");
        let header = blocks
            .iter()
            .find_map(|b| match b {
                Block::Header(level, attr, inlines) => Some((*level, attr, inlines)),
                _ => None,
            })
            .expect("Header block");
        assert_eq!(header.0, 1, "大見出し → level 1");
        assert_eq!(kv(header.1, "kind"), Some("large"), "large heading kind");
        assert!(
            kv(header.1, "style").is_none(),
            "standard style adds no style kv"
        );
    }

    #[test]
    fn window_heading_projects_with_style_attr() {
        let blocks = project("序章\n[#「序章」は窓中見出し]\n");
        let header = blocks
            .iter()
            .find_map(|b| match b {
                Block::Header(level, attr, _) => Some((*level, attr)),
                _ => None,
            })
            .expect("Header block");
        assert_eq!(header.0, 2, "中見出し → level 2");
        assert_eq!(kv(header.1, "kind"), Some("medium"), "medium kind");
        assert_eq!(kv(header.1, "style"), Some("window"), "window style attr");
    }

    #[test]
    fn sashie_keyword_form_no_caption_has_empty_alt() {
        let blocks = project("ある日、[#挿絵(cover.png)入る]その地に至る。\n");
        let img = find_image(&blocks).expect("sashie image");
        assert!(img.1.is_empty(), "no caption → empty alt: {:?}", img.1);
        assert_eq!(img.2.0, "cover.png", "image target file");
    }

    #[test]
    fn sashie_keyword_form_with_caption_uses_caption_alt() {
        let blocks = project("ある日、[#挿絵(cover.png)「図一」入る]その地に至る。\n");
        let img = find_image(&blocks).expect("sashie image");
        assert_eq!(
            img.1,
            &[Inline::Str("図一".to_owned())],
            "caption becomes alt text"
        );
    }

    #[test]
    fn sashie_general_form_uses_description_alt() {
        let blocks = project("[#キャラクターの図(fig.png)入る]\n");
        let img = find_image(&blocks).expect("sashie image");
        assert_eq!(
            img.1,
            &[Inline::Str("キャラクターの図".to_owned())],
            "leading description becomes alt text"
        );
        assert_eq!(img.2.0, "fig.png", "image target file");
    }

    /// Find the first `Image` inline in any `Para` block.
    fn find_image(blocks: &[Block]) -> Option<(&Attr, &[Inline], &(String, String))> {
        blocks.iter().find_map(|b| match b {
            Block::Para(inlines) => inlines.iter().find_map(|i| match i {
                Inline::Image(attr, alt, target) => Some((attr, alt.as_slice(), target)),
                _ => None,
            }),
            _ => None,
        })
    }

    // -----------------------------------------------------------------
    // Container attr arms
    // -----------------------------------------------------------------

    #[test]
    fn indent_container_carries_amount() {
        let blocks =
            project("本文。\n[#ここから2字下げ]\n中身。\n[#ここで字下げ終わり]\n後。\n");
        let (attr, _) = find_div(&blocks, "container-indent").expect("indent div");
        assert_eq!(kv(attr, "amount"), Some("2"), "indent amount");
        assert!(kv(attr, "wrap").is_none(), "plain indent has no wrap kv");
        assert!(
            kv(attr, "center").is_none(),
            "plain indent has no center kv"
        );
    }

    #[test]
    fn wrap_indent_container_carries_wrap_kv() {
        let blocks = project(
            "[#ここから2字下げ、折り返して4字下げ]\n本文。\n[#ここで字下げ終わり]\n",
        );
        let (attr, _) = find_div(&blocks, "container-indent").expect("indent div");
        assert_eq!(kv(attr, "amount"), Some("2"), "indent base amount");
        assert_eq!(kv(attr, "wrap"), Some("4"), "hanging-indent wrap amount");
    }

    #[test]
    fn center_indent_container_carries_center_kv() {
        let blocks =
            project("[#ここから5字下げ、ページの左右中央に]\n献辞\n[#ここで字下げ終わり]\n");
        let (attr, _) = find_div(&blocks, "container-indent").expect("indent div");
        assert_eq!(kv(attr, "amount"), Some("5"), "indent amount");
        assert_eq!(kv(attr, "center"), Some("true"), "page-centred indent kv");
    }

    #[test]
    fn warichu_block_container_div() {
        let blocks =
            project("前文。\n[#ここから割り注]\n上/下\n[#ここで割り注終わり]\n後文。\n");
        let div = find_div(&blocks, "container-warichu");
        assert!(div.is_some(), "warichu container div: {blocks:?}");
    }

    #[test]
    fn keigakomi_container_div() {
        let blocks = project("[#罫囲み]\n本文一行目。\n本文二行目。\n[#罫囲み終わり]\n");
        let (_, inner) = find_div(&blocks, "container-keigakomi").expect("keigakomi div");
        assert!(!inner.is_empty(), "keigakomi wraps inner blocks");
    }

    #[test]
    fn align_end_container_carries_offset() {
        let blocks = project("[#ここから地から3字上げ]\n名簿。\n[#ここで字上げ終わり]\n");
        let (attr, _) = find_div(&blocks, "container-align-end").expect("align-end div");
        assert_eq!(kv(attr, "offset"), Some("3"), "align-end offset");
    }

    // Post-S5, a *text-only* bouten range folds to an inline forward span (see
    // `bouten_carries_kind_and_position`), so the `container-bouten` div path is
    // reached only by a range whose run is non-foldable. Embedded ruby keeps the
    // range a container while leaving the open marker's variant / position intact.
    #[test]
    fn bouten_range_container_carries_variant() {
        let blocks = project("本文[#傍点]甲《こう》[#傍点終わり]。");
        let (attr, _) = find_div(&blocks, "container-bouten").expect("bouten range div");
        assert_eq!(kv(attr, "variant"), Some("goma"), "default bouten variant");
        assert!(
            kv(attr, "position").is_none(),
            "right-side range omits the position kv"
        );
    }

    #[test]
    fn bouten_range_left_position_kv() {
        let blocks = project("本文[#左に傍線]丙《へい》[#左に傍線終わり]。");
        let (attr, _) = find_div(&blocks, "container-bouten").expect("bouten range div");
        assert_eq!(kv(attr, "variant"), Some("bosen"), "傍線 variant slug");
        assert_eq!(kv(attr, "position"), Some("left"), "left-side range kv");
    }

    #[test]
    fn unknown_container_falls_through_to_unknown_class() {
        // 段組 (columns) has no dedicated container_attr arm → `container-unknown`.
        let blocks =
            project("前文。\n[#ここから2段組み]\n左右。\n[#ここで段組み終わり]\n後文。\n");
        let div = find_div(&blocks, "container-unknown");
        assert!(div.is_some(), "columns → container-unknown div: {blocks:?}");
    }

    #[test]
    fn table_container_falls_through_to_unknown_class() {
        let blocks = project("[#ここから表]\n項目\u{3000}\n[#ここで表終わり]\n");
        assert!(
            find_div(&blocks, "container-unknown").is_some(),
            "table → container-unknown: {blocks:?}"
        );
    }

    #[test]
    fn bold_block_container_falls_through_to_unknown_class() {
        let blocks = project("[#ここから太字]\n強調する段落。\n[#ここで太字終わり]\n");
        assert!(
            find_div(&blocks, "container-unknown").is_some(),
            "bold block → container-unknown: {blocks:?}"
        );
    }

    #[test]
    fn nested_containers_nest_divs() {
        let blocks = project(
            "[#ここから2字下げ]\n外。\n[#ここから3字下げ]\n内。\n\
             [#ここで字下げ終わり]\n戻る。\n[#ここで字下げ終わり]\n",
        );
        let (_, outer) = find_div(&blocks, "container-indent").expect("outer indent div");
        let has_nested = find_div(outer, "container-indent").is_some();
        assert!(has_nested, "inner indent div nested in outer: {outer:?}");
    }

    // -----------------------------------------------------------------
    // Defensive stack handling
    // -----------------------------------------------------------------

    #[test]
    fn unclosed_container_is_popped_at_eof() {
        // No matching close — `run` must still wrap the body in a Div.
        let blocks = project("[#ここから2字下げ]\n本文。\n");
        assert!(
            find_div(&blocks, "container-indent").is_some(),
            "unclosed container still wraps its body: {blocks:?}"
        );
    }

    #[test]
    fn unmatched_close_does_not_panic_and_keeps_body() {
        // A close with no matching open must not pop the root frame.
        let blocks = project("本文。\n[#ここで字下げ終わり]\n");
        assert!(
            blocks.iter().any(|b| matches!(b, Block::Para(_))),
            "body survives an unmatched close: {blocks:?}"
        );
        assert!(
            find_div(&blocks, "container-indent").is_none(),
            "no spurious container div: {blocks:?}"
        );
    }

    #[test]
    fn empty_source_yields_no_blocks() {
        let blocks = project("");
        assert!(blocks.is_empty(), "empty source → no blocks: {blocks:?}");
    }

    #[test]
    fn pandoc_api_version_is_pinned() {
        let doc = Document::new("x");
        let pandoc = to_pandoc(&doc.snapshot());
        assert_eq!(
            pandoc.pandoc_api_version,
            vec![1, 23],
            "pinned Pandoc 1.23 API version"
        );
        assert!(pandoc.meta.is_empty(), "no meta emitted");
    }

    // -----------------------------------------------------------------
    // Direct builder unit tests (forms not reachable as inline leaves
    // through the source pipeline, but live projection helpers)
    // -----------------------------------------------------------------

    #[test]
    fn line_inline_indent_carries_amount() {
        let inline = line_inline(LineFormat::Indent {
            amount: 4,
            end_offset: None,
        });
        match inline {
            Inline::Span(attr, inner) => {
                assert!(has_class(&attr, "indent"), "indent class: {:?}", attr.1);
                assert_eq!(kv(&attr, "amount"), Some("4"), "indent amount kv");
                assert!(inner.is_empty(), "indent is an empty marker span");
            }
            other => panic!("expected Span, got {other:?}"),
        }
    }

    #[test]
    fn line_inline_align_end_carries_offset() {
        let inline = line_inline(LineFormat::AlignEnd { offset: 7 });
        match inline {
            Inline::Span(attr, _) => {
                assert!(has_class(&attr, "align-end"), "align-end class");
                assert_eq!(kv(&attr, "offset"), Some("7"), "align-end offset kv");
            }
            other => panic!("expected Span, got {other:?}"),
        }
    }

    #[test]
    fn line_inline_center_is_empty_marker() {
        match line_inline(LineFormat::Center { page: false }) {
            Inline::Span(attr, inner) => {
                assert!(has_class(&attr, "center"), "center class");
                assert!(inner.is_empty(), "center marker span is empty");
            }
            other => panic!("expected Span, got {other:?}"),
        }
    }

    #[test]
    fn bouten_position_slug_covers_left_and_unknown() {
        assert_eq!(bouten_position_slug(BoutenPosition::Right), "right");
        assert_eq!(bouten_position_slug(BoutenPosition::Left), "left");
        // The `Both` arm is distinct from the `_ => "unknown"` fallthrough:
        // deleting it must not collapse 両側 into `unknown`.
        assert_eq!(bouten_position_slug(BoutenPosition::Both), "both");
    }

    #[test]
    fn annotation_kind_slug_covers_all_named_arms() {
        // Every named arm maps to its own slug; deleting any one arm would
        // collapse that variant into the `_ => "other"` fallthrough. Pin each
        // slug so no arm can silently drop out.
        for (kind, slug) in [
            (DirectiveKind::NonCanonical, "non-canonical"),
            (DirectiveKind::Editorial, "editorial"),
            (DirectiveKind::Sic, "sic"),
            (DirectiveKind::BaseTextVariant, "base-text-variant"),
            (DirectiveKind::EditorNote, "editor-note"),
            (DirectiveKind::RubyAttached, "ruby-attached"),
            (DirectiveKind::RubyRetarget, "ruby-retarget"),
            (DirectiveKind::RubyPairOpen, "ruby-pair-open"),
            (DirectiveKind::RubyPairClose, "ruby-pair-close"),
            (DirectiveKind::MarginNotePairOpen, "margin-note-pair-open"),
            (DirectiveKind::MarginNotePairClose, "margin-note-pair-close"),
        ] {
            assert_eq!(
                annotation_kind_slug(kind),
                slug,
                "{kind:?} must map to its own slug, not the `other` fallthrough"
            );
        }
    }

    #[test]
    fn heading_kind_slug_covers_levels() {
        assert_eq!(heading_kind_slug(HeadingKind::Large), "large");
        assert_eq!(heading_kind_slug(HeadingKind::Medium), "medium");
        assert_eq!(heading_kind_slug(HeadingKind::Small), "small");
    }

    #[test]
    fn heading_style_slug_covers_styles() {
        assert_eq!(
            heading_style_slug(HeadingStyle::SameLine),
            Some("same-line")
        );
        assert_eq!(heading_style_slug(HeadingStyle::Window), Some("window"));
        assert_eq!(
            heading_style_slug(HeadingStyle::Standard),
            None,
            "standard style adds no slug"
        );
    }

    #[test]
    fn small_heading_block_builder_is_level_3() {
        // Build the owned heading payload directly via a store.
        let mut store = NodeStore::new();
        let text_id = store.intern("見出し");
        let text = store.push_contents(&[Content::Plain(text_id)]);
        let heading = Heading {
            kind: HeadingKind::Small,
            style: HeadingStyle::SameLine,
            text,
        };
        match aozora_heading_block(heading, &store) {
            Block::Header(level, attr, inlines) => {
                assert_eq!(level, 3, "小見出し → level 3");
                assert_eq!(kv(&attr, "kind"), Some("small"), "small kind slug");
                assert_eq!(
                    kv(&attr, "style"),
                    Some("same-line"),
                    "same-line style attr"
                );
                assert_eq!(
                    inlines,
                    vec![Inline::Str("見出し".to_owned())],
                    "heading text inlines"
                );
            }
            other => panic!("expected Header, got {other:?}"),
        }
    }

    /// A container close emits its `Div` mid-stream, so content that follows
    /// the close is a *sibling* block at the enclosing level — not swallowed
    /// into the container. A no-op `close_container` would keep the frame open
    /// until EOF, folding the trailing content inside the Div.
    #[test]
    fn close_container_emits_div_before_trailing_content() {
        let blocks = project("A\n\n[#ここから2字下げ]\nB\n[#ここで字下げ終わり]\n\nC\n");
        let div_idx = blocks
            .iter()
            .position(|b| matches!(b, Block::Div(a, _) if has_class(a, "container-indent")))
            .expect("indent div present");
        let trailing_is_sibling = blocks[div_idx + 1..].iter().any(|b| {
            matches!(
                b,
                Block::Para(inlines)
                    if inlines.iter().any(|i| matches!(i, Inline::Str(s) if s == "C"))
            )
        });
        assert!(
            trailing_is_sibling,
            "trailing content must be a sibling Para after the closed Div: {blocks:?}"
        );
    }

    /// `push_content_inlines` dispatches a `Content::Segments` run element by
    /// element: `Text` → `Str`, `Gaiji` → gaiji span, `Directive` → annotation
    /// span. Deleting the `Segments` arm drops the whole run; deleting any
    /// segment arm swaps that element for an empty placeholder `Str`.
    #[test]
    fn push_content_inlines_dispatches_each_segment_kind() {
        use crate::syntax::ast::GaijiCanonicalOwned;

        let mut store = NodeStore::new();
        let text_id = store.intern("");
        let gaiji_hint = store.intern("外字の説明");
        let raw_id = store.intern("ママ");
        let gaiji = Gaiji {
            hint: gaiji_hint,
            canonical: GaijiCanonicalOwned::Unicode('A'),
            mencode_separator: true,
            standalone: false,
        };
        let directive = Directive {
            raw: raw_id,
            kind: DirectiveKind::Sic,
        };
        let seg = store.push_segments(&[
            Segment::Text(text_id),
            Segment::Gaiji(gaiji),
            Segment::Directive(directive),
        ]);
        let mut buf = Vec::new();
        push_content_inlines(Content::Segments(seg), &store, &mut buf);

        assert_eq!(buf.len(), 3, "one inline per segment: {buf:?}");
        assert_eq!(
            buf[0],
            Inline::Str("".to_owned()),
            "Text segment projects to its interned Str"
        );
        match &buf[1] {
            Inline::Span(attr, _) => assert!(
                has_class(attr, "gaiji"),
                "Gaiji segment projects to a gaiji span: {attr:?}"
            ),
            other => panic!("expected gaiji Span, got {other:?}"),
        }
        match &buf[2] {
            Inline::Span(attr, _) => {
                assert!(
                    has_class(attr, "annotation"),
                    "Directive segment projects to an annotation span: {attr:?}"
                );
                assert_eq!(
                    kv(attr, "kind"),
                    Some("sic"),
                    "the directive's kind slug rides through"
                );
            }
            other => panic!("expected annotation Span, got {other:?}"),
        }
    }

    /// A `container-bouten` range with the `両側` (both-side) position emits a
    /// `position=both` kv. Deleting the `Both` arm drops the kv entirely.
    #[test]
    fn container_attr_bouten_both_position_kv() {
        let attr = container_attr(RegionFormat::Bouten {
            kind: BoutenKind::Goma,
            position: BoutenPosition::Both,
        });
        assert_eq!(
            kv(&attr, "variant"),
            Some("goma"),
            "goma bouten variant slug"
        );
        assert_eq!(
            kv(&attr, "position"),
            Some("both"),
            "both-side range emits the position=both kv"
        );
    }

    /// Co-applied indent styles (#78) join into a space-separated `modifiers`
    /// kv; a style-free indent emits none. Pins both sides of the
    /// `if !modifiers.is_empty()` guard.
    #[test]
    fn container_attr_indent_modifiers_kv() {
        let styled = container_attr(RegionFormat::Indent(IndentBlock {
            amount: 3,
            wrap: None,
            center: false,
            layout: IndentLayout::None,
            styles: BlockStyles {
                gothic: true,
                horizontal: true,
                framed: false,
                font: None,
            },
        }));
        assert_eq!(
            kv(&styled, "modifiers"),
            Some("gothic horizontal"),
            "co-applied styles join into a modifiers kv"
        );
        let plain = container_attr(RegionFormat::Indent(IndentBlock {
            amount: 3,
            wrap: None,
            center: false,
            layout: IndentLayout::None,
            styles: BlockStyles::EMPTY,
        }));
        assert!(
            kv(&plain, "modifiers").is_none(),
            "a style-free indent emits no modifiers kv"
        );
    }
}