adoctra-core 0.0.1

Core parser and document model for the adoctra AsciiDoc toolchain
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
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
//! Reference registry: assign section ids and catalog every referable id.
//!
//! This is the first pass that needs the *whole* document at once: a `<<id>>`
//! may point forward to a section defined later, so the registry must be
//! complete before any reference resolves. It runs after reading and before
//! conversion. Reference labels are produced during conversion
//! (body_subs.rs), in document order and with the conversion state, like Ruby's
//! `xreftext`: an explicit reftext is formatted again at each reference;
//! otherwise a block's (lazily converted) title is used; otherwise `[id]`.
//! An unknown id emits a diagnostic and also renders `[id]`.

use std::collections::{btree_map::Entry, BTreeMap};

use crate::ast::{Block, BlockKind, Document, Inline, Span};
use crate::diagnostic::{Diagnostic, Severity};
use crate::visit::{self, InlineContext, VisitorMut};

/// What a *textless* reference to an id can display. Ordered so the structure
/// stays deterministic (like [`Attributes`]).
pub(crate) type Registry = BTreeMap<String, Target>;

/// The registry as Ruby's `catalog[:refs]` lists it: by registration order.
pub(crate) fn catalog(registry: &Registry) -> Vec<crate::ast::Reference> {
    let mut entries: Vec<_> = registry.iter().collect();
    entries.sort_by_key(|(_, target)| target.order);
    entries
        .into_iter()
        .map(|(id, target)| crate::ast::Reference {
            id: id.clone(),
            inline: target.inline,
        })
        .collect()
}

/// A referable node: its explicit reftext (formatted per reference) and, for a
/// block, its title. Neither ⇒ a known id that displays `[id]` *without* a
/// diagnostic (e.g. a plain paragraph anchor).
pub(crate) struct Target {
    pub reftext: Option<crate::reftext::Read>,
    pub title: Option<Title>,
    /// Registration order, which Ruby's `resolve_id` follows.
    pub order: usize,
    /// What an `xrefstyle` can show besides the title.
    pub numbering: Numbering,
    /// An inline anchor: Ruby's `Inline#xreftext` is its reftext even when
    /// empty, where a block's `xreftext` falls back on its title.
    pub inline: bool,
}

/// Ruby's `xreftext` inputs for an xrefstyle. Example blocks and images carry
/// a caption (and its `example-caption`/`figure-caption` signifier, by the
/// caption `context`); a section has its number
/// and `sectname` (unnumbered chapters and appendices are emphasized by any
/// style).
#[derive(Default)]
pub(crate) enum Numbering {
    #[default]
    None,
    Caption {
        /// The caption's parts (Ruby's stored `@caption` markup).
        caption: Vec<crate::AttributePart>,
        numeral: Option<String>,
        context: &'static str,
    },
    Section(crate::section_numbers::Section),
}

/// Apply an xrefstyle to a converted title, like `AbstractBlock#xreftext`
/// and `Section#xreftext` without numbered sections.
pub(crate) fn styled(
    title: Vec<Inline>,
    numbering: &Numbering,
    style: Option<&str>,
    attributes: &crate::Attributes,
    span: Span,
) -> Vec<Inline> {
    let Some(style) = style else {
        return title;
    };
    let text = |value: String| Inline::Text { value, span };
    let (caption, numeral, context) = match numbering {
        Numbering::Section(section) => {
            return styled_section(title, section, style, attributes, span)
        }
        Numbering::Caption {
            caption,
            numeral,
            context,
        } if !crate::attributes::parts_text(caption).is_empty() => (caption, numeral, context),
        _ => return title,
    };
    let signifier = match (
        numeral,
        attributes.value_parts(&format!("{context}-caption")),
    ) {
        (Some(numeral), Some(parts)) => {
            vec![signifier(parts, span), text(format!(" {numeral}"))]
        }
        // Ruby's `@caption.chomp '. '`.
        _ => {
            let mut caption = caption.clone();
            if let Some(crate::AttributePart::Text(last) | crate::AttributePart::Raw(last)) =
                caption.last_mut()
            {
                if let Some(chomped) = last.strip_suffix(". ") {
                    *last = chomped.to_owned();
                }
            }
            vec![signifier(caption, span)]
        }
    };
    match style {
        "full" => {
            let mut label = signifier;
            label.push(text(", \u{201c}".into()));
            label.extend(title);
            label.push(text("\u{201d}".into()));
            label
        }
        "short" => signifier,
        _ => title,
    }
}

/// Whether [`styled`] shows the target's title: Ruby's `xreftext` with
/// `short` builds a captioned block's or numbered section's label from its
/// signifier and number alone, so the title is not converted (nor memoized)
/// then.
pub(crate) fn styled_uses_title(numbering: &Numbering, style: Option<&str>) -> bool {
    if style != Some("short") {
        return true;
    }
    match numbering {
        Numbering::Section(section) => !section.is_numbered(),
        Numbering::Caption { caption, .. } => crate::attributes::parts_text(caption).is_empty(),
        _ => true,
    }
}

/// `Section#xreftext` with an xrefstyle: `full` and `short` show a numbered
/// section's `<sectname>-refsig` and number (`full` also the quoted title);
/// otherwise chapters and appendices are emphasized.
fn styled_section(
    title: Vec<Inline>,
    section: &crate::section_numbers::Section,
    style: &str,
    attributes: &crate::Attributes,
    span: Span,
) -> Vec<Inline> {
    let text = |value: String| Inline::Text { value, span };
    let emphasized = |title| {
        if section.emphasized() {
            vec![Inline::Emphasis {
                children: title,
                span,
            }]
        } else {
            title
        }
    };
    let (append, quoted) = match style {
        _ if !section.is_numbered() => return emphasized(title),
        "full" if section.emphasized() => (",", emphasized(title)),
        "full" => {
            let mut quoted = vec![text("\u{201c}".into())];
            quoted.extend(title);
            quoted.push(text("\u{201d}".into()));
            (",", quoted)
        }
        "short" => ("", Vec::new()),
        _ => return emphasized(title),
    };
    let mut label = Vec::new();
    if let Some(parts) = attributes.value_parts(&format!("{}-refsig", section.sectname)) {
        label.push(signifier(parts, span));
        label.push(text(" ".into()));
    }
    label.push(text(section.sectnum(".", append)));
    if !quoted.is_empty() {
        label.push(text(" ".into()));
        label.extend(quoted);
    }
    label
}

/// An attribute value as label text, keeping generated boundaries.
fn signifier(parts: Vec<crate::AttributePart>, span: Span) -> Inline {
    let value = crate::attributes::parts_text(&parts);
    if parts
        .iter()
        .all(|p| matches!(p, crate::AttributePart::Text(_)))
    {
        Inline::Text { value, span }
    } else {
        Inline::Substituted { value, parts, span }
    }
}

/// Registered ids in registration order.
pub(crate) fn ordered(registry: &Registry) -> Vec<&str> {
    let mut ids: Vec<_> = registry.iter().collect();
    ids.sort_by_key(|(_, target)| target.order);
    ids.into_iter().map(|(id, _)| id.as_str()).collect()
}

/// A cross-reference generated by an attribute definition (its `pass:m`
/// stage). Ruby converts it while defining the attribute, so its natural
/// lookup and label use the ids registered before the definition and the
/// attributes at that point; every use of the value shows that result.
pub(crate) struct Definition {
    pub span: Span,
    pub attributes: std::sync::Arc<crate::Attributes>,
    pub xref: crate::Xref,
    pub textless: bool,
}

/// A definition's reference resolved at the definition: its target and, when
/// textless, its label (`None` leaves the label to the reference, e.g. for
/// the current document).
pub(crate) struct Fixed {
    xref: crate::Xref,
    label: Option<Vec<Inline>>,
}

/// Fixed definition references, indexed by `Xref::definition`.
pub(crate) type FixedXrefs = Vec<Option<Fixed>>;

/// What registration hands to conversion.
pub(crate) type Registered = (Registry, EarlyTitles, FixedXrefs);

/// Restore a definition reference's fixed target and return its fixed label.
pub(crate) fn apply_fixed(fixed: &FixedXrefs, xref: &mut crate::Xref) -> Option<Vec<Inline>> {
    let resolved = fixed.get(xref.definition?)?.as_ref()?;
    *xref = crate::Xref {
        definition: None,
        ..resolved.xref.clone()
    };
    resolved.label.clone()
}

/// Attribute snapshots expose the same definition-time targets and labels as
/// their uses in the body. Install the already computed result without running
/// substitutions again or resolving against a later document state.
pub(crate) fn resolve_attribute_definitions(
    attributes: &mut crate::Attributes,
    fixed: &FixedXrefs,
) {
    let values: Vec<_> = attributes
        .iter()
        .filter_map(|(name, _)| {
            attributes
                .raw_parts_exact(name)
                .map(|parts| (name.to_owned(), parts.to_vec()))
        })
        .collect();
    for (name, mut parts) in values {
        resolve_definition_parts(&mut parts, fixed);
        attributes.set_parts(name, parts);
    }
}

pub(crate) fn resolve_definition_parts(parts: &mut Vec<crate::AttributePart>, fixed: &FixedXrefs) {
    fill_part_labels(parts, &mut |xref, _| apply_fixed(fixed, xref));
}

/// Converts a deferred block title while reading (BodySubs::convert_early).
pub(crate) type EarlyTitle<'a> =
    dyn FnMut((usize, usize), &crate::Attributes) -> Option<Vec<Inline>> + 'a;

