carta-readers 0.0.3

Input-format readers: parse a source format's text into the document model.
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
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
//! Reader for the `DokuWiki` markup language.
//!
//! The grammar is line-oriented at the block level and recursive-descent at the inline level. A
//! block is recognised by its first line: a heading (`=` runs), a code or raw passthrough region
//! (`<code>`, `<file>`, `<HTML>`, `<PHP>`), a table (rows opening with `|` or `^`), a list (`*` for
//! bullets, `-` for ordered, indented at least two columns), an indented code block, a thematic
//! break, a blockquote (`>` runs), or, failing all of those, a paragraph. Inline content is scanned
//! left to right with a small pending-text buffer: emphasis (`//`), strong (`**`), underline
//! (`__`), monospace (`''`), the `<sub>`/`<sup>`/`<del>` spans, links (`[[…]]`), media (`{{…}}`),
//! footnotes (`((…))`), bare URLs, and angle-bracket email addresses each form their own node.
//!
//! When the `Smart` extension is enabled, straight quotes fold into curly [`Inline::Quoted`] runs,
//! `--`/`---` fold into en/em dashes, and `...` folds into an ellipsis.

use carta_ast::{
    Alignment, Attr, Block, Caption, Cell, ColSpec, ColWidth, Document, Format, Inline,
    ListAttributes, ListNumberDelim, ListNumberStyle, MathType, QuoteType, Row, Table, TableBody,
    TableFoot, TableHead, Target, to_plain_text,
};
use carta_core::{Extension, Reader, ReaderOptions, Result};
use unicode_normalization::UnicodeNormalization;

use crate::entities;
use crate::heading_ids::{IdRegistry, IdScheme};
use crate::inline_text::trim_inline_ends;

/// The inline-syntax toggles that the scanner threads through every level of parsing.
#[derive(Debug, Clone, Copy)]
struct Ctx {
    /// Straight quotes, dashes, and ellipses fold into their typographic forms.
    smart: bool,
    /// `$…$` and `$$…$$` spans are read as inline and display math.
    math: bool,
}

/// What ends an inline scan started by an enclosing construct.
#[derive(Debug, Clone, Copy)]
enum Closer {
    /// A curly-quote run, closed by the matching straight quote character.
    Quote(char),
    /// A two-character emphasis run (`**`, `//`, `__`), closed by a repeat of the given character.
    Delim(char),
    /// A `''…''` monospace run, closed by `''`.
    Mono,
}

/// Which quote kinds already enclose the current scan. A quote of a kind already open does not open
/// again; the straight quote folds to its apostrophe or curly glyph instead.
#[derive(Debug, Clone, Copy, Default)]
struct QuoteCtx {
    in_single: bool,
    in_double: bool,
}

/// Parses `DokuWiki` markup into the document model.
#[derive(Debug, Default, Clone, Copy)]
pub struct DokuwikiReader;

impl Reader for DokuwikiReader {
    fn read(&self, input: &str, options: &ReaderOptions) -> Result<Document> {
        let ctx = Ctx {
            smart: options.extensions.contains(Extension::Smart),
            math: options.extensions.contains(Extension::TexMathDollars),
        };
        let text = normalize_newlines(input);
        let lines: Vec<&str> = text.split('\n').collect();
        let mut index = 0;
        let mut blocks = parse_blocks(&lines, &mut index, ctx, 0);
        if options.extensions.contains(Extension::EastAsianLineBreaks) {
            strip_wide_line_breaks(&mut blocks);
        }
        // Identifiers are derived only when `auto_identifiers` is on; the gfm variant and the
        // ASCII fold only select the algorithm, they do not enable derivation on their own.
        if options.extensions.contains(Extension::AutoIdentifiers)
            && let Some(scheme) = IdScheme::select(options.extensions, false)
        {
            let ascii = options.extensions.contains(Extension::AsciiIdentifiers);
            let mut registry = IdRegistry::default();
            assign_heading_ids(&mut blocks, scheme, ascii, &mut registry);
        }
        Ok(Document {
            blocks,
            ..Default::default()
        })
    }
}

/// The deepest level of inline or block nesting that recursive parsing will follow. Beyond it,
/// would-be delimiters are taken literally, bounding stack use on adversarial input.
const MAX_DEPTH: usize = 32;

/// Replace Windows and classic-Mac line endings with `\n` so the line-oriented scanner sees one
/// newline convention.
fn normalize_newlines(input: &str) -> String {
    input.replace("\r\n", "\n").replace('\r', "\n")
}

/// Whether `chars` from index `i` begins with the characters of `needle`.
fn matches_at(chars: &[char], i: usize, needle: &str) -> bool {
    needle
        .chars()
        .enumerate()
        .all(|(k, ch)| chars.get(i + k) == Some(&ch))
}

/// Count of leading space characters on a line.
fn leading_spaces(line: &str) -> usize {
    line.chars().take_while(|&c| c == ' ').count()
}

/// The width of one tab stop, in columns. A tab advances to the next multiple of this width.
const TAB_STOP: usize = 4;

/// Expand every tab in `line` to spaces, advancing to the next tab stop. Each non-tab character
/// counts as one column.
fn expand_tabs(line: &str) -> String {
    let mut out = String::new();
    let mut col = 0;
    for c in line.chars() {
        if c == '\t' {
            let next = (col / TAB_STOP + 1) * TAB_STOP;
            for _ in col..next {
                out.push(' ');
            }
            col = next;
        } else {
            out.push(c);
            col += 1;
        }
    }
    out
}

/// The column at which a line's first non-whitespace character sits, counting a tab as the width to
/// the next tab stop.
fn leading_columns(line: &str) -> usize {
    let mut col = 0;
    for c in line.chars() {
        match c {
            '\t' => col = (col / TAB_STOP + 1) * TAB_STOP,
            ' ' => col += 1,
            _ => break,
        }
    }
    col
}

// ===================================================================================================
// Block level
// ===================================================================================================

/// Parse a run of lines into blocks, advancing `index` past the consumed lines.
fn parse_blocks(lines: &[&str], index: &mut usize, ctx: Ctx, depth: usize) -> Vec<Block> {
    let mut blocks = Vec::new();
    while *index < lines.len() {
        let line = lines.get(*index).copied().unwrap_or("");
        if line.trim().is_empty() {
            *index += 1;
            continue;
        }
        if let Some((level, title, trailing)) = header_split(line) {
            blocks.push(Block::Header(
                level,
                Box::default(),
                inline_content(&title, ctx, depth),
            ));
            *index += 1;
            // Content after the closing run is re-parsed as a fresh block of its own.
            if !trailing.trim().is_empty() && depth < MAX_DEPTH {
                let tail = [trailing.as_str()];
                let mut tail_index = 0;
                blocks.append(&mut parse_blocks(&tail, &mut tail_index, ctx, depth + 1));
            }
            continue;
        }
        if let Some(block) = parse_code_or_raw(lines, index) {
            blocks.push(block);
            continue;
        }
        if is_table_line(line) {
            blocks.push(parse_table(lines, index, ctx, depth));
            continue;
        }
        if opens_list(line) {
            blocks.push(parse_list(lines, index, ctx, depth));
            continue;
        }
        if is_indented_code(line) {
            blocks.push(parse_indented_code(lines, index));
            continue;
        }
        if is_thematic_break(line) {
            blocks.push(Block::HorizontalRule);
            *index += 1;
            continue;
        }
        if quote_depth(line).is_some() {
            blocks.push(parse_quote(lines, index, ctx, depth));
            continue;
        }
        blocks.append(&mut parse_paragraph(lines, index, ctx, depth));
    }
    blocks
}

/// Whether the line, as the next line of an open paragraph, would instead begin a new block and so
/// interrupt the paragraph.
fn interrupts_paragraph(line: &str) -> bool {
    line.trim().is_empty()
        || header_split(line).is_some()
        || is_block_tag(line)
        || is_table_line(line)
        || opens_list(line)
        || is_indented_code(line)
        || is_thematic_break(line)
        || quote_depth(line).is_some()
}

/// Gather consecutive non-interrupting lines into a paragraph. An embedded `<code>` or `<file>`
/// region, even mid-line, breaks the run into the text before it, the region as its own block, and
/// the text after it.
fn parse_paragraph(lines: &[&str], index: &mut usize, ctx: Ctx, depth: usize) -> Vec<Block> {
    let mut buffer = String::new();
    let mut first = true;
    while *index < lines.len() {
        let line = lines.get(*index).copied().unwrap_or("");
        if !first && interrupts_paragraph(line) {
            break;
        }
        if !first {
            buffer.push('\n');
        }
        buffer.push_str(line);
        first = false;
        *index += 1;
    }
    split_on_embedded_code(&buffer, ctx, depth)
}

/// Split a paragraph's text on the first embedded `<code>`/`<file>` region that has a closing tag:
/// the text before becomes a paragraph, the region its own code block, and the remainder is split
/// again. Text with no such region is a single paragraph (or nothing, when blank).
fn split_on_embedded_code(text: &str, ctx: Ctx, depth: usize) -> Vec<Block> {
    let chars: Vec<char> = text.chars().collect();
    if depth < MAX_DEPTH
        && let Some((start, block, end)) = find_embedded_code(&chars)
    {
        let mut out = Vec::new();
        let before: String = chars.get(..start).unwrap_or(&[]).iter().collect();
        if !before.trim().is_empty() {
            out.push(Block::Para(inline_content(before.trim(), ctx, depth)));
        }
        out.push(block);
        let after: String = chars.get(end..).unwrap_or(&[]).iter().collect();
        if !after.trim().is_empty() {
            out.append(&mut split_on_embedded_code(&after, ctx, depth + 1));
        }
        out
    } else if text.trim().is_empty() {
        Vec::new()
    } else {
        vec![Block::Para(inline_content(text.trim(), ctx, depth))]
    }
}