/// The [`EarlyTitle`] key of the document title.
pub(crate) const HEADER_KEY: (usize, usize) = (usize::MAX, usize::MAX);

/// Deferred block titles converted while reading, keyed by placeholder range
/// (the document title by its heading range).
pub(crate) type EarlyTitles = BTreeMap<(usize, usize), Vec<Inline>>;

pub(crate) enum Title {
    /// A block title: final when converted while reading, otherwise a
    /// conversion placeholder that the first reference may convert.
    Nodes(Vec<Inline>),
    /// A section title, keyed by the heading range; conversion memoizes it
    /// once its references are resolved.
    Heading((usize, usize), Vec<Inline>),
    /// The displayed document title, converted before the body.
    Header,
}

/// What reading recorded for registration, keyed by reader ranges.
pub(crate) struct Read<'a> {
    /// Inline anchors cataloged while reading.
    pub anchors: Vec<(String, crate::anchor_catalog::Entry)>,
    /// Early-expanded block reftext.
    pub reftexts: BTreeMap<(usize, usize), crate::reftext::Read>,
    /// Caption numerals of numbered blocks.
    pub numerals: BTreeMap<(usize, usize), String>,
    /// Blockquotes whose credit line splits after its labels resolve.
    pub credits: std::collections::BTreeSet<(usize, usize)>,
    /// Section titles and their numbers.
    pub sections: &'a BTreeMap<(usize, usize), crate::section_numbers::Section>,
    /// References generated by attribute definitions.
    pub definitions: Vec<Definition>,
    pub nested_titles: std::collections::BTreeSet<(usize, usize)>,
    /// Blocks of dropped AsciiDoc cells, keyed by the cell's start.
    pub dropped_blocks: BTreeMap<usize, Vec<Block>>,
    /// Where reading completed each block with an id (Ruby registers it
    /// there), keyed by the block's range.
    pub block_stamps: BTreeMap<(usize, usize), crate::context::Stamp>,
}

/// Assign section ids and register every block id and cataloged inline
/// anchor, pushing a diagnostic for a duplicate id (the first one wins).
pub(crate) fn register(
    doc: &mut Document,
    read: Read<'_>,
    early_title: &mut EarlyTitle<'_>,
    diagnostics: &mut Vec<Diagnostic>,
    placed: &mut Vec<crate::context::Placed>,
) -> Registered {
    let Read {
        mut anchors,
        mut reftexts,
        mut numerals,
        credits,
        sections,
        definitions,
        nested_titles,
        dropped_blocks,
        block_stamps,
    } = read;
    // Every heading except the document title gets an automatic id, including
    // discrete and level-0 headings in the body, as in asciidoctor.
    let doctitle = doc
        .blocks
        .first()
        .filter(|_| doc.has_title)
        .map(|block| block.span);
    // Inline anchors join in source order, between the blocks around them.
    anchors.sort_by_key(|(_, entry)| entry.span.start);
    let fixed = (0..definitions.len()).map(|_| None).collect();
    let mut ids = Ids {
        doctitle,
        nested_titles,
        dropped_blocks,
        anchors: anchors.into_iter().peekable(),
        definitions: definitions.into_iter().peekable(),
        fixed,
        position: 0,
        reftexts: &mut reftexts,
        numerals: &mut numerals,
        credits,
        sections,
        early_title,
        early: EarlyTitles::new(),
        header_resolving: false,
        registry: Registry::new(),
        diagnostics,
        placed,
        block_stamps,
        manpage_name: false,
    };
    // A manual page's NAME section registers in the header, after the
    // document title; Ruby converts its title there, whatever its id.
    let title = usize::from(doc.has_title).min(doc.blocks.len());
    let (head, body) = doc.blocks.split_at_mut(title);
    visit::walk_blocks_mut(&mut ids, head);
    if let Some(heading) = doc
        .manpage
        .as_mut()
        .and_then(|manpage| manpage.name_section.as_mut())
        .map(|section| &mut section.heading)
    {
        let attributes = std::sync::Arc::clone(&heading.attribute_context);
        if let (Some(_), BlockKind::Heading { inlines, .. }) = (&heading.id, &mut heading.kind) {
            ids.resolve_reading(inlines, &attributes);
        }
        ids.manpage_name = true;
        visit::walk_block_mut(&mut ids, heading);
        ids.manpage_name = false;
    }
    visit::walk_blocks_mut(&mut ids, body);
    ids.flush(usize::MAX);
    (ids.registry, ids.early, ids.fixed)
}

struct Ids<'a> {
    doctitle: Option<Span>,
    /// Nested documents' title headings (no automatic id).
    nested_titles: std::collections::BTreeSet<(usize, usize)>,
    /// Blocks of dropped AsciiDoc cells, registered when their table ends.
    dropped_blocks: BTreeMap<usize, Vec<Block>>,
    anchors: std::iter::Peekable<std::vec::IntoIter<(String, crate::anchor_catalog::Entry)>>,
    /// Definition references in reading order.
    definitions: std::iter::Peekable<std::vec::IntoIter<Definition>>,
    fixed: FixedXrefs,
    /// The reading position of the field whose labels are being produced.
    position: usize,
    reftexts: &'a mut BTreeMap<(usize, usize), crate::reftext::Read>,
    numerals: &'a mut BTreeMap<(usize, usize), String>,
    credits: std::collections::BTreeSet<(usize, usize)>,
    sections: &'a BTreeMap<(usize, usize), crate::section_numbers::Section>,
    early_title: &'a mut EarlyTitle<'a>,
    early: EarlyTitles,
    /// The document title is converting for a reference (Ruby's
    /// `@resolving_xref`): a reference inside it shows `[^top]`.
    header_resolving: bool,
    registry: Registry,
    diagnostics: &'a mut Vec<Diagnostic>,
    /// Duplicate ids, reported where reading registered them in Ruby.
    placed: &'a mut Vec<crate::context::Placed>,
    block_stamps: BTreeMap<(usize, usize), crate::context::Stamp>,
    /// Registering a manual page's NAME section from the header: Ruby's
    /// header section has no numeral (`sectnum` is empty).
    manpage_name: bool,
}

/// Where a quote's substituted attribution starts.
fn credit_start(block: &Block) -> Option<usize> {
    match &block.kind {
        BlockKind::Quote {
            attribution: Some(attribution),
            ..
        }
        | BlockKind::Verse {
            attribution: Some(attribution),
            ..
        } => attribution_start(attribution),
        _ => None,
    }
}

impl Ids<'_> {
    /// Register cataloged anchors and resolve definition references that
    /// start before `position`, in source order.
    fn flush(&mut self, position: usize) {
        loop {
            let anchor = self.anchors.peek().map(|(_, entry)| entry.span.start);
            let definition = self.definitions.peek().map(|d| d.span.start);
            match (anchor, definition) {
                (Some(a), d) if a < position && d.is_none_or(|d| a <= d) => self.anchor(),
                (_, Some(d)) if d < position => self.define(),
                _ => break,
            }
        }
    }

    /// Fix a definition reference with the partial registry, as Ruby's
    /// converter does while the attribute is being defined.
    fn define(&mut self) {
        let Definition {
            span,
            attributes,
            mut xref,
            textless,
        } = self.definitions.next().unwrap();
        self.position = span.start;
        self.reading_target(&mut xref, true, &attributes);
        let label = textless
            .then(|| self.reading_xref_label(&xref, true, span, &attributes))
            .flatten();
        if let Some(slot) = xref.definition.and_then(|i| self.fixed.get_mut(i)) {
            *slot = Some(Fixed { xref, label });
        }
    }

    fn anchor(&mut self) {
        let (id, entry) = self.anchors.next().unwrap();
        if entry.bibliography && self.registry.contains_key(&id) {
            self.report(
                Some(entry.stamp),
                Diagnostic {
                    omitted_span: None,
                    report: Default::default(),
                    span: entry.span,
                    severity: Severity::Warning,
                    message: format!("id assigned to bibliography anchor already in use: {id}"),
                },
            );
            return;
        }
        let target = Target {
            reftext: entry.reftext,
            title: None,
            order: self.registry.len(),
            numbering: Numbering::None,
            inline: !entry.block,
        };
        let kind = if entry.block { "block" } else { "anchor" };
        if let Some(duplicate) = register_id(&mut self.registry, id, target, kind, entry.span) {
            self.report(Some(entry.stamp), duplicate);
        }
    }

    /// Report a duplicate id where reading registered it (`stamp`), else
    /// with the references.
    fn report(&mut self, stamp: Option<crate::context::Stamp>, diagnostic: Diagnostic) {
        match stamp {
            Some(stamp) => self.placed.push(crate::context::Placed {
                stamp,
                diagnostic,
                physical: false,
            }),
            None => self.diagnostics.push(diagnostic),
        }
    }
}

impl Ids<'_> {
    /// Ruby converts an automatic-id heading and an anchored block title with
    /// a literal `{` while parsing, before the block registers itself: a
    /// reference to an id not yet registered (forward or self) displays
    /// `[id]`; an earlier target lends its reftext or converted title. A
    /// reference to a title deferred to conversion resolves there.
    fn resolve_reading(&mut self, inlines: &mut [Inline], attributes: &crate::Attributes) {
        for inline in inlines {
            match inline {
                Inline::CrossReference {
                    xref,
                    children,
                    span,
                } => {
                    self.reading_target(xref, false, attributes);
                    if children.is_empty() {
                        if let Some(mut label) =
                            self.reading_xref_label(xref, false, *span, attributes)
                        {
                            strip_label(&mut label);
                            *children = label;
                        }
                    } else {
                        self.resolve_reading(children, attributes)
                    }
                }
                Inline::Strong { children, .. }
                | Inline::Emphasis { children, .. }
                | Inline::Monospace { children, .. }
                | Inline::Mark { children, .. }
                | Inline::Superscript { children, .. }
                | Inline::Subscript { children, .. }
                | Inline::Link { children, .. } => self.resolve_reading(children, attributes),
                Inline::AttributeRef { span, .. }
                | Inline::Substituted { span, .. }
                | Inline::Footnote { span, .. } => {
                    let span = *span;
                    fill_labels(inline, |xref, textless| {
                        if let Some(label) = apply_fixed(&self.fixed, xref) {
                            return Some(label);
                        }
                        self.reading_target(xref, true, attributes);
                        textless
                            .then(|| self.reading_xref_label(xref, true, span, attributes))
                            .flatten()
                    });
                }
                _ => {}
            }
        }
    }

    /// A natural reference while reading looks its text up among the ids
    /// registered so far, without caching (Ruby's `resolve_id` before
    /// `@parsed`): the first whose label spells it wins.
    fn reading_target(
        &mut self,
        xref: &mut crate::Xref,
        lexical: bool,
        attributes: &crate::Attributes,
    ) {
        let Some(fragment) = natural_text(xref, &self.registry, lexical) else {
            return;
        };
        for id in ordered(&self.registry)
            .into_iter()
            .map(str::to_owned)
            .collect::<Vec<_>>()
        {
            let label = self.reading_xreftext(&id, None, Span::new(0, 0), attributes);
            if label.as_deref().and_then(crate::xref_target::lexical_label)
                == Some(fragment.clone())
            {
                crate::xref_target::retarget(xref, &id, lexical);
                return;
            }
        }
    }

    /// A textless label while reading: an interdocument path, the referenced
    /// node's label, or `[id]` for an id not registered yet. The current
    /// document's title is left to conversion.
    fn reading_xref_label(
        &mut self,
        xref: &crate::Xref,
        lexical: bool,
        span: Span,
        attributes: &crate::Attributes,
    ) -> Option<Vec<Inline>> {
        if let Some(path) = &xref.path {
            return Some(crate::entity_references::reference_inlines(
                &decoded(path, lexical),
                span,
            ));
        }
        if xref.refid.as_deref().is_none_or(str::is_empty) {
            return self.reading_top_label(span, attributes);
        }
        let id = decoded_refid(xref, lexical)?;
        if self.registry.contains_key(&id) {
            let style = match &xref.xrefstyle {
                Some(style) => Some(decoded(style, lexical)),
                None => attributes.get("xrefstyle").map(str::to_owned),
            };
            self.reading_label(&id, style.as_deref(), span, attributes)
        } else if id.is_empty() {
            None
        } else {
            Some(crate::entity_references::unknown_reference_label(
                xref, &id, lexical, span,
            ))
        }
    }
}

/// The text of a pending natural reference to an unknown id that resembles
/// reftext, in lexical spelling; clears the pending lookup.
pub(crate) fn natural_text(
    xref: &mut crate::Xref,
    registry: &Registry,
    lexical: bool,
) -> Option<String> {
    let spelling = xref.natural.take()?;
    let decoded = decoded(xref.fragment.as_deref()?, lexical);
    (!registry.contains_key(&decoded) && crate::xref_target::looks_like_text(&decoded))
        .then_some(spelling)
}

/// The decoded registry id of an internal reference (`None` for the
/// current document or an interdocument path). Fields of value-generated
/// references are lexical.
pub(crate) fn decoded_refid(xref: &crate::Xref, lexical: bool) -> Option<String> {
    if xref.path.is_some() {
        return None;
    }
    xref.refid.as_deref().map(|refid| decoded(refid, lexical))
}

pub(crate) fn decoded(value: &str, lexical: bool) -> String {
    if lexical {
        crate::attributes::decode_special(value)
    } else {
        value.to_owned()
    }
}

/// Cross-references generated inside a value: `f` resolves each `OpenXref`
/// in order and, when it is directly followed by its `CloseXref` (textless),
/// may return its label, inserted as semantic parts; the node's flat value
/// follows. Labels lose their link and anchor tags, as borrowed AST labels do.
pub(crate) fn fill_labels(
    node: &mut Inline,
    mut f: impl FnMut(&mut crate::Xref, bool) -> Option<Vec<Inline>>,
) {
    match node {
        Inline::AttributeRef {
            value: Some(value),
            parts,
            ..
        }
        | Inline::Substituted { value, parts, .. } => {
            if fill_part_labels(parts, &mut f) {
                *value = crate::attributes::parts_text(parts);
            }
        }
        // References inside a footnote's text.
        Inline::Footnote { footnote, .. } => {
            fill_part_labels(&mut footnote.content, &mut f);
        }
        // References inside a keyboard, button or menu label.
        Inline::Ui { ui, .. } => {
            for label in ui.labels_mut() {
                fill_part_labels(label, &mut f);
            }
        }
        Inline::Stem { stem, .. } => {
            fill_part_labels(&mut stem.parts, &mut f);
        }
        // References inside a flow index term.
        Inline::IndexTerm { term, .. } => {
            for label in term.labels_mut() {
                fill_part_labels(label, &mut f);
            }
        }
        _ => {}
    }
}

fn fill_part_labels(
    parts: &mut Vec<crate::AttributePart>,
    f: &mut impl FnMut(&mut crate::Xref, bool) -> Option<Vec<Inline>>,
) -> bool {
    let mut filled = false;
    let mut i = 0;
    while i < parts.len() {
        if let crate::AttributePart::Footnote(footnote) = &mut parts[i] {
            filled |= fill_part_labels(&mut footnote.content, f);
            i += 1;
            continue;
        }
        if let crate::AttributePart::Ui(ui) = &mut parts[i] {
            for label in ui.labels_mut() {
                filled |= fill_part_labels(label, f);
            }
            i += 1;
            continue;
        }
        if let crate::AttributePart::Stem(stem) = &mut parts[i] {
            filled |= fill_part_labels(&mut stem.parts, f);
            i += 1;
            continue;
        }
        if let crate::AttributePart::IndexTerm(term) = &mut parts[i] {
            for label in term.labels_mut() {
                filled |= fill_part_labels(label, f);
            }
            i += 1;
            continue;
        }
        let textless = matches!(parts.get(i + 1), Some(crate::AttributePart::CloseXref));
        if let crate::AttributePart::OpenXref(xref) = &mut parts[i] {
            if let Some(mut nodes) = f(xref, textless).filter(|_| textless) {
                strip_label(&mut nodes);
                let inserted = label_parts(&nodes);
                let count = inserted.len();
                parts.splice(i + 1..i + 1, inserted);
                i += count;
                filled = true;
            }
        }
        i += 1;
    }
    filled
}

/// A borrowed label as semantic parts (plain formatting becomes boundaries).
pub(crate) fn label_parts(nodes: &[Inline]) -> Vec<crate::AttributePart> {
    use crate::AttributePart as Part;
    let mut parts = Vec::new();
    for node in nodes {
        match node {
            Inline::Text { value, .. } => crate::attributes::push_part(&mut parts, value, false),
            Inline::Raw { value, .. } => crate::attributes::push_part(&mut parts, value, true),
            Inline::Substituted { parts: inner, .. } => {
                for part in inner {
                    crate::attributes::push_value(&mut parts, part.clone());
                }
            }
            Inline::AttributeRef {
                name,
                value,
                parts: inner,
                ..
            } => match value {
                Some(_) if !inner.is_empty() => {
                    for part in inner {
                        crate::attributes::push_value(&mut parts, part.clone());
                    }
                }
                Some(value) => crate::attributes::push_part(&mut parts, value, false),
                None => crate::attributes::push_part(&mut parts, &format!("{{{name}}}"), false),
            },
            Inline::Link { children, .. } | Inline::CrossReference { children, .. } => {
                parts.extend(label_parts(children))
            }
            Inline::Anchor { .. } => {}
            Inline::Image { image, .. } => parts.push(Part::Image(Box::new(image.clone()))),
            Inline::Footnote { footnote, .. } => {
                parts.push(Part::Footnote(Box::new(footnote.clone())))
            }
            Inline::Ui { ui, .. } => parts.push(Part::Ui(Box::new(ui.clone()))),
            Inline::IndexTerm { term, .. } => parts.push(Part::IndexTerm(Box::new(term.clone()))),
            Inline::Stem { stem, .. } => parts.push(Part::Stem(Box::new(stem.clone()))),
            node => {
                let format = crate::attribute_macros::format(node).expect("formatting node");
                let (Inline::Strong { children, .. }
                | Inline::Emphasis { children, .. }
                | Inline::Monospace { children, .. }
                | Inline::Mark { children, .. }
                | Inline::Superscript { children, .. }
                | Inline::Subscript { children, .. }) = node
                else {
                    unreachable!()
                };
                parts.push(Part::Open(format));
                for part in label_parts(children) {
                    crate::attributes::push_value(&mut parts, part);
                }
                parts.push(Part::Close(format));
            }
        }
    }
    parts
}