/// The first `<code>`/`<file>` region in `chars` that carries a closing tag, as its start index, the
/// parsed code block, and the index just past the closing tag.
fn find_embedded_code(chars: &[char]) -> Option<(usize, Block, usize)> {
    let mut i = 0;
    while i < chars.len() {
        if chars.get(i) == Some(&'<')
            && (named_tag_at(chars, i, "code") || named_tag_at(chars, i, "file"))
            && let Some((block, end)) = parse_raw_region(chars, i)
        {
            return Some((i, block, end));
        }
        i += 1;
    }
    None
}

/// Whether `chars` at `start` opens with `<name` followed by `>` or whitespace.
fn named_tag_at(chars: &[char], start: usize, name: &str) -> bool {
    if chars.get(start) != Some(&'<') {
        return false;
    }
    let after = start + 1 + name.chars().count();
    if !matches_at(chars, start + 1, name) {
        return false;
    }
    matches!(chars.get(after), Some('>')) || chars.get(after).is_some_and(|c| c.is_whitespace())
}

/// A heading line split into its level, title text, and any trailing content after the closing run.
/// A heading opens with two to six `=` and carries no leading whitespace; it closes at the first run
/// of at least two `=` that follows the opening run, and the level is six minus one for each opening
/// `=` beyond the first. Whatever follows the closing run is returned verbatim as trailing content.
/// `None` when the line does not open or never closes a heading.
fn header_split(line: &str) -> Option<(i32, String, String)> {
    if line.starts_with(' ') || line.starts_with('\t') {
        return None;
    }
    let chars: Vec<char> = line.chars().collect();
    let open = chars.iter().take_while(|&&c| c == '=').count();
    if !(2..=6).contains(&open) {
        return None;
    }
    let mut at = open;
    while at < chars.len() {
        if chars.get(at) == Some(&'=') {
            let run = run_length(&chars, at, '=');
            if run >= 2 {
                let title: String = chars.get(open..at).unwrap_or(&[]).iter().collect();
                let trailing: String = chars.get(at + run..).unwrap_or(&[]).iter().collect();
                let level = i32::try_from(7 - open).unwrap_or(1);
                return Some((level, title.trim().to_string(), trailing));
            }
            at += run;
        } else {
            at += 1;
        }
    }
    None
}

/// Whether the line, at column zero, opens a code, file, or raw passthrough region.
fn is_block_tag(line: &str) -> bool {
    starts_named_tag(line, "code")
        || starts_named_tag(line, "file")
        || line.starts_with("<HTML>")
        || line.starts_with("<PHP>")
}

/// Whether `line` opens with `<name` followed by either `>` or whitespace (an attribute list).
fn starts_named_tag(line: &str, name: &str) -> bool {
    let Some(rest) = line.strip_prefix('<').and_then(|l| l.strip_prefix(name)) else {
        return false;
    };
    matches!(rest.chars().next(), Some('>')) || rest.starts_with(|c: char| c.is_whitespace())
}

/// Whether the line opens a table row: it begins with a cell delimiter and yields at least one cell.
/// A lone delimiter with nothing to delimit is ordinary text, not a degenerate one-row table.
fn is_table_line(line: &str) -> bool {
    (line.starts_with('|') || line.starts_with('^')) && !split_row(line).is_empty()
}

/// Whether the line is an indented code line: indented at least two columns and carrying content.
fn is_indented_code(line: &str) -> bool {
    leading_columns(line) >= 2 && !line.trim().is_empty()
}

/// Whether the line is a thematic break: four or more `-` and nothing else. Any other character,
/// including a trailing space, disqualifies it.
fn is_thematic_break(line: &str) -> bool {
    line.len() >= 4 && line.chars().all(|c| c == '-')
}

/// The list marker on a line: its indentation and whether it is ordered (`-`) rather than a bullet
/// (`*`). A marker needs at least two leading spaces and a space after the marker character.
fn list_marker(line: &str) -> Option<(usize, bool)> {
    let indent = leading_spaces(line);
    if indent < 2 {
        return None;
    }
    let chars: Vec<char> = line.chars().collect();
    let marker = chars.get(indent)?;
    let ordered = match marker {
        '*' => false,
        '-' => true,
        _ => return None,
    };
    if chars.get(indent + 1) == Some(&' ') {
        Some((indent, ordered))
    } else {
        None
    }
}

/// The nesting level of a list line: one level for every two columns of indentation, so indents of
/// two and three columns share level one, four and five share level two, and so on.
fn list_level(indent: usize) -> usize {
    indent / 2
}

/// Whether a line opens a list: it carries a list marker that sits at the top level (level one).
/// A marker indented deeper than that does not begin a list and is left to become indented code.
fn opens_list(line: &str) -> bool {
    list_marker(line).is_some_and(|(indent, _)| list_level(indent) == 1)
}

/// The blockquote nesting depth of a line (its run of leading `>`), or `None` when the line is not a
/// quote — a `>` run with no content after it is treated as ordinary text.
fn quote_depth(line: &str) -> Option<usize> {
    if !line.starts_with('>') {
        return None;
    }
    let depth = line.chars().take_while(|&c| c == '>').count();
    let rest = line.get(depth..).unwrap_or("");
    let rest = rest.strip_prefix(' ').unwrap_or(rest);
    if rest.is_empty() { None } else { Some(depth) }
}

/// The kind of region a block-level passthrough tag opens.
enum RawKind {
    /// `<code …>` or `<file …>`: a code block whose first attribute word, when not `-`, is a class.
    Code,
    /// `<HTML>`: an HTML raw block.
    Html,
    /// `<PHP>`: a PHP snippet, wrapped as an HTML raw block.
    Php,
}

/// Parse a code, file, or raw passthrough region beginning at the current line. The opening tag may
/// carry content on its own line after `>`, and the region runs to its closing tag, possibly several
/// lines below. A region that is never closed is not a block here; it stays as ordinary text.
fn parse_code_or_raw(lines: &[&str], index: &mut usize) -> Option<Block> {
    let line = lines.get(*index).copied().unwrap_or("");
    if !is_block_tag(line) {
        return None;
    }
    let joined: String = lines.get(*index..).unwrap_or(&[]).join("\n");
    let chars: Vec<char> = joined.chars().collect();
    let (block, end) = parse_raw_region(&chars, 0)?;
    let consumed = chars
        .get(..end)
        .unwrap_or(&[])
        .iter()
        .filter(|&&c| c == '\n')
        .count();
    *index += consumed + 1;
    Some(block)
}

/// Parse a `<code>`/`<file>`/`<HTML>`/`<PHP>` passthrough region beginning at `start`, returning the
/// block and the index just past its closing tag. `None` when no such opener sits at `start` or the
/// region has no closing tag.
fn parse_raw_region(chars: &[char], start: usize) -> Option<(Block, usize)> {
    let (kind, close) = if named_tag_at(chars, start, "code") {
        (RawKind::Code, "</code>")
    } else if named_tag_at(chars, start, "file") {
        (RawKind::Code, "</file>")
    } else if matches_at(chars, start, "<HTML>") {
        (RawKind::Html, "</HTML>")
    } else if matches_at(chars, start, "<PHP>") {
        (RawKind::Php, "</PHP>")
    } else {
        return None;
    };
    let open_end = (start..chars.len()).find(|&i| chars.get(i) == Some(&'>'))?;
    let attr_text: String = chars
        .get(start + 1..open_end)
        .unwrap_or(&[])
        .iter()
        .collect();
    let content_start = open_end + 1;
    let close_at = find_subsequence(chars, content_start, close)?;
    let mut content: String = chars
        .get(content_start..close_at)
        .unwrap_or(&[])
        .iter()
        .collect();
    if let Some(stripped) = content.strip_prefix('\n') {
        content = stripped.to_string();
    }
    let end = close_at + close.chars().count();
    let block = match kind {
        RawKind::Code => {
            let class = code_language(&attr_text);
            let attr = Attr {
                classes: class.into_iter().map(Into::into).collect(),
                ..Default::default()
            };
            Block::CodeBlock(Box::new(attr), content.into())
        }
        RawKind::Html => Block::RawBlock(Format("html".into()), content.into()),
        RawKind::Php => {
            Block::RawBlock(Format("html".into()), format!("<?php {content} ?>").into())
        }
    };
    Some((block, end))
}

/// The language class of a code or file region: its first attribute word, unless that word is `-`
/// (an explicit "no language") or absent.
fn code_language(attr_text: &str) -> Option<String> {
    let mut words = attr_text.split_whitespace();
    let first = words.next();
    // Skip the tag name itself, which the attribute slice may still carry for `file`/`code`.
    match first {
        Some("code" | "file") => {}
        Some(word) if word != "-" => return Some(word.to_string()),
        _ => return None,
    }
    match words.next() {
        Some(word) if word != "-" => Some(word.to_string()),
        _ => None,
    }
}

/// The index just past the first occurrence of `needle` in `chars` at or after `from`.
fn find_subsequence(chars: &[char], from: usize, needle: &str) -> Option<usize> {
    let len = needle.chars().count();
    (from..=chars.len().saturating_sub(len)).find(|&i| matches_at(chars, i, needle))
}

/// Parse a run of indented code lines. Tabs are expanded to spaces, then the common two-column indent
/// is stripped from each line.
fn parse_indented_code(lines: &[&str], index: &mut usize) -> Block {
    let mut out = String::new();
    while *index < lines.len() {
        let line = lines.get(*index).copied().unwrap_or("");
        if !is_indented_code(line) {
            break;
        }
        let expanded = expand_tabs(line);
        let body = expanded.get(2..).unwrap_or("");
        out.push_str(body);
        out.push('\n');
        *index += 1;
    }
    Block::CodeBlock(Box::default(), out.into())
}