/// The range of a deferred field's private conversion placeholder.
pub(crate) fn placeholder(nodes: &[Inline]) -> Option<(usize, usize)> {
    match nodes {
        [Inline::Text { value, span }] if value.is_empty() => Some((span.start, span.end)),
        _ => None,
    }
}

impl Ids<'_> {
    /// A label while reading. The reftext uses the reading attributes without
    /// executing expressions; a deferred title is converted early; `None`
    /// leaves the reference to conversion.
    /// A reference to the current document while reading (Ruby's
    /// `Document#xreftext`): a nonempty reftext, else `doctitle` — the
    /// `title` attribute, else the document title, which converts now with
    /// the reading attributes and keeps that conversion (Ruby's
    /// `@converted_title`). Without a document title, `doctitle` has nothing
    /// to show before a top-level section reading has finished (a section
    /// joins the document after its content), so it displays `[^top]`.
    fn reading_top_label(
        &mut self,
        span: Span,
        attributes: &crate::Attributes,
    ) -> Option<Vec<Inline>> {
        if let Some(doctitle) = self.doctitle {
            let top = || {
                vec![Inline::Text {
                    value: "[^top]".into(),
                    span,
                }]
            };
            if self.header_resolving {
                return Some(top());
            }
            let header_reftext = self
                .registry
                .values()
                .find(|target| matches!(target.title, Some(Title::Header)))
                .and_then(|target| target.reftext.as_ref())
                .map(|read| read.snapshot(attributes));
            let reftext = header_reftext.or_else(|| {
                attributes.get("reftext").map(|value| {
                    crate::reftext::Read::source(value, span.start).snapshot(attributes)
                })
            });
            let mut label = if let Some(nodes) = reftext.filter(|n| !inline_text(n).is_empty()) {
                nodes
            } else if let Some(value) = attributes.get("title") {
                crate::entity_references::reference_inlines(value, span)
            } else {
                let key = (doctitle.start, doctitle.end);
                match self.early.get(&key) {
                    Some(converted) => converted.clone(),
                    None => {
                        let mut converted = (self.early_title)(HEADER_KEY, attributes)?;
                        self.header_resolving = true;
                        self.resolve_reading(&mut converted, attributes);
                        self.header_resolving = false;
                        self.early.insert(key, converted.clone());
                        converted
                    }
                }
            };
            strip_label(&mut label);
            return Some(label);
        }
        let nested = |start: usize| {
            self.sections
                .iter()
                .any(|(&(outer, _), section)| outer < start && start < section.closed_at)
        };
        let first = self
            .sections
            .iter()
            .find(|(&(start, _), section)| section.closed_at <= span.start && !nested(start))
            .map(|(key, _)| *key);
        let Some(first) = first else {
            return Some(vec![Inline::Text {
                value: "[^top]".into(),
                span,
            }]);
        };
        // The first section's title as reading converted it (Ruby's memo).
        self.registry
            .values()
            .find_map(|target| match &target.title {
                Some(Title::Heading(key, nodes))
                    if *key == first && placeholder(nodes).is_none() =>
                {
                    let mut label = nodes.clone();
                    strip_label(&mut label);
                    Some(label)
                }
                _ => None,
            })
    }

    fn reading_label(
        &mut self,
        id: &str,
        style: Option<&str>,
        span: Span,
        attributes: &crate::Attributes,
    ) -> Option<Vec<Inline>> {
        self.reading_xreftext(id, style, span, attributes)
            .or_else(|| {
                self.registry[id]
                    .title
                    .is_none()
                    .then(|| crate::entity_references::reference_inlines(&format!("[{id}]"), span))
            })
    }

    /// Ruby's `xreftext` while reading: a nonempty reftext, else the title;
    /// `None` without either or for the document title (converted later).
    fn reading_xreftext(
        &mut self,
        id: &str,
        style: Option<&str>,
        span: Span,
        attributes: &crate::Attributes,
    ) -> Option<Vec<Inline>> {
        let target = &self.registry[id];
        if let Some(nodes) = target
            .reftext
            .as_ref()
            .map(|read| read.snapshot(attributes))
            .filter(|nodes| target.inline || !inline_text(nodes).is_empty())
        {
            return Some(nodes);
        }
        let title = match &target.title {
            Some(Title::Nodes(nodes)) => match placeholder(nodes) {
                None => Some(nodes.clone()),
                Some(key) => {
                    let mut converted = (self.early_title)(key, attributes)?;
                    self.resolve_reading(&mut converted, attributes);
                    self.early.insert(key, converted.clone());
                    if let Some(Title::Nodes(nodes)) = &mut self
                        .registry
                        .get_mut(id)
                        .and_then(|target| target.title.as_mut())
                    {
                        *nodes = converted.clone();
                    }
                    Some(converted)
                }
            },
            Some(Title::Heading(_, nodes)) => Some(nodes.clone()),
            Some(Title::Header) | None => None,
        }?;
        // Sections reading has not closed yet have no numerals.
        let masked;
        let numbering = match &self.registry[id].numbering {
            Numbering::Section(section) => {
                masked = Numbering::Section(section.at(self.position));
                &masked
            }
            numbering => numbering,
        };
        Some(styled(title, numbering, style, attributes, span))
    }
}

impl VisitorMut for Ids<'_> {
    fn enter_block(&mut self, block: &mut Block) -> bool {
        self.flush(block.span.start);
        self.position = block.span.start;
        // Ruby registers a section when it reads the title
        // (`initialize_section`), any other block at the end of `next_block`:
        // after its content and the inline anchors cataloged in it, converting
        // an anchored title there.
        if matches!(block.kind, BlockKind::Heading { .. }) {
            self.register_block(block);
        }
        // A quote attribution was substituted while reading: from its
        // attribute line before the content, or from a blockquote credit
        // line after the content was parsed.
        if credit_start(block).is_some_and(|start| start < block.span.start) {
            self.resolve_attribution(block);
        }
        true
    }

    fn leave_block(&mut self, block: &mut Block) {
        if let Some(start) = credit_start(block).filter(|&start| start >= block.span.start) {
            self.flush(start);
            self.position = start;
            self.resolve_attribution(block);
        }
        if matches!(block.kind, BlockKind::Table(_)) {
            // Ruby reads a dropped AsciiDoc cell (the table's last cells)
            // into a nested document sharing the catalog: its ids register
            // although the cell is never output.
            // One at a time: a table inside a dropped cell takes its own.
            while let Some((&start, _)) = self
                .dropped_blocks
                .range(block.span.start..block.span.end)
                .next()
            {
                if let Some(mut blocks) = self.dropped_blocks.remove(&start) {
                    visit::walk_blocks_mut(self, &mut blocks);
                }
            }
        }
        if !matches!(block.kind, BlockKind::Heading { .. }) {
            self.flush(block.span.end);
            self.position = block.span.end;
            self.register_block(block);
        }
    }

    fn visit_inlines(&mut self, _inlines: &mut Vec<Inline>, _context: InlineContext) {}
}

impl Ids<'_> {
    /// Register a block's id (or a heading's automatic one), resolving the
    /// references of a title converted while reading first.
    fn register_block(&mut self, block: &mut Block) {
        // The document title lends its text to an explicit id but never
        // receives an automatic one; nor does a nested document's title.
        let doctitle = Some(block.span) == self.doctitle;
        let nested_title = self
            .nested_titles
            .contains(&(block.span.start, block.span.end));
        let attributes = std::sync::Arc::clone(&block.attribute_context);
        match (&mut block.kind, &mut block.title) {
            // A heading converted while reading (an automatic id, or an
            // explicit one with an attribute reference: Ruby's
            // `initialize_section`) resolves its references before its own
            // id registers.
            (BlockKind::Heading { inlines, .. }, _)
                if (block.id.is_none() || placeholder(inlines).is_none())
                    && !doctitle
                    && !nested_title =>
            {
                self.resolve_reading(inlines, &attributes)
            }
            (_, Some(title)) if block.id.is_some() && placeholder(title).is_none() => {
                self.resolve_reading(title, &attributes)
            }
            _ => {}
        }
        let title = match &block.kind {
            BlockKind::Heading { .. } if doctitle => Some(Title::Header),
            // A title Ruby converts at its first use is a pending block title.
            BlockKind::Heading { inlines, .. } if placeholder(inlines).is_some() => {
                Some(Title::Nodes(inlines.clone()))
            }
            BlockKind::Heading { inlines, .. } => Some(Title::Heading(
                (block.span.start, block.span.end),
                inlines.clone(),
            )),
            _ => block.title.clone().map(Title::Nodes),
        };
        let key = (block.span.start, block.span.end);
        let numbering = match (&block.kind, &block.caption) {
            (BlockKind::Heading { .. }, _) => match self.sections.get(&key) {
                Some(section) if section.is_numbered() || section.emphasized() => {
                    let mut section = section.clone();
                    if self.manpage_name {
                        section.path.clear();
                    }
                    Numbering::Section(section)
                }
                // A manual page's header NAME section, read outside the body:
                // Ruby's `initialize_section` numbers it with `sectnums`, but
                // it never takes a numeral.
                None if self.manpage_name => {
                    let section = crate::section_numbers::Section::read(
                        None,
                        1,
                        false,
                        false,
                        &attributes,
                        None,
                    );
                    if section.is_numbered() {
                        Numbering::Section(section)
                    } else {
                        Numbering::None
                    }
                }
                _ => Numbering::None,
            },
            (kind, Some(caption)) => match crate::context::caption_context(kind) {
                Some(context) => Numbering::Caption {
                    caption: if block.caption_parts.is_empty() {
                        vec![crate::AttributePart::Text(caption.clone())]
                    } else {
                        block.caption_parts.clone()
                    },
                    numeral: self.numerals.remove(&key),
                    context,
                },
                None => Numbering::None,
            },
            _ => Numbering::None,
        };
        if let Some(id) = block.id.clone() {
            let reftext = self.reftexts.remove(&key);
            let target = Target {
                reftext,
                title,
                order: self.registry.len(),
                numbering,
                inline: false,
            };
            // Ruby names a section (not a discrete heading) in its warning.
            let kind = match &block.kind {
                BlockKind::Heading { .. }
                    if !doctitle
                        && !matches!(block.attrs.style.as_deref(), Some("discrete" | "float")) =>
                {
                    "section"
                }
                _ => "block",
            };
            // Ruby registers a section's id at its title and a block's once
            // reading completes the block.
            let stamp = match kind {
                "section" => self
                    .sections
                    .get(&key)
                    .map(|section| section.diagnostics_before),
                _ => self.block_stamps.get(&key).copied(),
            };
            if let Some(duplicate) = register_id(&mut self.registry, id, target, kind, block.span) {
                self.report(stamp, duplicate);
            }
        } else if let (BlockKind::Heading { inlines, .. }, false, Some(policy)) = (
            &block.kind,
            doctitle || nested_title,
            IdPolicy::new(&attributes),
        ) {
            // Without `sectids` the heading keeps no id and is not registered.
            let id = policy.generate(&inline_text(inlines));
            let unique = policy.unique(id, |candidate| self.registry.contains_key(candidate));
            let target = Target {
                reftext: None,
                title,
                order: self.registry.len(),
                numbering,
                inline: false,
            };
            self.registry.insert(unique.clone(), target);
            block.id = Some(unique);
        }
    }

    fn resolve_attribution(&mut self, block: &mut Block) {
        let credit = self.credits.contains(&(block.span.start, block.span.end));
        let attributes = std::sync::Arc::clone(&block.attribute_context);
        if let BlockKind::Quote {
            attribution: Some(attribution),
            ..
        }
        | BlockKind::Verse {
            attribution: Some(attribution),
            ..
        } = &mut block.kind
        {
            for part in [&mut attribution.author, &mut attribution.citetitle]
                .into_iter()
                .flatten()
            {
                self.resolve_reading(part, &attributes);
            }
            // Ruby splits the converted credit line.
            if credit {
                if let Some(author) = attribution.author.take() {
                    let credit = crate::blockquote_credit::split(author);
                    attribution.author = Some(credit.author);
                    attribution.citetitle = credit.citetitle;
                    attribution.trailing = credit.trailing;
                }
            }
        }
    }
}

/// Where a quote attribution starts in the source.
fn attribution_start(attribution: &crate::ast::Attribution) -> Option<usize> {
    [&attribution.author, &attribution.citetitle]
        .into_iter()
        .flatten()
        .filter_map(|part| part.first())
        .map(|inline| inline.span().start)
        .min()
}

/// Register `id -> reftext` in the registry, warning (at `span`) on a duplicate
/// and keeping the first definition — asciidoctor's behaviour. The duplicate
/// block/anchor still renders its (now ambiguous) id in the backends. Shared by
/// blocks, sections and inline anchors; `kind` names the owner in Ruby's
/// warning.
fn register_id(
    registry: &mut Registry,
    id: String,
    target: Target,
    kind: &str,
    span: Span,
) -> Option<Diagnostic> {
    match registry.entry(id) {
        Entry::Occupied(e) => Some(Diagnostic {
            omitted_span: None,
            report: Default::default(),
            span,
            severity: Severity::Warning,
            message: format!("id assigned to {kind} already in use: {}", e.key()),
        }),
        Entry::Vacant(e) => {
            e.insert(target);
            None
        }
    }
}

/// The automatic id of a manual page's NAME section, read when only the
/// document's id can be registered (`None` with `sectids` unset).
pub(crate) fn section_id(heading: &Block, doc_id: Option<&str>) -> Option<String> {
    let BlockKind::Heading { inlines, .. } = &heading.kind else {
        unreachable!("a section title")
    };
    let policy = IdPolicy::new(&heading.attribute_context)?;
    let id = policy.generate(&inline_text(inlines));
    Some(policy.unique(id, |candidate| doc_id == Some(candidate)))
}

/// Ruby's `Section.generate_id` settings, read from the attributes at the
/// title (`None` when `sectids` is unset, so no id is generated).
struct IdPolicy {
    /// `idprefix`, `_` when unset; inserted verbatim (not lowercased).
    prefix: String,
    /// The first character of `idseparator` (`_` when unset), `None` for an
    /// empty separator, which only deletes spaces.
    separator: Option<char>,
}

impl IdPolicy {
    fn new(attributes: &crate::Attributes) -> Option<Self> {
        attributes.get("sectids")?;
        let prefix = attributes.get("idprefix").unwrap_or("_").to_owned();
        // Ruby keeps only the first character of a longer separator.
        let separator = match attributes.get("idseparator") {
            Some(separator) => separator.chars().next(),
            None => Some('_'),
        };
        Some(Self { prefix, separator })
    }

    /// The id of an (already resolved) title: lowercase it, drop every raw
    /// tag or entity, then characters other than word chars, spaces, hyphens
    /// and dots (InvalidSectionIdCharsRx); prepend the prefix and squeeze runs
    /// of spaces, hyphens, dots and separators into one separator, dropping a
    /// trailing one (and a leading one without a prefix). An all-separator
    /// title yields an empty id, exactly as asciidoctor emits `id=""`.
    fn generate(&self, title: &str) -> String {
        let mut id = self.prefix.clone();
        id.push_str(&strip_invalid(title));
        let Some(separator) = self.separator else {
            return id.replace(' ', "");
        };
        // Ruby's `tr_s " #{sep}.-", sep`.
        let mut squeezed = String::with_capacity(id.len());
        let mut translated = false;
        for ch in id.chars() {
            if matches!(ch, ' ' | '.' | '-') || ch == separator {
                if !translated {
                    squeezed.push(separator);
                }
                translated = true;
            } else {
                squeezed.push(ch);
                translated = false;
            }
        }
        if squeezed.ends_with(separator) {
            squeezed.pop();
        }
        if self.prefix.is_empty() && squeezed.starts_with(separator) {
            squeezed.remove(0);
        }
        squeezed
    }

    /// Make `base` unique against ids already `taken`, appending the
    /// separator and `2`, `3`, … like asciidoctor.
    fn unique(&self, base: String, taken: impl Fn(&str) -> bool) -> String {
        if !taken(&base) {
            return base;
        }
        let separator = self.separator.map(String::from).unwrap_or_default();
        (2u64..)
            .map(|n| format!("{base}{separator}{n}"))
            .find(|candidate| !taken(candidate))
            .expect("an unused id")
    }
}

/// Lowercase `title` and drop what Ruby's InvalidSectionIdCharsRx matches.
fn strip_invalid(title: &str) -> String {
    // InvalidSectionIdCharsRx operates on the substituted lexical title, not
    // decoded visible text. In particular &#65; is removed, not turned into A.
    let title: String = title.chars().flat_map(char::to_lowercase).collect();
    let mut kept = String::with_capacity(title.len());
    let mut offset = 0;
    let mut unclosed_tag = false;
    while offset < title.len() {
        let rest = &title[offset..];
        if rest.starts_with('<') && !unclosed_tag {
            if let Some(end) = rest.find('>') {
                if end > 1 {
                    offset += end + 1;
                    continue;
                }
            } else {
                // Do not repeatedly scan an unfinished run of '<' to EOF.
                unclosed_tag = true;
            }
        }
        if rest.starts_with('&') {
            if let Some(end) =
                crate::entity_references::entity_name_end(title.as_bytes(), offset + 1)
            {
                offset = end;
                continue;
            }
        }
        let ch = rest.chars().next().unwrap();
        offset += ch.len_utf8();
        // Everything else (apostrophe, slash, punctuation, em dash, thin
        // space, …) is dropped, not turned into a separator.
        if matches!(ch, ' ' | '-' | '.') || crate::unicode_word::is_word(ch) {
            kept.push(ch);
        }
    }
    kept
}

/// A lexical view for ID derivation only. Flatten semantic formatting while
/// preserving protection of literal characters and raw attribute boundaries.
pub(crate) fn inline_text(inlines: &[Inline]) -> String {
    let mut s = String::new();
    push_text(inlines, &mut s);
    s
}