/// Parse a thematically grouped run of list lines into one bullet or ordered list.
fn parse_list(lines: &[&str], index: &mut usize, ctx: Ctx, depth: usize) -> Block {
    let start = *index;
    let mut items = Vec::new();
    while *index < lines.len() {
        let line = lines.get(*index).copied().unwrap_or("");
        let Some((indent, ordered)) = list_marker(line) else {
            break;
        };
        let text: String = line.chars().skip(indent + 2).collect();
        items.push((list_level(indent), ordered, text));
        *index += 1;
    }
    // A line whose level jumps more than one above the line before it does not belong to the list;
    // it (and everything after) is left to be parsed afresh — an over-indented marker becomes
    // indented code.
    let cutoff = list_cutoff(&items);
    let consumed = items.get(..cutoff).unwrap_or(&[]);
    let mut pos = 0;
    let list = build_list(consumed, &mut pos, ctx, depth);
    // A marker-type switch or a dedent below the opening level also ends this list; rewind so the
    // remaining lines are parsed fresh on the next pass.
    *index = start + pos;
    list
}

/// The number of leading items that form one list: the run ends at the first item whose level rises
/// more than one above the item before it.
fn list_cutoff(items: &[(usize, bool, String)]) -> usize {
    let mut previous = None;
    for (i, (level, _, _)) in items.iter().enumerate() {
        if let Some(prev) = previous
            && *level > prev + 1
        {
            return i;
        }
        previous = Some(*level);
    }
    items.len()
}

/// Build one list (and its nested sublists) from the collected items, advancing `pos`. A deeper
/// level opens a child list; the same level with the other marker ends this list.
fn build_list(items: &[(usize, bool, String)], pos: &mut usize, ctx: Ctx, depth: usize) -> Block {
    let (base_level, ordered) = items
        .get(*pos)
        .map_or((0, false), |(level, ordered, _)| (*level, *ordered));
    let mut entries: Vec<Vec<Block>> = Vec::new();
    while let Some((level, item_ordered, text)) = items.get(*pos) {
        if *level < base_level {
            break;
        }
        if *level == base_level {
            if *item_ordered != ordered {
                break;
            }
            let mut blocks = vec![Block::Plain(inline_content(text, ctx, depth))];
            *pos += 1;
            if depth < MAX_DEPTH && items.get(*pos).is_some_and(|(l, _, _)| *l > base_level) {
                blocks.push(build_list(items, pos, ctx, depth + 1));
            }
            entries.push(blocks);
        } else if depth < MAX_DEPTH {
            let child = build_list(items, pos, ctx, depth + 1);
            match entries.last_mut() {
                Some(last) => last.push(child),
                None => entries.push(vec![child]),
            }
        } else {
            *pos += 1;
        }
    }
    if ordered {
        Block::OrderedList(
            ListAttributes {
                start: 1,
                style: ListNumberStyle::DefaultStyle,
                delim: ListNumberDelim::DefaultDelim,
            },
            entries,
        )
    } else {
        Block::BulletList(entries)
    }
}

/// Parse a run of blockquote lines, nesting by `>` depth.
fn parse_quote(lines: &[&str], index: &mut usize, ctx: Ctx, depth: usize) -> Block {
    let mut items = Vec::new();
    while *index < lines.len() {
        let line = lines.get(*index).copied().unwrap_or("");
        let Some(level) = quote_depth(line) else {
            break;
        };
        let rest = line.get(level..).unwrap_or("");
        let rest = rest.strip_prefix(' ').unwrap_or(rest);
        items.push((level, rest.to_string()));
        *index += 1;
    }
    let mut pos = 0;
    Block::BlockQuote(build_quote(&items, &mut pos, 1, ctx, depth))
}

/// Build the blocks of a blockquote at nesting `level`, recursing into deeper runs.
fn build_quote(
    items: &[(usize, String)],
    pos: &mut usize,
    level: usize,
    ctx: Ctx,
    depth: usize,
) -> Vec<Block> {
    let mut blocks = Vec::new();
    while let Some((line_level, _)) = items.get(*pos) {
        if *line_level < level {
            break;
        }
        if *line_level == level {
            let mut inlines = Vec::new();
            while let Some((line_level, text)) = items.get(*pos) {
                if *line_level != level {
                    break;
                }
                if !inlines.is_empty() {
                    inlines.push(Inline::LineBreak);
                }
                inlines.extend(inline_content(text, ctx, depth));
                *pos += 1;
            }
            blocks.push(Block::Plain(inlines));
        } else if depth < MAX_DEPTH {
            blocks.push(Block::BlockQuote(build_quote(
                items,
                pos,
                level + 1,
                ctx,
                depth + 1,
            )));
        } else {
            *pos += 1;
        }
    }
    blocks
}

// ===================================================================================================
// Heading identifiers
// ===================================================================================================

/// Assign a derived identifier to every heading in document order, descending through block
/// containers. The slug is formed from the heading's plain text — folded to ASCII first when `ascii`
/// is set — and made unique within the document by the registry.
fn assign_heading_ids(
    blocks: &mut [Block],
    scheme: IdScheme,
    ascii: bool,
    registry: &mut IdRegistry,
) {
    for block in blocks {
        match block {
            Block::Header(_, attr, inlines) => {
                let text = to_plain_text(inlines);
                let text = if ascii { asciify(&text) } else { text };
                attr.id = registry.assign(scheme, &text).into();
            }
            Block::BlockQuote(children)
            | Block::Div(_, children)
            | Block::Figure(_, _, children) => {
                assign_heading_ids(children, scheme, ascii, registry);
            }
            Block::BulletList(items) | Block::OrderedList(_, items) => {
                for item in items {
                    assign_heading_ids(item, scheme, ascii, registry);
                }
            }
            _ => {}
        }
    }
}

/// Fold text to ASCII by canonical decomposition, dropping every character that is not ASCII so a
/// letter carrying a diacritic keeps its base letter.
fn asciify(text: &str) -> String {
    text.nfd().filter(char::is_ascii).collect()
}

// ===================================================================================================
// East Asian line breaks
// ===================================================================================================

/// Drop soft line breaks that fall between two wide East Asian characters, where the break carries no
/// visual width. The surrounding text runs are left separate rather than merged.
fn strip_wide_line_breaks(blocks: &mut [Block]) {
    for block in blocks {
        match block {
            Block::Para(inlines) | Block::Plain(inlines) | Block::Header(_, _, inlines) => {
                strip_wide_in_inlines(inlines);
            }
            Block::BlockQuote(children)
            | Block::Div(_, children)
            | Block::Figure(_, _, children) => {
                strip_wide_line_breaks(children);
            }
            Block::BulletList(items) | Block::OrderedList(_, items) => {
                for item in items {
                    strip_wide_line_breaks(item);
                }
            }
            _ => {}
        }
    }
}

/// Drop width-free soft breaks within one inline sequence, recursing into nested inline containers.
fn strip_wide_in_inlines(inlines: &mut Vec<Inline>) {
    for inline in inlines.iter_mut() {
        match inline {
            Inline::Emph(children)
            | Inline::Underline(children)
            | Inline::Strong(children)
            | Inline::Strikeout(children)
            | Inline::Superscript(children)
            | Inline::Subscript(children)
            | Inline::SmallCaps(children)
            | Inline::Quoted(_, children)
            | Inline::Cite(_, children)
            | Inline::Link(_, children, _)
            | Inline::Image(_, children, _)
            | Inline::Span(_, children) => strip_wide_in_inlines(children),
            Inline::Note(blocks) => strip_wide_line_breaks(blocks),
            _ => {}
        }
    }
    let mut i = 0;
    while i < inlines.len() {
        if matches!(inlines.get(i), Some(Inline::SoftBreak)) {
            let prev_wide = i
                .checked_sub(1)
                .and_then(|p| inlines.get(p))
                .and_then(last_char)
                .is_some_and(is_east_asian_wide);
            let next_wide = inlines
                .get(i + 1)
                .and_then(first_char)
                .is_some_and(is_east_asian_wide);
            if prev_wide && next_wide {
                inlines.remove(i);
                continue;
            }
        }
        i += 1;
    }
}

/// The last character of an inline's textual content, descending into nested containers.
fn last_char(inline: &Inline) -> Option<char> {
    match inline {
        Inline::Str(s) | Inline::Code(_, s) | Inline::Math(_, s) | Inline::RawInline(_, s) => {
            s.chars().last()
        }
        Inline::Emph(children)
        | Inline::Underline(children)
        | Inline::Strong(children)
        | Inline::Strikeout(children)
        | Inline::Superscript(children)
        | Inline::Subscript(children)
        | Inline::SmallCaps(children)
        | Inline::Quoted(_, children)
        | Inline::Cite(_, children)
        | Inline::Link(_, children, _)
        | Inline::Image(_, children, _)
        | Inline::Span(_, children) => children.iter().rev().find_map(last_char),
        _ => None,
    }
}

/// The first character of an inline's textual content, descending into nested containers.
fn first_char(inline: &Inline) -> Option<char> {
    match inline {
        Inline::Str(s) | Inline::Code(_, s) | Inline::Math(_, s) | Inline::RawInline(_, s) => {
            s.chars().next()
        }
        Inline::Emph(children)
        | Inline::Underline(children)
        | Inline::Strong(children)
        | Inline::Strikeout(children)
        | Inline::Superscript(children)
        | Inline::Subscript(children)
        | Inline::SmallCaps(children)
        | Inline::Quoted(_, children)
        | Inline::Cite(_, children)
        | Inline::Link(_, children, _)
        | Inline::Image(_, children, _)
        | Inline::Span(_, children) => children.iter().find_map(first_char),
        _ => None,
    }
}

/// Whether a character occupies a wide cell in East Asian text (Unicode East Asian Width Wide or
/// Fullwidth). Halfwidth and Ambiguous-width characters are excluded.
fn is_east_asian_wide(c: char) -> bool {
    matches!(c as u32,
        0x1100..=0x115F
        | 0x2E80..=0x2EFF
        | 0x2F00..=0x2FDF
        | 0x2FF0..=0x2FFF
        | 0x3000..=0x303E
        | 0x3041..=0x33FF
        | 0x3400..=0x4DBF
        | 0x4E00..=0x9FFF
        | 0xA000..=0xA4CF
        | 0xA960..=0xA97F
        | 0xAC00..=0xD7A3
        | 0xF900..=0xFAFF
        | 0xFE10..=0xFE19
        | 0xFE30..=0xFE6F
        | 0xFF00..=0xFF60
        | 0xFFE0..=0xFFE6
        | 0x1B000..=0x1B16F
        | 0x1F200..=0x1F2FF
        | 0x20000..=0x2FFFD
        | 0x30000..=0x3FFFD)
}

// ===================================================================================================
// Inline level
// ===================================================================================================

/// The number of speculative delimiter openings an inline scan will attempt before it treats the
/// rest of its input as literal text. Each opener whose closer must be searched for costs one unit,
/// so this bounds the backtracking work an adversarial delimiter-dense run can provoke while staying
/// far above what any genuine document consumes.
fn inline_budget(len: usize) -> usize {
    len.saturating_mul(8).saturating_add(64).min(200_000)
}

/// Parse a block's inline content: scan it, then drop leading and trailing whitespace.
fn inline_content(text: &str, ctx: Ctx, depth: usize) -> Vec<Inline> {
    let chars: Vec<char> = text.chars().collect();
    let mut pos = 0;
    let mut budget = inline_budget(chars.len());
    let (mut inlines, _) = scan(
        &chars,
        &mut pos,
        None,
        ctx,
        QuoteCtx::default(),
        depth,
        &mut budget,
    );
    trim_inline_ends(&mut inlines);
    inlines
}

/// Scan a slice of characters as inline content with no surrounding-quote context.
fn scan_slice(chars: &[char], ctx: Ctx, depth: usize) -> Vec<Inline> {
    let mut pos = 0;
    let mut budget = inline_budget(chars.len());
    let (inlines, _) = scan(
        chars,
        &mut pos,
        None,
        ctx,
        QuoteCtx::default(),
        depth,
        &mut budget,
    );
    inlines
}

/// Push the buffered text as a `Str` and clear the buffer.
fn flush(pending: &mut String, out: &mut Vec<Inline>) {
    if !pending.is_empty() {
        out.push(Inline::Str(std::mem::take(pending).into()));
    }
}

/// Scan characters into inlines from `*pos`. When `end` is set, the scan stops and reports `true` on
/// the matching closing delimiter; otherwise it runs to the end and reports `false`.
#[allow(clippy::too_many_lines)]
fn scan(
    chars: &[char],
    pos: &mut usize,
    end: Option<Closer>,
    ctx: Ctx,
    qctx: QuoteCtx,
    depth: usize,
    budget: &mut usize,
) -> (Vec<Inline>, bool) {
    let start = *pos;
    let mut out: Vec<Inline> = Vec::new();
    let mut pending = String::new();
    while let Some(&c) = chars.get(*pos) {
        if let Some(closer) = end
            && at_closer(chars, *pos, start, closer)
        {
            flush(&mut pending, &mut out);
            *pos += closer_width(closer);
            return (coalesce(out), true);
        }
        if c.is_ascii_alphabetic()
            && boundary_before(chars, *pos)
            && let Some((link, end)) = try_autolink(chars, *pos)
        {
            flush(&mut pending, &mut out);
            out.push(link);
            *pos = end;
            continue;
        }
        match c {
            ' ' | '\t' | '\n' => scan_whitespace_run(chars, pos, &mut pending, &mut out),
            '&' => {
                if let Some((decoded, next)) =
                    entities::read_reference(chars, *pos, chars.len(), true)
                {
                    pending.push_str(&decoded);
                    *pos = next;
                } else {
                    pending.push('&');
                    *pos += 1;
                }
            }
            '\\' if chars.get(*pos + 1) == Some(&'\\') => {
                scan_hard_break(chars, pos, &mut pending, &mut out);
            }
            '\\' if ctx.math && chars.get(*pos + 1) == Some(&'$') => {
                // A backslash-escaped dollar is literal text, not a math delimiter.
                pending.push('\\');
                pending.push('$');
                *pos += 2;
            }
            '*' if chars.get(*pos + 1) == Some(&'*') && depth < MAX_DEPTH => {
                handle_delim(
                    chars,
                    pos,
                    '*',
                    ctx,
                    qctx,
                    depth,
                    budget,
                    &mut pending,
                    &mut out,
                    Inline::Strong,
                );
            }
            '/' if chars.get(*pos + 1) == Some(&'/') && depth < MAX_DEPTH => {
                handle_delim(
                    chars,
                    pos,
                    '/',
                    ctx,
                    qctx,
                    depth,
                    budget,
                    &mut pending,
                    &mut out,
                    Inline::Emph,
                );
            }
            '_' if chars.get(*pos + 1) == Some(&'_') && depth < MAX_DEPTH => {
                handle_delim(
                    chars,
                    pos,
                    '_',
                    ctx,
                    qctx,
                    depth,
                    budget,
                    &mut pending,
                    &mut out,
                    Inline::Underline,
                );
            }
            '\'' if chars.get(*pos + 1) == Some(&'\'') => {
                handle_mono_or_quote(chars, pos, ctx, qctx, depth, budget, &mut pending, &mut out);
            }
            '\'' | '"' if ctx.smart => {
                handle_quote(
                    chars,
                    pos,
                    c,
                    ctx,
                    qctx,
                    depth,
                    budget,
                    &mut pending,
                    &mut out,
                );
            }
            '$' if ctx.math => {
                handle_math(chars, pos, &mut pending, &mut out);
            }
            '-' if ctx.smart => {
                let run = run_length(chars, *pos, '-');
                pending.push_str(&fold_dashes(run));
                *pos += run;
            }
            '.' if ctx.smart => {
                let run = run_length(chars, *pos, '.');
                pending.push_str(&fold_ellipsis(run));
                *pos += run;
            }
            '[' if chars.get(*pos + 1) == Some(&'[') && depth < MAX_DEPTH => {
                handle_construct(chars, pos, c, ctx, depth, budget, &mut pending, &mut out);
            }
            '{' if chars.get(*pos + 1) == Some(&'{') && depth < MAX_DEPTH => {
                handle_construct(chars, pos, c, ctx, depth, budget, &mut pending, &mut out);
            }
            '(' if chars.get(*pos + 1) == Some(&'(') && depth < MAX_DEPTH => {
                handle_construct(chars, pos, c, ctx, depth, budget, &mut pending, &mut out);
            }
            '%' if chars.get(*pos + 1) == Some(&'%') => {
                handle_construct(chars, pos, c, ctx, depth, budget, &mut pending, &mut out);
            }
            '<' if depth < MAX_DEPTH => {
                handle_construct(chars, pos, c, ctx, depth, budget, &mut pending, &mut out);
            }
            '~' if chars.get(*pos + 1) == Some(&'~') => {
                handle_construct(chars, pos, c, ctx, depth, budget, &mut pending, &mut out);
            }
            other => {
                pending.push(other);
                *pos += 1;
            }
        }
    }
    flush(&mut pending, &mut out);
    (coalesce(out), end.is_none())
}

/// Whether the scan's closing delimiter sits at `pos`. The two-character closers must follow at least
/// one character of content and lean against non-whitespace on their left.
fn at_closer(chars: &[char], pos: usize, start: usize, closer: Closer) -> bool {
    match closer {
        Closer::Quote(quote) => {
            chars.get(pos) == Some(&quote) && can_close_quote(chars, pos, quote)
        }
        Closer::Delim(delim) => {
            chars.get(pos) == Some(&delim)
                && chars.get(pos + 1) == Some(&delim)
                && pos > start
                && chars.get(pos - 1).is_some_and(|c| !c.is_whitespace())
        }
        Closer::Mono => {
            chars.get(pos) == Some(&'\'')
                && chars.get(pos + 1) == Some(&'\'')
                && pos > start
                && chars.get(pos - 1).is_some_and(|c| !c.is_whitespace())
        }
    }
}

/// The number of characters a closing delimiter occupies.
fn closer_width(closer: Closer) -> usize {
    match closer {
        Closer::Quote(_) => 1,
        Closer::Delim(_) | Closer::Mono => 2,
    }
}

/// Handle a `''` opener: a monospace run when both delimiters flank non-whitespace content,
/// otherwise — under smart typography — the two quotes fold individually, and otherwise the opener
/// stays literal.
#[allow(clippy::too_many_arguments)]
fn handle_mono_or_quote(
    chars: &[char],
    pos: &mut usize,
    ctx: Ctx,
    qctx: QuoteCtx,
    depth: usize,
    budget: &mut usize,
    pending: &mut String,
    out: &mut Vec<Inline>,
) {
    if depth < MAX_DEPTH
        && let Some((node, end)) = parse_mono(chars, *pos, ctx, depth, budget)
    {
        flush(pending, out);
        out.push(node);
        *pos = end;
    } else if ctx.smart {
        handle_quote(chars, pos, '\'', ctx, qctx, depth, budget, pending, out);
    } else {
        pending.push('\'');
        *pos += 1;
    }
}

/// Consume a run of spaces, tabs, and newlines at `*pos`, emitting a single break: a soft break
/// when the run contains a newline, an ordinary space otherwise.
fn scan_whitespace_run(
    chars: &[char],
    pos: &mut usize,
    pending: &mut String,
    out: &mut Vec<Inline>,
) {
    flush(pending, out);
    let mut has_newline = false;
    while let Some(&w) = chars.get(*pos) {
        match w {
            '\n' => {
                has_newline = true;
                *pos += 1;
            }
            ' ' | '\t' => *pos += 1,
            _ => break,
        }
    }
    out.push(if has_newline {
        Inline::SoftBreak
    } else {
        Inline::Space
    });
}