fn push_text(inlines: &[Inline], s: &mut String) {
    for inline in inlines {
        match inline {
            Inline::Text { value, .. } => push_protected(value, s),
            Inline::Raw { value, .. } => s.push_str(value),
            Inline::Substituted { parts, .. } => {
                s.push_str(&crate::attributes::reference_text(parts))
            }
            // A missing attribute keeps its literal `{name}`, matching how the
            // backends render it (and so the id reflects the visible text).
            Inline::AttributeRef {
                name, value, parts, ..
            } => match value {
                Some(v) if parts.is_empty() => push_protected(v, s),
                Some(_) => {
                    s.push_str(&crate::attributes::reference_text(parts));
                }
                None => {
                    s.push('{');
                    s.push_str(name);
                    s.push('}');
                }
            },
            Inline::Strong { children, .. }
            | Inline::Emphasis { children, .. }
            | Inline::Monospace { children, .. }
            | Inline::Mark { children, .. }
            | Inline::Superscript { children, .. }
            | Inline::Subscript { children, .. }
            | Inline::Link { children, .. }
            | Inline::CrossReference { children, .. } => {
                // Keep structural boundaries while flattening. Otherwise raw
                // "&co", a formatted "py", and ";" would become a new entity.
                // Empty angle delimiters contribute no ID characters and avoid
                // introducing any backend's choice of formatting tags.
                s.push_str("<>");
                push_text(children, s);
                s.push_str("<>");
            }
            // A text-mode icon (no `icons`) is Ruby's `[alt&#93;` markup:
            // its alt text remains once the tags (and the entity) go.
            Inline::Image { image, .. } if image.icon && image.icons.is_none() => {
                s.push_str("<>[");
                s.push_str(&crate::attributes::reference_text(&image.alt));
                s.push_str("&#93;<>");
            }
            // An anchor or image has no visible text (Ruby removes the
            // generated tags) but still separates lexical runs.
            Inline::Anchor { .. } | Inline::Image { .. } => s.push_str("<>"),
            // Ruby's footnote markup leaves its `[index]` text.
            Inline::Footnote { footnote, .. } => s.push_str(&crate::attributes::reference_text(&[
                crate::AttributePart::Footnote(Box::new(footnote.clone())),
            ])),
            // Ruby's keyboard/button/menu markup leaves its labels (and the
            // caret's entities, which the sanitizer drops).
            Inline::Ui { ui, .. } => s.push_str(&crate::attributes::reference_text(&[
                crate::AttributePart::Ui(Box::new(ui.clone())),
            ])),
            Inline::Stem { stem, .. } => s.push_str(&stem.lexical()),
            // Ruby's flow term leaves its text, a concealed one nothing.
            Inline::IndexTerm { term, .. } => s.push_str(&crate::attributes::reference_text(&[
                crate::AttributePart::IndexTerm(Box::new(term.clone())),
            ])),
        }
    }
}

fn push_protected(text: &str, output: &mut String) {
    for ch in text.chars() {
        match ch {
            '&' => output.push_str("&amp;"),
            '<' => output.push_str("&lt;"),
            '>' => output.push_str("&gt;"),
            _ => output.push(ch),
        }
    }
}

/// Ruby's `DropAnchorRx` over a borrowed label: link and anchor tags are
/// dropped, keeping their text, so a reference never nests links or repeats
/// the target's anchors. Formatting is retained; the original heading and
/// source reference positions remain unchanged.
pub(crate) fn strip_label(inlines: &mut Vec<Inline>) {
    let mut stripped = Vec::with_capacity(inlines.len());
    for mut inline in inlines.drain(..) {
        match &mut inline {
            Inline::Anchor { .. } => {}
            Inline::Link { children, .. } | Inline::CrossReference { children, .. } => {
                strip_label(children);
                stripped.append(children);
            }
            // A footnote marker loses its link: Ruby's DropAnchorRx leaves
            // `<sup class="footnote">[1]</sup>`.
            Inline::Footnote { footnote, span }
                if footnote.kind != crate::FootnoteKind::Unresolved =>
            {
                use crate::AttributePart as Part;
                let definition = footnote.kind == crate::FootnoteKind::Definition;
                let marker = footnote.marker();
                stripped.push(Inline::Substituted {
                    value: marker.clone(),
                    parts: vec![
                        Part::OpenWithAttributes {
                            format: crate::AttributeFormat::Superscript,
                            id: footnote
                                .id
                                .as_ref()
                                .filter(|_| definition)
                                .map(|id| format!("_footnote_{id}")),
                            role: Some(
                                if definition {
                                    "footnote"
                                } else {
                                    "footnoteref"
                                }
                                .into(),
                            ),
                        },
                        Part::Text(marker),
                        Part::Close(crate::AttributeFormat::Superscript),
                    ],
                    span: *span,
                });
            }
            // An image keeps its markup without its link tag.
            Inline::Image { image, .. } => {
                image.attributes.remove("link");
                stripped.push(inline);
            }
            // A keyboard, button or menu macro keeps its markup; links inside
            // its labels lose their tags.
            Inline::Ui { ui, .. } => {
                for label in ui.labels_mut() {
                    strip_parts(label);
                }
                stripped.push(inline);
            }
            Inline::Stem { stem, .. } => {
                strip_parts(&mut stem.parts);
                stripped.push(inline);
            }
            Inline::IndexTerm { term, .. } => {
                for label in term.labels_mut() {
                    strip_parts(label);
                }
                stripped.push(inline);
            }
            Inline::Strong { children, .. }
            | Inline::Emphasis { children, .. }
            | Inline::Monospace { children, .. }
            | Inline::Mark { children, .. }
            | Inline::Superscript { children, .. }
            | Inline::Subscript { children, .. } => {
                strip_label(children);
                stripped.push(inline);
            }
            _ => stripped.push(inline),
        }
    }
    *inlines = stripped;
    strip_attribute_links(inlines);
}

fn strip_attribute_links(inlines: &mut [Inline]) {
    struct Strip;
    impl VisitorMut for Strip {
        fn visit_inline(&mut self, inline: &mut Inline) {
            if let Inline::AttributeRef { parts, .. } | Inline::Substituted { parts, .. } = inline {
                strip_parts(parts);
            }
            visit::walk_inline_mut(self, inline);
        }
    }
    visit::walk_inlines_mut(&mut Strip, inlines);
}

/// Ruby's DropAnchorRx over generated parts: link, anchor and cross-reference
/// tags go, images lose their link, labels of keyboard, button and menu
/// macros are stripped too.
fn strip_parts(parts: &mut Vec<crate::AttributePart>) {
    for part in parts.iter_mut() {
        match part {
            crate::AttributePart::Image(image) => {
                image.attributes.remove("link");
            }
            crate::AttributePart::Ui(ui) => {
                for label in ui.labels_mut() {
                    strip_parts(label);
                }
            }
            crate::AttributePart::Stem(stem) => strip_parts(&mut stem.parts),
            crate::AttributePart::IndexTerm(term) => {
                for label in term.labels_mut() {
                    strip_parts(label);
                }
            }
            _ => {}
        }
    }
    parts.retain(|part| {
        !matches!(
            part,
            crate::AttributePart::OpenLink(_)
                | crate::AttributePart::CloseLink
                | crate::AttributePart::Anchor(_)
                | crate::AttributePart::OpenXref(_)
                | crate::AttributePart::CloseXref
        )
    });
}

#[cfg(test)]
mod tests {
    use crate::ast::{BlockKind, Inline};
    use crate::diagnostic::Severity;

    /// The id assigned to the n-th heading block (0-based), if any.
    fn heading_id(src: &str, nth: usize) -> Option<String> {
        let doc = crate::parse(src).document;
        doc.flat_blocks()
            .iter()
            .filter(|b| matches!(b.kind, BlockKind::Heading { .. }))
            .map(|b| b.id.clone())
            .nth(nth)
            .flatten()
    }

    /// The first cross-reference (target, children) found anywhere in the doc.
    fn first_xref(src: &str) -> (String, Vec<Inline>) {
        fn find(inlines: &[Inline]) -> Option<(String, Vec<Inline>)> {
            for n in inlines {
                match n {
                    Inline::CrossReference { xref, children, .. } => {
                        return Some((xref.refid.clone().unwrap_or_default(), children.clone()))
                    }
                    Inline::Strong { children, .. }
                    | Inline::Emphasis { children, .. }
                    | Inline::Monospace { children, .. }
                    | Inline::Mark { children, .. }
                    | Inline::Superscript { children, .. }
                    | Inline::Subscript { children, .. }
                    | Inline::Link { children, .. } => {
                        if let Some(hit) = find(children) {
                            return Some(hit);
                        }
                    }
                    _ => {}
                }
            }
            None
        }
        let doc = crate::parse(src).document;
        for b in &doc.flat_blocks() {
            let inlines = match &b.kind {
                BlockKind::Heading { inlines, .. } | BlockKind::Paragraph { inlines } => inlines,
                _ => continue,
            };
            if let Some(hit) = find(inlines) {
                return hit;
            }
        }
        panic!("no cross-reference in {src:?}");
    }

    fn text_of(children: &[Inline]) -> String {
        // These resolution assertions compare text, without the temporary
        // structural boundaries used only while deriving IDs.
        super::inline_text(children).replace("<>", "")
    }

    fn generate_id(title: &str) -> String {
        let policy = super::IdPolicy {
            prefix: "_".into(),
            separator: Some('_'),
        };
        policy.generate(title)
    }

    #[test]
    fn generate_id_matches_asciidoctor() {
        // Verified against asciidoctor 2.0.23.
        assert_eq!(generate_id("Hello World"), "_hello_world");
        assert_eq!(generate_id("Hello, World!"), "_hello_world");
        assert_eq!(generate_id("foo & bar"), "_foo_bar");
        assert_eq!(generate_id("1. Intro"), "_1_intro");
        assert_eq!(generate_id("a.b.c"), "_a_b_c");
        assert_eq!(generate_id("a-b-c"), "_a_b_c");
        assert_eq!(generate_id("A/B/C"), "_abc");
        assert_eq!(generate_id("100%"), "_100");
        assert_eq!(generate_id("café déjà"), "_café_déjà");
        // The apostrophe is dropped (the resolved title carries `’`, U+2019).
        assert_eq!(generate_id("It\u{2019}s me"), "_its_me");
        // An all-separator title collapses to the empty id, like asciidoctor.
        assert_eq!(generate_id("___"), "");
    }