/// Handle a `\\` sequence at `*pos`: a hard line break when followed by whitespace or the line end,
/// and two literal backslashes otherwise.
fn scan_hard_break(chars: &[char], pos: &mut usize, pending: &mut String, out: &mut Vec<Inline>) {
    let after = chars.get(*pos + 2);
    if after.is_none_or(|c| c.is_whitespace()) {
        flush(pending, out);
        out.push(Inline::LineBreak);
        *pos += 2;
        if after.is_some() {
            *pos += 1;
        }
    } else {
        pending.push('\\');
        pending.push('\\');
        *pos += 2;
    }
}

/// Try to parse the inline construct introduced by `c` at `pos`: a link (`[[`), media (`{{`), a
/// footnote (`((`), a verbatim span (`%%`), an angle-bracket construct (`<`), or a dropped macro
/// (`~~`). Returns the produced nodes and the index past the construct.
fn scan_construct(
    chars: &[char],
    pos: usize,
    c: char,
    ctx: Ctx,
    depth: usize,
) -> Option<(Vec<Inline>, usize)> {
    match c {
        '[' => parse_link(chars, pos).map(|(node, end)| (vec![node], end)),
        '{' => parse_media(chars, pos).map(|(node, end)| (vec![node], end)),
        '(' => parse_footnote(chars, pos, ctx, depth).map(|(node, end)| (vec![node], end)),
        '%' => parse_nowiki_pct(chars, pos),
        '<' => parse_angle(chars, pos, ctx, depth),
        '~' => parse_macro(chars, pos).map(|end| (Vec::new(), end)),
        _ => None,
    }
}

/// Dispatch an inline construct opener at `*pos`: on a successful parse the produced nodes are
/// appended and `*pos` advances past the construct; otherwise the opener is buffered literally and
/// `*pos` advances one character.
#[allow(clippy::too_many_arguments)]
fn handle_construct(
    chars: &[char],
    pos: &mut usize,
    c: char,
    ctx: Ctx,
    depth: usize,
    budget: &mut usize,
    pending: &mut String,
    out: &mut Vec<Inline>,
) {
    // Parsing a construct recurses (footnotes even re-parse their interior as blocks), and an
    // enclosing emphasis run that fails to close discards its scan and re-scans the same span — so
    // the same construct can be parsed many times over. Charge the shared backtracking budget by the
    // span consumed, so that repeated re-parsing of a region cannot exceed the input-proportional
    // budget and the total work stays linear.
    if *budget > 0
        && let Some((mut nodes, end)) = scan_construct(chars, *pos, c, ctx, depth)
    {
        *budget = budget.saturating_sub((end - *pos).max(1));
        flush(pending, out);
        out.append(&mut nodes);
        *pos = end;
    } else {
        pending.push(c);
        *pos += 1;
    }
}

/// Wrap a generic two-character emphasis run, or, when no valid closer exists, emit the opener
/// literally and resume scanning right after it. The run's content is scanned recursively, so a
/// would-be inner marker that cannot close is taken as text and an outer marker that the inner run
/// consumed past never pairs.
#[allow(clippy::too_many_arguments)]
fn handle_delim(
    chars: &[char],
    pos: &mut usize,
    delim: char,
    ctx: Ctx,
    qctx: QuoteCtx,
    depth: usize,
    budget: &mut usize,
    pending: &mut String,
    out: &mut Vec<Inline>,
    wrap: fn(Vec<Inline>) -> Inline,
) {
    let begin = *pos;
    // The opener must lean against following non-whitespace content, and searching for its closer
    // must stay within the backtracking budget.
    if !is_ws_opt(chars.get(begin + 2).copied()) && *budget > 0 {
        *budget -= 1;
        let mut scan_pos = begin + 2;
        let (inner, closed) = scan(
            chars,
            &mut scan_pos,
            Some(Closer::Delim(delim)),
            ctx,
            qctx,
            depth + 1,
            budget,
        );
        if closed {
            flush(pending, out);
            out.push(wrap(inner));
            *pos = scan_pos;
            return;
        }
        // No closer: the opener is literal text and the speculative scan is thrown away, but the
        // outer scan resumes just past the opener and, in a delimiter-dense run, would re-scan the
        // same span from each following opener in turn. Charge the shared budget by the span scanned
        // so repeated failed opens stay linear in the input rather than quadratic (an OOM vector).
        *budget = budget.saturating_sub(scan_pos - begin);
    }
    pending.push(delim);
    pending.push(delim);
    *pos = begin + 2;
}

/// Try to open a curly-quote run at `*pos`; on a missing closer, leave the opener as the apt quote
/// glyph and let the scan reprocess what follows. An empty run is kept for double quotes but folds to
/// apostrophes for single quotes.
#[allow(clippy::too_many_arguments)]
fn handle_quote(
    chars: &[char],
    pos: &mut usize,
    quote: char,
    ctx: Ctx,
    qctx: QuoteCtx,
    depth: usize,
    budget: &mut usize,
    pending: &mut String,
    out: &mut Vec<Inline>,
) {
    let begin = *pos;
    if can_open_quote(chars, begin, quote, qctx) && depth < MAX_DEPTH && *budget > 0 {
        *budget -= 1;
        *pos = begin + 1;
        let mut inner_qctx = qctx;
        if quote == '\'' {
            inner_qctx.in_single = true;
        } else {
            inner_qctx.in_double = true;
        }
        let (inner, closed) = scan(
            chars,
            pos,
            Some(Closer::Quote(quote)),
            ctx,
            inner_qctx,
            depth + 1,
            budget,
        );
        if closed && (quote == '"' || !inner.is_empty()) {
            flush(pending, out);
            out.push(Inline::Quoted(quote_type(quote), inner));
            return;
        }
        // As in `handle_delim`: an unpaired opener rewinds to just past itself, so charge the span
        // the failed scan covered to keep a quote-dense run from being re-scanned quadratically.
        *budget = budget.saturating_sub(pos.saturating_sub(begin));
        *pos = begin + 1;
    } else {
        *pos = begin + 1;
    }
    pending.push(quote_glyph(chars, begin, quote));
}

/// The quote-node kind for a straight quote character.
fn quote_type(quote: char) -> QuoteType {
    if quote == '\'' {
        QuoteType::SingleQuote
    } else {
        QuoteType::DoubleQuote
    }
}

/// The curly glyph a non-paired straight quote folds into: an apostrophe for `'`, and an opening or
/// closing double quote depending on which side it leans.
fn quote_glyph(chars: &[char], pos: usize, quote: char) -> char {
    if quote == '\'' {
        '\u{2019}'
    } else if left_flanking(chars, pos) {
        '\u{201c}'
    } else {
        '\u{201d}'
    }
}

/// Monospace run `''…''`: its interior is parsed and then flattened to text. The run forms only when
/// the opener is followed by a non-space, the closer preceded by a non-space, and the interior is
/// non-empty; otherwise the opener is not a monospace marker.
///
/// Under smart typography the interior is scanned with quote folding active: any typographic quotes
/// that pair within the run are rendered as their glyphs, but if a straight quote inside disrupts the
/// closing `''` so the run never closes, the opener is not a monospace marker after all.
fn parse_mono(
    chars: &[char],
    begin: usize,
    ctx: Ctx,
    depth: usize,
    budget: &mut usize,
) -> Option<(Inline, usize)> {
    if is_ws_opt(chars.get(begin + 2).copied()) {
        return None;
    }
    if ctx.smart {
        if *budget == 0 {
            return None;
        }
        *budget -= 1;
        let mut pos = begin + 2;
        let (inner, closed) = scan(
            chars,
            &mut pos,
            Some(Closer::Mono),
            ctx,
            QuoteCtx::default(),
            depth + 1,
            budget,
        );
        if !closed {
            return None;
        }
        return Some((
            Inline::Code(Box::default(), flatten_mono(&inner).into()),
            pos,
        ));
    }
    let close = find_subsequence(chars, begin + 2, "''")?;
    if close <= begin + 2 || is_ws_opt(chars.get(close - 1).copied()) {
        return None;
    }
    let content = chars.get(begin + 2..close).unwrap_or(&[]);
    let inner = scan_slice(content, ctx, depth + 1);
    Some((
        Inline::Code(Box::default(), to_plain_text(&inner).into()),
        close + 2,
    ))
}

/// Flatten monospace interior inlines to text, rendering a quoted run as its curly quote glyphs so
/// folded quotation survives inside the code span.
fn flatten_mono(inlines: &[Inline]) -> String {
    let mut out = String::new();
    push_mono_text(inlines, &mut out);
    out
}

fn push_mono_text(inlines: &[Inline], out: &mut String) {
    for inline in inlines {
        match inline {
            Inline::Str(text) | Inline::Code(_, text) | Inline::Math(_, text) => out.push_str(text),
            Inline::Space | Inline::SoftBreak | Inline::LineBreak => out.push(' '),
            Inline::Quoted(QuoteType::SingleQuote, xs) => {
                out.push('\u{2018}');
                push_mono_text(xs, out);
                out.push('\u{2019}');
            }
            Inline::Quoted(QuoteType::DoubleQuote, xs) => {
                out.push('\u{201c}');
                push_mono_text(xs, out);
                out.push('\u{201d}');
            }
            Inline::Emph(xs)
            | Inline::Underline(xs)
            | Inline::Strong(xs)
            | Inline::Strikeout(xs)
            | Inline::Superscript(xs)
            | Inline::Subscript(xs)
            | Inline::SmallCaps(xs)
            | Inline::Cite(_, xs)
            | Inline::Link(_, xs, _)
            | Inline::Image(_, xs, _)
            | Inline::Span(_, xs) => push_mono_text(xs, out),
            Inline::RawInline(..) | Inline::Note(_) => {}
        }
    }
}

/// Handle a `$` opener under dollar-math: a `$$…$$` display span when the next character is also `$`,
/// otherwise a `$…$` inline span. A failed attempt emits a single literal `$` and resumes scanning at
/// the following character, so an unmatched dollar is taken as text.
fn handle_math(chars: &[char], pos: &mut usize, pending: &mut String, out: &mut Vec<Inline>) {
    let begin = *pos;
    let parsed = if chars.get(begin + 1) == Some(&'$') {
        parse_display_math(chars, begin)
    } else {
        parse_inline_math(chars, begin)
    };
    if let Some((node, end)) = parsed {
        flush(pending, out);
        out.push(node);
        *pos = end;
    } else {
        pending.push('$');
        *pos = begin + 1;
    }
}

/// A `$$…$$` display-math span: its interior is taken verbatim. `None` when the span has no closer or
/// encloses nothing.
fn parse_display_math(chars: &[char], begin: usize) -> Option<(Inline, usize)> {
    let close = find_subsequence(chars, begin + 2, "$$")?;
    if close <= begin + 2 {
        return None;
    }
    let content: String = chars.get(begin + 2..close).unwrap_or(&[]).iter().collect();
    Some((
        Inline::Math(MathType::DisplayMath, content.into()),
        close + 2,
    ))
}

/// A `$…$` inline-math span: the opener must be followed by a non-space, the closer preceded by a
/// non-space and not followed by a digit. Its interior is taken verbatim.
fn parse_inline_math(chars: &[char], begin: usize) -> Option<(Inline, usize)> {
    if is_ws_opt(chars.get(begin + 1).copied()) {
        return None;
    }
    let mut j = begin + 1;
    while j < chars.len() {
        if chars.get(j) == Some(&'$')
            && j > begin + 1
            && chars.get(j - 1).is_some_and(|c| !c.is_whitespace())
            && !chars.get(j + 1).is_some_and(char::is_ascii_digit)
        {
            let content: String = chars.get(begin + 1..j).unwrap_or(&[]).iter().collect();
            return Some((Inline::Math(MathType::InlineMath, content.into()), j + 1));
        }
        j += 1;
    }
    None
}

/// The number of consecutive `ch` at `pos`.
fn run_length(chars: &[char], pos: usize, ch: char) -> usize {
    let mut n = 0;
    while chars.get(pos + n) == Some(&ch) {
        n += 1;
    }
    n
}

/// Fold a run of `n` hyphens into em and en dashes: every three become an em dash, a remaining two a
/// single en dash, a remaining one a hyphen.
fn fold_dashes(n: usize) -> String {
    let mut s = "\u{2014}".repeat(n / 3);
    match n % 3 {
        2 => s.push('\u{2013}'),
        1 => s.push('-'),
        _ => {}
    }
    s
}

/// Fold a run of `n` dots: every three become an ellipsis, with any remainder kept as dots.
fn fold_ellipsis(n: usize) -> String {
    let mut s = "\u{2026}".repeat(n / 3);
    s.push_str(&".".repeat(n % 3));
    s
}

// --- flanking ---

/// The character before `pos`, if any.
fn before_char(chars: &[char], pos: usize) -> Option<char> {
    pos.checked_sub(1).and_then(|p| chars.get(p)).copied()
}

/// Whether an optional character is whitespace, treating a missing character (a boundary) as
/// whitespace.
fn is_ws_opt(opt: Option<char>) -> bool {
    opt.is_none_or(char::is_whitespace)
}

/// Whether a character slice is empty or all whitespace.
fn is_blank(chars: &[char]) -> bool {
    chars.iter().all(|c| c.is_whitespace())
}

/// Whether an optional character is punctuation, treating a missing character as not punctuation.
fn is_punct_opt(opt: Option<char>) -> bool {
    opt.is_some_and(is_punct)
}

/// Whether a character counts as punctuation for flanking: ASCII punctuation, or any other
/// non-alphanumeric, non-whitespace character.
fn is_punct(c: char) -> bool {
    c.is_ascii_punctuation() || (!c.is_alphanumeric() && !c.is_whitespace())
}

/// Whether the single character at `pos` is left-flanking (it leans against following content).
fn left_flanking(chars: &[char], pos: usize) -> bool {
    let before = before_char(chars, pos);
    let after = chars.get(pos + 1).copied();
    !is_ws_opt(after) && (!is_punct_opt(after) || is_ws_opt(before) || is_punct_opt(before))
}

/// Whether the single character at `pos` is right-flanking (it leans against preceding content).
fn right_flanking(chars: &[char], pos: usize) -> bool {
    let before = before_char(chars, pos);
    let after = chars.get(pos + 1).copied();
    !is_ws_opt(before) && (!is_punct_opt(before) || is_ws_opt(after) || is_punct_opt(after))
}

/// Whether a straight quote at `pos` may open a quoted run. A quote whose kind already encloses the
/// position may not open again, so nested same-kind quotation never forms.
fn can_open_quote(chars: &[char], pos: usize, quote: char, qctx: QuoteCtx) -> bool {
    if (quote == '\'' && qctx.in_single) || (quote == '"' && qctx.in_double) {
        return false;
    }
    left_flanking(chars, pos)
}

/// Whether a straight quote at `pos` may close a quoted run. A single quote may not close against a
/// following alphanumeric, so a word-internal apostrophe never ends a quotation.
fn can_close_quote(chars: &[char], pos: usize, quote: char) -> bool {
    if !right_flanking(chars, pos) {
        return false;
    }
    if quote == '\'' {
        !chars.get(pos + 1).is_some_and(|c| c.is_alphanumeric())
    } else {
        true
    }
}

/// Whether `pos` sits at a non-alphanumeric boundary (the start of a word for autolink purposes).
fn boundary_before(chars: &[char], pos: usize) -> bool {
    before_char(chars, pos).is_none_or(|c| !c.is_alphanumeric())
}

// --- bare URL autolinking ---

/// Match a bare URL beginning at `pos` (`scheme://…`), returning the link and the end index.
fn try_autolink(chars: &[char], pos: usize) -> Option<(Inline, usize)> {
    let mut k = pos;
    while chars
        .get(k)
        .is_some_and(|&c| c.is_ascii_alphanumeric() || matches!(c, '.' | '+' | '-'))
    {
        k += 1;
    }
    if !matches_at(chars, k, "://") {
        return None;
    }
    let scheme: String = chars.get(pos..k)?.iter().collect::<String>().to_lowercase();
    if !crate::url_schemes::is_scheme(&scheme) {
        return None;
    }
    let content_start = k + 3;
    let scan_end = forward_scan(chars, pos);
    let end = trim_trailing(chars, content_start, scan_end);
    if end <= content_start {
        return None;
    }
    let url: String = chars.get(pos..end)?.iter().collect();
    Some((
        Inline::Link(
            Box::default(),
            vec![Inline::Str(url.clone().into())],
            Box::new(Target {
                url: url.into(),
                title: carta_ast::Text::default(),
            }),
        ),
        end,
    ))
}

/// Walk a URL run forward, stopping at whitespace or `<`, balancing parentheses, and ending at an
/// unbalanced `)` or a `]` outside any parenthesis.
fn forward_scan(chars: &[char], from: usize) -> usize {
    let mut depth: i32 = 0;
    let mut j = from;
    while let Some(&c) = chars.get(j) {
        if c.is_whitespace() || c == '<' {
            break;
        }
        match c {
            '(' => depth += 1,
            ')' | ']' if depth == 0 => break,
            ')' => depth -= 1,
            _ => {}
        }
        j += 1;
    }
    j
}

/// Drop trailing punctuation from a URL run, never below `min`. A trailing `;` takes a preceding
/// `&entity;` with it.
fn trim_trailing(chars: &[char], min: usize, mut end: usize) -> usize {
    while end > min {
        match chars.get(end - 1) {
            Some('!' | '"' | '\'' | '*' | ',' | '.' | ':' | '?' | '_' | '~') => end -= 1,
            Some(';') => {
                let mut j = end - 1;
                while j > min
                    && chars
                        .get(j - 1)
                        .is_some_and(|&c| c.is_ascii_alphanumeric() || c == '#')
                {
                    j -= 1;
                }
                end = if j > min && chars.get(j - 1) == Some(&'&') {
                    j - 1
                } else {
                    end - 1
                };
            }
            _ => break,
        }
    }
    end
}

// --- post-processing ---

/// Merge adjacent text runs and collapse adjacent whitespace into a single token (preferring a hard
/// space), so dropped macros and split apostrophes leave no doubled spacing or fragmented words.
fn coalesce(inlines: Vec<Inline>) -> Vec<Inline> {
    let mut out: Vec<Inline> = Vec::with_capacity(inlines.len());
    for inline in inlines {
        match inline {
            Inline::Str(s) => {
                if let Some(Inline::Str(prev)) = out.last_mut() {
                    prev.push_str(&s);
                } else if !s.is_empty() {
                    out.push(Inline::Str(s));
                }
            }
            Inline::Space | Inline::SoftBreak => match out.last() {
                Some(Inline::Space) => {}
                Some(Inline::SoftBreak) => {
                    if matches!(inline, Inline::Space)
                        && let Some(slot) = out.last_mut()
                    {
                        *slot = Inline::Space;
                    }
                }
                _ => out.push(inline),
            },
            other => out.push(other),
        }
    }
    out
}

/// Split text into `Str` words separated by single whitespace tokens, with no markup interpretation.
fn tokenize_text(text: &str) -> Vec<Inline> {
    let mut out = Vec::new();
    let mut word = String::new();
    for c in text.chars() {
        if c.is_whitespace() {
            if !word.is_empty() {
                out.push(Inline::Str(std::mem::take(&mut word).into()));
            }
            let token = if c == '\n' {
                Inline::SoftBreak
            } else {
                Inline::Space
            };
            if !matches!(out.last(), Some(Inline::Space | Inline::SoftBreak)) {
                out.push(token);
            }
        } else {
            word.push(c);
        }
    }
    if !word.is_empty() {
        out.push(Inline::Str(word.into()));
    }
    out
}