    fn policy(prefix: &str, separator: Option<char>) -> super::IdPolicy {
        super::IdPolicy {
            prefix: prefix.into(),
            separator,
        }
    }

    #[test]
    fn id_policy_matches_section_generate_id() {
        // Verified against asciidoctor 2.0.23 (Section.generate_id).
        let cases = [
            (policy("", Some('-')), "-Lead and trail-", "lead-and-trail"),
            (policy("", Some('.')), "a. b - c__d", "a.b.c__d"),
            (policy("Sec.", Some('_')), "Hello World", "Sec_hello_world"),
            (policy("Pre ", Some('-')), "Über  Größe", "Pre-über-größe"),
            // A letter separator is squeezed like Ruby's tr_s.
            (policy("_", Some('x')), "xxlarge x y", "_xlargexy"),
            // An empty separator only deletes spaces.
            (
                policy("sec-", None),
                "-Lead and trail-",
                "sec--leadandtrail-",
            ),
            (policy("sec-", None), "a. b - c", "sec-a.b-c"),
            // The prefix is neither lowercased nor sanitized.
            (policy("A&b;", Some('_')), "C D", "A&b;c_d"),
            (policy("", Some('_')), "___", ""),
        ];
        for (policy, title, expected) in cases {
            assert_eq!(policy.generate(title), expected, "{title}");
        }
        // Combining marks are word characters, as in Ruby's \p{Word}.
        assert_eq!(generate_id("e\u{301}t\u{e9}"), "_e\u{301}t\u{e9}");
    }

    #[test]
    fn id_policy_deduplicates_with_its_separator() {
        let taken = ["dup", "dup-2", "x"];
        let is_taken = |id: &str| taken.contains(&id);
        assert_eq!(
            policy("", Some('-')).unique("dup".into(), is_taken),
            "dup-3"
        );
        assert_eq!(policy("", None).unique("dup".into(), is_taken), "dup2");
        assert_eq!(policy("", None).unique("new".into(), is_taken), "new");
    }

    #[test]
    fn id_policy_reads_attributes_at_each_title() {
        let src = "== One Two\n\n:idprefix: p-\n\n== One Two\n\n:idseparator: --\n\n\
                   === One Two\n\n:idprefix!:\n\n== One Two\n\n[discrete]\n== One Two\n";
        let ids: Vec<_> = (0..5).map(|n| heading_id(src, n)).collect();
        assert_eq!(
            ids,
            [
                "_one_two",
                "p_one_two",
                "p-one-two",
                "_one-two",
                "_one-two-2"
            ]
            .map(|id| Some(id.to_owned()))
        );
    }

    #[test]
    fn unset_sectids_leaves_headings_without_ids() {
        let src = "= Doc\n:sectids!:\n\n== First\n\n[discrete]\n=== Float\n\n\
                   [[x]]\n== Explicit\n\n== Second [[y]]\n\n:sectids:\n\n== Later\n\n\
                   <<_first>> <<First>> <<x>>\n";
        let ids: Vec<_> = (1..6).map(|n| heading_id(src, n)).collect();
        assert_eq!(
            ids,
            [
                None,
                None,
                Some("x".into()),
                Some("y".into()),
                Some("_later".into())
            ]
        );
        // Neither the generated nor the natural id of an unnamed section resolves.
        let messages: Vec<_> = crate::parse(src)
            .diagnostics
            .into_iter()
            .map(|d| d.message)
            .collect();
        assert_eq!(
            messages,
            [
                "unresolved cross reference: '_first'",
                "unresolved cross reference: 'First'"
            ]
        );
    }

    #[test]
    fn generated_ids_cut_a_longer_separator_for_later_reading() {
        // Ruby stores the first character back into the document attribute
        // when it generates an id; explicit ids leave it alone, and body text
        // (converted from the header attributes) still sees the whole value.
        let src = ":idseparator: -+\n\nBefore {idseparator}\n\n[[a]]\n== A {idseparator}\n\n\
                   == B C {idseparator}\n\n== D {idseparator}\n\nAfter {idseparator}\n";
        let doc = crate::parse(src).document;
        let texts: Vec<_> = doc
            .flat_blocks()
            .iter()
            .filter_map(|b| match &b.kind {
                BlockKind::Heading { inlines, .. } | BlockKind::Paragraph { inlines } => {
                    Some((b.id.clone(), text_of(inlines)))
                }
                _ => None,
            })
            .collect();
        let owned = |id: Option<&str>, text: &str| (id.map(str::to_owned), text.to_owned());
        assert_eq!(
            texts,
            [
                owned(None, "Before -+"),
                owned(Some("a"), "A -+"),
                owned(Some("_b-c"), "B C -+"),
                owned(Some("_d"), "D -"),
                owned(None, "After -+"),
            ]
        );
    }

    #[test]
    fn section_gets_auto_id_doctitle_does_not() {
        // Level-1 section gets an id; the level-0 doctitle does not.
        assert_eq!(
            heading_id("= Doc Title\n\n== Real Section\n\nbody", 0),
            None
        );
        assert_eq!(
            heading_id("= Doc Title\n\n== Real Section\n\nbody", 1),
            Some("_real_section".into())
        );
    }

    #[test]
    fn duplicate_titles_get_numbered_ids() {
        let src = "== Intro\n\na\n\n== Intro\n\nb";
        assert_eq!(heading_id(src, 0), Some("_intro".into()));
        assert_eq!(heading_id(src, 1), Some("_intro_2".into()));
    }

    #[test]
    fn textless_reference_resolves_to_section_title() {
        let src = "== Section Two\n\nSee <<_section_two>>.";
        let result = crate::parse(src);
        assert!(
            result.diagnostics.is_empty(),
            "no diagnostic for a known id"
        );
        let (target, children) = first_xref(src);
        assert_eq!(target, "_section_two");
        assert_eq!(text_of(&children), "Section Two");
    }

    #[test]
    fn forward_reference_resolves() {
        // The reference precedes the section it points at.
        let src = "Intro: <<_later>>.\n\n== Later\n\nbody";
        let result = crate::parse(src);
        assert!(result.diagnostics.is_empty());
        let (_, children) = first_xref(src);
        assert_eq!(text_of(&children), "Later");
    }

    #[test]
    fn explicit_reftext_is_kept() {
        let src = "== Section Two\n\nSee <<_section_two,custom>>.";
        let (_, children) = first_xref(src);
        assert_eq!(text_of(&children), "custom");
        assert!(crate::parse(src).diagnostics.is_empty());
    }

    #[test]
    fn resolved_reftext_preserves_formatting() {
        // asciidoctor's basic xref keeps the title's inline markup.
        let src = "== The _good_ part\n\nRef: <<_the_good_part>>.";
        let (_, children) = first_xref(src);
        assert!(
            children
                .iter()
                .any(|n| matches!(n, Inline::Emphasis { .. })),
            "expected emphasis in resolved reftext, got {children:?}"
        );
        assert_eq!(text_of(&children), "The good part");
    }

    #[test]
    fn xref_macro_resolves_like_angle_form() {
        let src = "== Section Two\n\nSee xref:_section_two[].";
        let (target, children) = first_xref(src);
        assert_eq!(target, "_section_two");
        assert_eq!(text_of(&children), "Section Two");
    }

    /// The cross-reference in block `b`'s title, and the paragraph's one.
    fn title_and_paragraph_labels(src: &str) -> (String, crate::Span, String) {
        let result = crate::parse(src);
        assert!(result.diagnostics.is_empty(), "{:?}", result.diagnostics);
        let blocks = result.document.flat_blocks();
        let titled = blocks
            .iter()
            .find(|b| b.id.as_deref() == Some("b"))
            .expect("block b");
        let (span, title) = titled
            .title
            .as_ref()
            .and_then(|t| {
                t.iter().find_map(|n| match n {
                    Inline::CrossReference { children, span, .. } => {
                        Some((*span, text_of(children)))
                    }
                    _ => None,
                })
            })
            .expect("a reference in b's title");
        let paragraph = blocks
            .iter()
            .find_map(|b| match &b.kind {
                BlockKind::Paragraph { inlines } => inlines.iter().find_map(|n| match n {
                    Inline::CrossReference { children, .. } => Some(text_of(children)),
                    _ => None,
                }),
                _ => None,
            })
            .expect("the paragraph's reference");
        (title, span, paragraph)
    }

    #[test]
    fn a_short_label_does_not_convert_the_target_title() {
        // Ruby's `xreftext` with `short` builds a captioned block's label from
        // its signifier and number, so the forward reference does not convert
        // (and memoize) b's title while resolving: the reference inside that
        // title resolves normally later. Without the style (or with `full`)
        // the title is converted inside the label and shows `[a]`.
        let body = ".First\n[#a]\n----\nx\n----\n\nSee <<b>>.\n\n.Second, from <<a>>\n[#b]\n----\ny\n----\n";
        let short = format!(":listing-caption: Example\n:xrefstyle: short\n\n{body}");
        let (title, span, paragraph) = title_and_paragraph_labels(&short);
        assert_eq!(
            (title.as_str(), paragraph.as_str()),
            ("Example 1", "Example 2")
        );
        assert_eq!(&short[span.start..span.end], "<<a>>");
        let full = format!(":listing-caption: Example\n:xrefstyle: full\n\n{body}");
        let (title, _, paragraph) = title_and_paragraph_labels(&full);
        assert_eq!(title, "[a]");
        assert_eq!(paragraph, "Example 2, \u{201c}Second, from [a]\u{201d}");
        let (title, _, paragraph) = title_and_paragraph_labels(body);
        assert_eq!(
            (title.as_str(), paragraph.as_str()),
            ("[a]", "Second, from [a]")
        );
    }

    #[test]
    fn cross_reference_inside_admonition_resolves() {
        // A `<<id>>` in an admonition body must resolve — the resolve pass descends
        // into the admonition's child blocks, not skipping them like verbatim text.
        let src = "== Later\n\nNOTE: see <<_later>>.";
        let result = crate::parse(src);
        assert!(result.diagnostics.is_empty(), "known id, no diagnostic");
        let inlines = result
            .document
            .flat_blocks()
            .iter()
            .find_map(|b| match &b.kind {
                BlockKind::Admonition { blocks, .. } => match &blocks[0].kind {
                    BlockKind::Paragraph { inlines } => Some(inlines.clone()),
                    _ => None,
                },
                _ => None,
            })
            .expect("an admonition block with a paragraph body");
        let children = inlines
            .iter()
            .find_map(|n| match n {
                Inline::CrossReference { children, .. } => Some(children.clone()),
                _ => None,
            })
            .expect("a cross-reference in the admonition body");
        assert_eq!(text_of(&children), "Later");
    }

    #[test]
    fn unknown_id_warns_and_falls_back_to_bracketed_text() {
        let src = "See <<nope>>.";
        let result = crate::parse(src);
        assert_eq!(result.diagnostics.len(), 1);
        assert_eq!(result.diagnostics[0].severity, Severity::Warning);
        // The diagnostic span covers the whole `<<nope>>` construct.
        let span = result.diagnostics[0].span;
        assert_eq!(&src[span.start..span.end], "<<nope>>");
        let (target, children) = first_xref(src);
        assert_eq!(target, "nope");
        assert_eq!(text_of(&children), "[nope]");
    }

    #[test]
    fn unknown_id_with_explicit_text_keeps_text_but_warns() {
        let src = "See <<nope,go there>>.";
        let result = crate::parse(src);
        assert_eq!(result.diagnostics.len(), 1);
        let (_, children) = first_xref(src);
        assert_eq!(text_of(&children), "go there");
    }

    #[test]
    fn textless_ref_to_paragraph_anchor_falls_back_without_diagnostic() {
        // The id is *known* (a paragraph anchor) but has no natural text, so the
        // display falls back to `[id]` — and, unlike an unknown id, no warning.
        let src = "[[pa]]\nHello.\n\nSee <<pa>>.";
        let result = crate::parse(src);
        assert!(
            result.diagnostics.is_empty(),
            "no diagnostic for a known id"
        );
        let (target, children) = first_xref(src);
        assert_eq!(target, "pa");
        assert_eq!(text_of(&children), "[pa]");
    }

    #[test]
    fn textless_ref_to_anchor_reftext_is_display_text() {
        let src = "[[pa,The Para]]\nHello.\n\nSee <<pa>>.";
        let result = crate::parse(src);
        assert!(result.diagnostics.is_empty());
        let (_, children) = first_xref(src);
        assert_eq!(text_of(&children), "The Para");
    }

    #[test]
    fn explicit_anchor_overrides_section_auto_id() {
        // `[[custom]]` before a section replaces the auto id `_real_title`; a
        // textless `<<custom>>` still shows the section's title.
        let src = "[[custom]]\n== Real Title\n\nSee <<custom>>.";
        let result = crate::parse(src);
        assert!(result.diagnostics.is_empty());
        assert_eq!(heading_id(src, 0), Some("custom".into()));
        let (target, children) = first_xref(src);
        assert_eq!(target, "custom");
        assert_eq!(text_of(&children), "Real Title");
    }

    #[test]
    fn explicit_reftext_overrides_section_title() {
        let src = "[[s,Custom Ref]]\n== Real Title\n\nSee <<s>>.";
        let (_, children) = first_xref(src);
        assert_eq!(text_of(&children), "Custom Ref");
        assert!(crate::parse(src).diagnostics.is_empty());
    }

    #[test]
    fn duplicate_explicit_id_warns_once_and_first_wins() {
        let src = "[[dup]]\nFirst.\n\n[[dup]]\nSecond.\n\nSee <<dup>>.";
        let result = crate::parse(src);
        assert_eq!(result.diagnostics.len(), 1);
        assert_eq!(result.diagnostics[0].severity, Severity::Warning);
        assert!(
            result.diagnostics[0].message.contains("already in use"),
            "got: {}",
            result.diagnostics[0].message
        );
        // The first definition (no reftext) wins → textless ref renders `[dup]`.
        let (_, children) = first_xref(src);
        assert_eq!(text_of(&children), "[dup]");
    }

    #[test]
    fn xref_resolves_to_inline_anchor_reftext() {
        // A textless `<<id>>` to an *inline* `[[id,reftext]]` shows the reftext —
        // and resolves forward, the anchor coming after the reference.
        let src = "Go to <<point>>.\n\nSee the [[point,the Important Part]]here.";
        let result = crate::parse(src);
        assert!(result.diagnostics.is_empty(), "known id → no diagnostic");
        let (target, children) = first_xref(src);
        assert_eq!(target, "point");
        assert_eq!(text_of(&children), "the Important Part");
    }

    #[test]
    fn xref_to_textless_inline_anchor_falls_back_without_diagnostic() {
        // The inline anchor's id is known but has no reftext → `[id]`, no warning.
        let src = "Go to <<spot>>.\n\nSee the [[spot]]here.";
        let result = crate::parse(src);
        assert!(result.diagnostics.is_empty(), "known id → no diagnostic");
        let (_, children) = first_xref(src);
        assert_eq!(text_of(&children), "[spot]");
    }

    #[test]
    fn anchor_macro_id_resolves_like_the_shorthand() {
        let src = "Go to <<point>>.\n\nSee anchor:point[the Part] now.";
        let (_, children) = first_xref(src);
        assert_eq!(text_of(&children), "the Part");
    }

    #[test]
    fn duplicate_inline_anchor_and_block_anchor_warns() {
        // An inline `[[dup]]` colliding with an earlier block `[[dup]]` warns once
        // (the first definition wins), like two block anchors.
        let src = "[[dup]]\nFirst.\n\nthen [[dup]]again.";
        let result = crate::parse(src);
        assert_eq!(result.diagnostics.len(), 1);
        assert_eq!(result.diagnostics[0].severity, Severity::Warning);
        assert!(result.diagnostics[0].message.contains("already in use"));
    }

    /// The `caption` of every top-level example block, in document order.
    fn example_captions(src: &str) -> Vec<Option<String>> {
        crate::parse(src)
            .document
            .blocks
            .iter()
            .filter(|b| matches!(b.kind, BlockKind::Example { .. }))
            .map(|b| b.caption.clone())
            .collect()
    }

    #[test]
    fn titled_example_gets_numbered_caption() {
        let src = ".First\n====\none\n====";
        assert_eq!(example_captions(src), vec![Some("Example 1. ".into())]);
    }

    #[test]
    fn two_titled_examples_number_sequentially() {
        let src = ".First\n====\none\n====\n\n.Second\n====\ntwo\n====";
        assert_eq!(
            example_captions(src),
            vec![Some("Example 1. ".into()), Some("Example 2. ".into())]
        );
    }

    #[test]
    fn untitled_example_has_no_caption_and_does_not_advance_counter() {
        // titled, untitled, titled → 1, (none), 2 — the untitled block neither
        // gets a caption nor consumes a number, matching asciidoctor.
        let src = ".First\n====\none\n====\n\n====\nmid\n====\n\n.Third\n====\nthree\n====";
        assert_eq!(
            example_captions(src),
            vec![Some("Example 1. ".into()), None, Some("Example 2. ".into())]
        );
    }

    #[test]
    fn example_caption_attribute_overrides_prefix() {
        let src = ":example-caption: Esempio\n\n.Custom\n====\nx\n====";
        assert_eq!(example_captions(src), vec![Some("Esempio 1. ".into())]);
    }

    #[test]
    fn titled_listing_gets_no_caption() {
        // Only example blocks are numbered; a titled listing keeps a bare title
        // (asciidoctor's `listing-caption` is unset by default).
        let src = ".Code\n----\nputs 1\n----";
        let caption = crate::parse(src)
            .document
            .blocks
            .iter()
            .find(|b| matches!(b.kind, BlockKind::Listing { .. }))
            .and_then(|b| b.caption.clone());
        assert_eq!(caption, None);
    }

    #[test]
    fn example_nested_in_quote_is_numbered_but_quote_is_not() {
        // The caption pass descends into a quote container: a titled example
        // inside a `____` block still gets numbered; the quote carries no caption.
        let src = "____\n.Inner\n====\nx\n====\n____";
        let doc = crate::parse(src).document;
        let quote = &doc.flat_blocks()[0];
        assert!(quote.caption.is_none());
        let inner = match &quote.kind {
            BlockKind::Quote { blocks, .. } => &blocks[0],
            other => panic!("expected quote, got {other:?}"),
        };
        assert_eq!(inner.caption.as_deref(), Some("Example 1. "));
    }
}