// --- links and media ---

/// Parse a `[[target|label]]` link, returning the link node and its end index. A bracket pair whose
/// target side (the text before the first `|`) is entirely empty is not a link; the opener stays
/// literal.
fn parse_link(chars: &[char], start: usize) -> Option<(Inline, usize)> {
    let close = find_subsequence(chars, start + 2, "]]")?;
    let inner: String = chars.get(start + 2..close).unwrap_or(&[]).iter().collect();
    let (raw_target, label) = match inner.split_once('|') {
        Some((t, l)) => (t, Some(l.to_string())),
        None => (inner.as_str(), None),
    };
    if raw_target.is_empty() {
        return None;
    }
    let target = raw_target.trim().to_string();
    let (url, display) = classify_link_target(&target);
    // An explicit but empty label falls back to the target's auto-display text.
    let label_inlines = match label {
        Some(text) if !text.trim().is_empty() => tokenize_text(text.trim()),
        _ => vec![Inline::Str(display.into())],
    };
    Some((
        Inline::Link(
            Box::default(),
            label_inlines,
            Box::new(Target {
                url: url.into(),
                title: carta_ast::Text::default(),
            }),
        ),
        close + 2,
    ))
}

/// Resolve a link target to its destination URL and auto-display text.
fn classify_link_target(target: &str) -> (String, String) {
    if target.starts_with("\\\\") || is_external(target) {
        (target.to_string(), target.to_string())
    } else if let Some((prefix, rest)) = target.split_once('>') {
        (interwiki_url(prefix, rest), rest.to_string())
    } else {
        (resolve_id(target), display_id(target))
    }
}

/// Parse a `{{image?query|caption}}` media reference into an image, or, when the query opts out of
/// embedding, a link.
fn parse_media(chars: &[char], start: usize) -> Option<(Inline, usize)> {
    let close = find_subsequence(chars, start + 2, "}}")?;
    let inner: String = chars.get(start + 2..close).unwrap_or(&[]).iter().collect();
    let end = close + 2;

    let leading_space = inner.starts_with(char::is_whitespace);
    let (spec, caption) = match inner.split_once('|') {
        Some((s, c)) => (s, Some(c)),
        None => (inner.as_str(), None),
    };
    // A brace pair whose source side (before the first `|`) is empty is not a media reference.
    if spec.is_empty() {
        return None;
    }
    let trailing_space = spec.ends_with(char::is_whitespace);
    let mut classes = Vec::new();
    if let Some(class) = media_align(leading_space, trailing_space) {
        classes.push(class.into());
    }

    let spec = spec.trim();
    let (id, query) = match spec.split_once('?') {
        Some((i, q)) => (i, Some(q)),
        None => (spec, None),
    };
    let url = if is_external(id) {
        id.to_string()
    } else {
        resolve_id(id)
    };
    // An explicit but empty caption falls back to the source's auto-display text.
    let alt = match caption {
        Some(text) if !text.trim().is_empty() => tokenize_text(text.trim()),
        _ if is_external(id) => vec![Inline::Str(id.into())],
        _ => vec![Inline::Str(display_id(id).into())],
    };
    let target = Target {
        url: url.into(),
        title: carta_ast::Text::default(),
    };

    let node = match query {
        Some(q) if q.contains("linkonly") => Inline::Link(
            Box::new(Attr {
                classes,
                ..Default::default()
            }),
            alt,
            Box::new(target),
        ),
        Some(q) => {
            let (width, height) = parse_size(q);
            let mut attributes = Vec::new();
            if let Some(w) = width {
                attributes.push(("width".to_string(), w));
            }
            if let Some(h) = height {
                attributes.push(("height".to_string(), h));
            }
            attributes.push(("query".to_string(), format!("?{q}")));
            Inline::Image(
                Box::new(Attr {
                    classes,
                    attributes: attributes
                        .into_iter()
                        .map(|(k, v)| (k.into(), v.into()))
                        .collect(),
                    ..Default::default()
                }),
                alt,
                Box::new(target),
            )
        }
        None => Inline::Image(
            Box::new(Attr {
                classes,
                ..Default::default()
            }),
            alt,
            Box::new(target),
        ),
    };
    Some((node, end))
}

/// The alignment class for a media reference, from whether its braces carry interior padding.
fn media_align(leading: bool, trailing: bool) -> Option<&'static str> {
    match (leading, trailing) {
        (true, true) => Some("align-center"),
        (false, true) => Some("align-left"),
        (true, false) => Some("align-right"),
        (false, false) => None,
    }
}

/// Parse the leading `width` and optional `xheight` of a media query into pixel strings.
fn parse_size(query: &str) -> (Option<String>, Option<String>) {
    let chars: Vec<char> = query.chars().collect();
    let mut i = 0;
    let mut width = String::new();
    while let Some(&c) = chars.get(i) {
        if c.is_ascii_digit() {
            width.push(c);
            i += 1;
        } else {
            break;
        }
    }
    if width.is_empty() {
        return (None, None);
    }
    let mut height = String::new();
    if matches!(chars.get(i), Some('x' | 'X')) {
        i += 1;
        while let Some(&c) = chars.get(i) {
            if c.is_ascii_digit() {
                height.push(c);
                i += 1;
            } else {
                break;
            }
        }
    }
    let height = if height.is_empty() {
        None
    } else {
        Some(height)
    };
    (Some(width), height)
}

/// Whether a target names an external destination: a known scheme followed by `://`.
fn is_external(s: &str) -> bool {
    match s.find("://") {
        Some(idx) => {
            let scheme = s.get(..idx).unwrap_or("");
            !scheme.is_empty()
                && scheme
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '+' | '-'))
                && crate::url_schemes::is_scheme(&scheme.to_lowercase())
        }
        None => false,
    }
}

/// Resolve a page identifier to a site-relative URL. A namespaced id becomes a slash path, rooted
/// unless it is relative (a leading `.`); an id with no namespace is left untouched.
fn resolve_id(id: &str) -> String {
    if !id.contains(':') {
        return id.to_string();
    }
    if let Some(rest) = id.strip_prefix('.') {
        return rest.trim_start_matches('.').replace(':', "/");
    }
    let replaced = id.replace(':', "/");
    if replaced.starts_with('/') {
        replaced
    } else {
        format!("/{replaced}")
    }
}

/// The display text for a bare page identifier: the segment after the last namespace separator.
fn display_id(id: &str) -> String {
    match id.rsplit_once(':') {
        Some((_, last)) => last.to_string(),
        None => id.to_string(),
    }
}

/// Map an interwiki shortcut and its tail to a destination URL.
fn interwiki_url(prefix: &str, rest: &str) -> String {
    match prefix {
        "wp" => format!("https://en.wikipedia.org/wiki/{rest}"),
        "wpfr" => format!("https://fr.wikipedia.org/wiki/{rest}"),
        "wpde" => format!("https://de.wikipedia.org/wiki/{rest}"),
        "wpes" => format!("https://es.wikipedia.org/wiki/{rest}"),
        "wpjp" => format!("https://jp.wikipedia.org/wiki/{rest}"),
        "wppl" => format!("https://pl.wikipedia.org/wiki/{rest}"),
        "doku" => format!("https://www.dokuwiki.org/{rest}"),
        "phpfn" => format!("https://secure.php.net/{rest}"),
        "callto" => format!("callto://{rest}"),
        other => format!("{other}>{rest}"),
    }
}

// --- footnotes, nowiki, angle tags, macros ---

/// Parse a `((…))` footnote into a note holding the block content of its body. A body that is empty
/// or only whitespace is not a footnote, so the opener stays literal.
fn parse_footnote(chars: &[char], begin: usize, ctx: Ctx, depth: usize) -> Option<(Inline, usize)> {
    let close = find_subsequence(chars, begin + 2, "))")?;
    let inner: String = chars.get(begin + 2..close).unwrap_or(&[]).iter().collect();
    if inner.trim().is_empty() {
        return None;
    }
    Some((
        Inline::Note(parse_blocks_str(&inner, ctx, depth + 1)),
        close + 2,
    ))
}

/// Parse a `%%…%%` no-formatting span: its content is taken verbatim as text. Like the emphasis
/// markers, the opener needs a non-whitespace character after it and the closer one before it, so a
/// `%%` adjacent to a space stays literal.
fn parse_nowiki_pct(chars: &[char], begin: usize) -> Option<(Vec<Inline>, usize)> {
    if chars.get(begin + 2).is_none_or(|c| c.is_whitespace()) {
        return None;
    }
    let mut j = begin + 2;
    while j < chars.len() {
        if chars.get(j) == Some(&'%')
            && chars.get(j + 1) == Some(&'%')
            && j > begin + 2
            && chars.get(j - 1).is_some_and(|c| !c.is_whitespace())
        {
            let inner: String = chars.get(begin + 2..j).unwrap_or(&[]).iter().collect();
            return Some((tokenize_text(&inner), j + 2));
        }
        j += 1;
    }
    None
}

/// Parse an angle-bracket inline construct: the markup spans, a verbatim span, raw HTML/PHP, or an
/// email address.
fn parse_angle(
    chars: &[char],
    begin: usize,
    ctx: Ctx,
    depth: usize,
) -> Option<(Vec<Inline>, usize)> {
    // A span tag with a blank interior is not markup; the opener stays literal text.
    if let Some((inner, end)) = tag_region(chars, begin, "<sub>", "</sub>")
        && !is_blank(&inner)
    {
        return Some((
            vec![Inline::Subscript(scan_slice(&inner, ctx, depth + 1))],
            end,
        ));
    }
    if let Some((inner, end)) = tag_region(chars, begin, "<sup>", "</sup>")
        && !is_blank(&inner)
    {
        return Some((
            vec![Inline::Superscript(scan_slice(&inner, ctx, depth + 1))],
            end,
        ));
    }
    if let Some((inner, end)) = tag_region(chars, begin, "<del>", "</del>")
        && !is_blank(&inner)
    {
        return Some((
            vec![Inline::Strikeout(scan_slice(&inner, ctx, depth + 1))],
            end,
        ));
    }
    if let Some((inner, end)) = tag_region(chars, begin, "<nowiki>", "</nowiki>") {
        let text: String = inner.iter().collect();
        return Some((tokenize_text(&text), end));
    }
    if let Some((inner, end)) = tag_region(chars, begin, "<html>", "</html>") {
        let text: String = inner.iter().collect();
        return Some((
            vec![Inline::RawInline(Format("html".into()), text.into())],
            end,
        ));
    }
    if let Some((inner, end)) = tag_region(chars, begin, "<php>", "</php>") {
        let text: String = inner.iter().collect();
        return Some((
            vec![Inline::RawInline(
                Format("html".into()),
                format!("<?php {text} ?>").into(),
            )],
            end,
        ));
    }
    angle_email(chars, begin).map(|(node, end)| (vec![node], end))
}

/// The interior characters and end index of an `open…close` tag region starting at `start`.
fn tag_region(chars: &[char], start: usize, open: &str, close: &str) -> Option<(Vec<char>, usize)> {
    if !matches_at(chars, start, open) {
        return None;
    }
    let content_start = start + open.chars().count();
    let close_at = find_subsequence(chars, content_start, close)?;
    let inner = chars.get(content_start..close_at).unwrap_or(&[]).to_vec();
    Some((inner, close_at + close.chars().count()))
}

/// Parse `<local@domain>` into a `mailto:` link.
fn angle_email(chars: &[char], start: usize) -> Option<(Inline, usize)> {
    if chars.get(start) != Some(&'<') {
        return None;
    }
    let mut j = start + 1;
    while let Some(&c) = chars.get(j) {
        if c == '>' {
            break;
        }
        if c.is_whitespace() || c == '<' {
            return None;
        }
        j += 1;
    }
    if chars.get(j) != Some(&'>') {
        return None;
    }
    let inner: String = chars.get(start + 1..j).unwrap_or(&[]).iter().collect();
    let (local, domain) = inner.split_once('@')?;
    if local.is_empty() || !domain.contains('.') || domain.starts_with('.') || domain.ends_with('.')
    {
        return None;
    }
    let url = format!("mailto:{inner}");
    Some((
        Inline::Link(
            Box::default(),
            vec![Inline::Str(inner.into())],
            Box::new(Target {
                url: url.into(),
                title: carta_ast::Text::default(),
            }),
        ),
        j + 1,
    ))
}

/// Recognise a dropped page macro (`~~NOTOC~~`, `~~NOCACHE~~`), returning its end index.
fn parse_macro(chars: &[char], start: usize) -> Option<usize> {
    for token in ["~~NOTOC~~", "~~NOCACHE~~"] {
        if matches_at(chars, start, token) {
            return Some(start + token.chars().count());
        }
    }
    None
}

/// Split text into lines and parse them as blocks.
fn parse_blocks_str(text: &str, ctx: Ctx, depth: usize) -> Vec<Block> {
    let lines: Vec<&str> = text.split('\n').collect();
    let mut index = 0;
    parse_blocks(&lines, &mut index, ctx, depth)
}

// ===================================================================================================
// Tables
// ===================================================================================================

/// Parse a run of table rows. The first row sets the column count and per-column alignment, and is
/// the header row when it opens with `^`; all remaining rows form the single body.
fn parse_table(lines: &[&str], index: &mut usize, ctx: Ctx, depth: usize) -> Block {
    let mut rows: Vec<(bool, Vec<String>)> = Vec::new();
    while *index < lines.len() {
        let line = lines.get(*index).copied().unwrap_or("");
        if !is_table_line(line) {
            break;
        }
        rows.push((line.starts_with('^'), split_row(line)));
        *index += 1;
    }

    let first = rows.first();
    let col_count = first.map_or(0, |(_, cells)| cells.len());
    let col_specs: Vec<ColSpec> = first
        .map(|(_, cells)| {
            cells
                .iter()
                .map(|cell| ColSpec {
                    align: cell_align(cell),
                    width: ColWidth::ColWidthDefault,
                })
                .collect()
        })
        .unwrap_or_default();

    let mut head_rows = Vec::new();
    let mut body_rows = Vec::new();
    for (i, (header, cells)) in rows.iter().enumerate() {
        let row = build_row(cells, col_count, ctx, depth);
        if i == 0 && *header {
            head_rows.push(row);
        } else {
            body_rows.push(row);
        }
    }

    Block::Table(Box::new(Table {
        attr: Attr::default(),
        caption: Caption::default(),
        col_specs,
        head: TableHead {
            attr: Attr::default(),
            rows: head_rows,
        },
        bodies: vec![TableBody {
            attr: Attr::default(),
            row_head_columns: 0,
            head: Vec::new(),
            body: body_rows,
        }],
        foot: TableFoot::default(),
    }))
}

/// Build a table row, fitting it to `col_count` by truncating extra cells and padding short rows.
fn build_row(cells: &[String], col_count: usize, ctx: Ctx, depth: usize) -> Row {
    let mut out = Vec::with_capacity(col_count);
    for i in 0..col_count {
        let trimmed = cells.get(i).map_or("", |c| c.trim());
        let content = if trimmed.is_empty() {
            Vec::new()
        } else {
            vec![Block::Plain(inline_content(trimmed, ctx, depth))]
        };
        out.push(Cell {
            attr: Attr::default(),
            align: Alignment::AlignDefault,
            row_span: 1,
            col_span: 1,
            content,
        });
    }
    Row {
        attr: Attr::default(),
        cells: out,
    }
}

/// The column alignment implied by a raw cell's padding: at least two spaces on a side anchors that
/// side, both anchors centre, neither leaves the default.
fn cell_align(raw: &str) -> Alignment {
    let leading = raw.chars().take_while(|&c| c == ' ').count();
    let trailing = raw.chars().rev().take_while(|&c| c == ' ').count();
    match (leading >= 2, trailing >= 2) {
        (true, true) => Alignment::AlignCenter,
        (_, true) => Alignment::AlignLeft,
        (true, _) => Alignment::AlignRight,
        _ => Alignment::AlignDefault,
    }
}

/// Split a table row into its raw cell texts, treating `|` and `^` as delimiters but ignoring those
/// inside links, media, monospace, no-format spans, and verbatim regions.
fn split_row(line: &str) -> Vec<String> {
    let chars: Vec<char> = line.chars().collect();
    let mut segments: Vec<String> = Vec::new();
    let mut seg = String::new();
    let mut i = 0;
    while i < chars.len() {
        if let Some(skip) = protected_end(&chars, i) {
            seg.extend(chars.get(i..skip).unwrap_or(&[]));
            i = skip;
            continue;
        }
        match chars.get(i) {
            Some('|' | '^') => {
                segments.push(std::mem::take(&mut seg));
                i += 1;
            }
            Some(&c) => {
                seg.push(c);
                i += 1;
            }
            None => break,
        }
    }
    segments.push(seg);
    if !segments.is_empty() {
        segments.remove(0);
    }
    if segments.last().is_some_and(String::is_empty) {
        segments.pop();
    }
    segments
}

/// If a protected span opens at `i`, the index just past its closing delimiter (or the end of the
/// line when it is unterminated).
fn protected_end(chars: &[char], i: usize) -> Option<usize> {
    for (open, close) in [("[[", "]]"), ("{{", "}}"), ("''", "''"), ("%%", "%%")] {
        if matches_at(chars, i, open) {
            let from = i + open.chars().count();
            let end = find_subsequence(chars, from, close)
                .map_or(chars.len(), |p| p + close.chars().count());
            return Some(end);
        }
    }
    if matches_at(chars, i, "<nowiki>") {
        let from = i + "<nowiki>".chars().count();
        let end = find_subsequence(chars, from, "</nowiki>")
            .map_or(chars.len(), |p| p + "</nowiki>".chars().count());
        return Some(end);
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Reads with the default option set and reports only whether the read completed without error,
    /// so a pathological input can be checked for graceful, bounded-time handling.
    fn reads_ok(input: &str) -> bool {
        DokuwikiReader
            .read(input, &ReaderOptions::default())
            .is_ok()
    }

    #[test]
    fn adversarial_footnotes_under_open_emphasis_do_not_stall() {
        // Each `((…))` footnote re-parses its interior, and an emphasis run that fails to close
        // discards its scan and re-scans the same span — so overlapping footnotes and unclosed `//`
        // openers once re-parsed the same regions a super-linear number of times, which a nightly
        // fuzz run hit as a timeout. Charging the inline backtracking budget for each construct
        // bounds how often a region can be re-parsed; the pre-fix code blew up exponentially on an
        // input a fraction of this size.
        let input = format!("(({}))", "//((x)) ".repeat(400));
        assert!(reads_ok(&input));
    }

    #[test]
    fn adversarially_nested_footnotes_do_not_stall() {
        let input = format!("{}x{}", "((".repeat(2_000), "))".repeat(2_000));
        assert!(reads_ok(&input));
    }

    #[test]
    fn a_delimiter_dense_run_does_not_blow_up() {
        // An emphasis opener with no closer discards its speculative scan and rewinds to just past
        // itself, so a run of unclosed `//` openers whose would-be closers are all whitespace-led
        // (never valid) was re-scanned from every position — quadratic work that allocated a
        // discarded inline tree each time. A nightly fuzz run hit this as an out-of-memory on a
        // sub-kilobyte input. Charging the backtracking budget for the scanned span keeps it linear.
        let input = "//a ".repeat(4_000);
        assert!(reads_ok(&input));
    }
}