carta-readers 0.0.2

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
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
//! Block-structure phase: consume input line by line into a tree of [`IrBlock`]s, following the
//! `CommonMark` spec's open-block algorithm (spec appendix "A parsing strategy"). Leaf text is left
//! raw for the inline phase; link reference definitions are stripped from paragraph fronts and
//! collected into the [`RefMap`].

use carta_ast::{Attr, Format, ListAttributes, ListNumberDelim, ListNumberStyle};
use carta_core::{Extension, Extensions};

use super::cursor::{Cursor, FenceInfo, ListMarkerParse};
use super::{
    ExampleMap, FootnoteDefs, IrBlock, IrDefItem, RefMap, TAB_STOP, attr, grid, html_block, scan,
    table, texttable,
};

/// Parse the normalized input into the block tree plus the collected link, footnote, and example
/// references.
pub(crate) fn parse(
    input: &str,
    extensions: Extensions,
    greedy_paragraphs: bool,
) -> (Vec<IrBlock>, RefMap, FootnoteDefs, ExampleMap) {
    let mut parser = Parser::new(extensions, greedy_paragraphs);
    let lines = split_lines(input);
    for index in 0..lines.len() {
        let line = lines.get(index).copied().unwrap_or("");
        let following = lines.get(index + 1..).unwrap_or(&[]);
        parser.process_line(line, following);
    }
    parser.finalize_open_text_tables();
    parser.finish()
}

/// Split into lines on `\n`, dropping a single trailing empty line produced by a final newline.
fn split_lines(input: &str) -> Vec<&str> {
    if input.is_empty() {
        return Vec::new();
    }
    let mut lines: Vec<&str> = input.split('\n').collect();
    if input.ends_with('\n') {
        lines.pop();
    }
    lines
}

#[derive(Debug, Clone)]
enum Kind {
    Document,
    BlockQuote,
    List(ListInfo),
    Item(ItemInfo),
    /// A footnote definition, holding its normalized label. Its content is gathered like a list
    /// item (a four-column continuation indent) and collected out of the body by [`Parser::finish`].
    FootnoteDef(String),
    /// A fenced div (see [`DivInfo`]). Content is parsed recursively; a bare colon-run line of at
    /// least the opening length closes it.
    FencedDiv(DivInfo),
    Paragraph,
    /// A line block: each source line is appended raw (a `|`-led line opens a new entry, an
    /// indented line continues the previous). The lines are split apart and prepared in
    /// [`Parser::build_block`].
    LineBlock,
    /// A definition list, holding one [`Kind::DefinitionItem`] per term. A transparent container:
    /// it consumes nothing on continuation and defers to its items.
    DefinitionList,
    /// One term of a definition list: its raw term text and whether the entry is tight (its
    /// definition paragraphs render as `Plain` rather than `Para`). A transparent container holding
    /// one [`Kind::Definition`] per `:`/`~` marker.
    DefinitionItem {
        term: String,
        tight: bool,
    },
    /// One definition body of a definition list. Its content continues under a four-column indent
    /// like a list item; `indent` is the column its content begins at.
    Definition {
        indent: usize,
    },
    Heading(i32),
    IndentedCode,
    FencedCode(FenceInfo),
    HtmlBlock(u8),
    /// A raw HTML block in the Markdown family when inner content is not parsed (neither
    /// `native_divs` nor `markdown_in_html_blocks` applies). A block-level open tag at the left
    /// margin begins a span that accumulates lines verbatim — nested same-name tags counted, blank
    /// lines kept — until a close tag brings `depth` back to zero; the whole span is one `RawBlock`.
    /// A self-closing, void, or bare close tag opens a span already at `depth` zero: a single line.
    RawHtmlSpan {
        tag: String,
        depth: usize,
    },
    /// A block-level HTML element whose inner content is parsed as markdown. A `<div>` (with
    /// `native_divs` enabled) becomes an [`IrBlock::Div`] carrying the tag's attributes; any other
    /// recognized block tag (with `markdown_in_html_blocks` enabled) keeps its open and close tags as
    /// raw HTML with the parsed content between them. The element is a transparent container: nested
    /// same-name elements nest as their own containers, so tag balancing falls out of the tree.
    HtmlElement(HtmlElementInfo),
    /// A raw TeX environment opened by `\begin{NAME}` at a line start. It accumulates lines verbatim
    /// until a matching `\end{NAME}` brings the nesting `depth` back to zero, then becomes a
    /// `RawBlock` for the `tex` format. `name` is the literal brace content of the opener, compared
    /// exactly. Math environments (`equation`, `align`, …) are excluded — they stay inline.
    RawTex {
        name: String,
        depth: usize,
    },
    ThematicBreak,
    /// A dash-ruled table candidate, accumulating its physical lines (each `\n`-terminated). Its
    /// exact extent is settled when the block closes: the lines are parsed into a table, with any
    /// surplus rows after the table re-fed as following blocks, or — when they form no table — the
    /// leaf is repurposed into the thematic break or paragraph the lines actually are.
    TextTable,
}

#[derive(Debug, Clone)]
struct ListInfo {
    bullet: bool,
    marker: u8,
    style: ListNumberStyle,
    delim: ListNumberDelim,
    start: i32,
}

#[derive(Debug, Clone)]
struct ItemInfo {
    /// Column indent required for a continuation line to belong to this item.
    indent: usize,
    /// For an example-list item, its `@label` (or `None` for the anonymous `@`); `None` for every
    /// other item. The label resolves later `@label` references to this item's number.
    example_label: Option<String>,
}

#[derive(Debug, Clone)]
struct HtmlElementInfo {
    /// The lowercased tag name (e.g. `div`, `section`), used to recognize the matching close tag.
    tag: String,
    /// Attributes parsed from the open tag; only meaningful when `as_div` holds.
    attr: Attr,
    /// The open tag's raw text, kept verbatim for the leading raw block when not rendered as a div.
    raw_open: String,
    /// The matching close tag's raw text, kept verbatim for the trailing raw block when not a div.
    /// Empty until the element is closed (or it closed implicitly at end of input).
    raw_close: String,
    /// When set, the element renders as an [`IrBlock::Div`]; otherwise the open/close tags are kept
    /// as raw HTML around the parsed content.
    as_div: bool,
    /// Whether the element's final content block tightens from `Para` to `Plain` (set when no blank
    /// line separates that content from the close tag).
    tighten_last: bool,
}

#[derive(Debug, Clone)]
struct DivInfo {
    /// The opening fence's colon-run length; a closing fence must be at least this long.
    fence: usize,
    /// The column the opening fence began at. Continuation lines re-base to this column, so the
    /// indentation of inner blocks is measured relative to it rather than the line start.
    indent: usize,
    attr: Attr,
}

/// Outcome of the phase-1 container descent for one line.
struct Descent {
    /// The deepest container that matched the line's continuation markers.
    container: usize,
    /// Whether every open container matched (a `false` marks where lazy continuation and block
    /// closing apply).
    all_matched: bool,
    /// The fenced divs matched on the descent, innermost last, each with the line as it stood at
    /// that div's indentation.
    div_path: Vec<(usize, String)>,
    /// Set when an open leaf consumed the whole line, so no further processing is needed.
    consumed: bool,
}

#[derive(Debug)]
struct Node {
    kind: Kind,
    open: bool,
    parent: usize,
    children: Vec<usize>,
    text: String,
    /// The visual column this block's first line began at, before its leading indentation was
    /// consumed. Recorded for paragraphs so a dash ruling on the next line can read a headed
    /// table's column alignment against the header's true position; zero for every other block.
    indent: usize,
    /// Render this paragraph as `Plain` rather than `Para`. Set when a block-level HTML element
    /// interrupts the paragraph with no blank line between, so the interrupted paragraph reads tight.
    as_plain: bool,
    /// Whether the line that followed this block (while it was the deepest open block) was blank.
    /// Drives loose-vs-tight list classification.
    last_line_blank: bool,
}

impl Node {
    fn new(kind: Kind) -> Self {
        Node {
            kind,
            open: true,
            parent: 0,
            children: Vec::new(),
            text: String::new(),
            indent: 0,
            as_plain: false,
            last_line_blank: false,
        }
    }
}

/// How an open paragraph absorbs the block openers on the next line (see [`Parser::greedy_gates`]).
// Four independent fold decisions, each governing a distinct opener — they are flags by nature.
#[allow(clippy::struct_excessive_bools)]
#[derive(Clone, Copy, Default)]
struct GreedyGates {
    /// The foldable openers — block quote, heading, thematic break, fenced div, footnote definition
    /// — continue the paragraph as a lazy line rather than interrupting it.
    foldable: bool,
    /// A list marker that would *start* a fresh list folds; one continuing an open list still opens.
    list_start: bool,
    /// The block-quote fold, gated further on `blank_before_blockquote`.
    blockquote: bool,
    /// The heading fold, gated further on `blank_before_header`.
    heading: bool,
}

struct Parser {
    nodes: Vec<Node>,
    refs: RefMap,
    extensions: Extensions,
    /// When set, most block openers do not interrupt an open paragraph (see
    /// [`ReaderOptions::greedy_paragraphs`](carta_core::ReaderOptions::greedy_paragraphs)).
    greedy_paragraphs: bool,
    /// Set while a code fence that could not open a code block (its info names no language, or it
    /// has no closing fence) is folding into a paragraph. Until a matching closing fence or a blank
    /// line, each following line is absorbed as paragraph text with no block opener allowed to fire.
    fence_fold: Option<FenceInfo>,
}

impl Parser {
    fn new(extensions: Extensions, greedy_paragraphs: bool) -> Self {
        Parser {
            nodes: vec![Node::new(Kind::Document)],
            refs: RefMap::new(),
            extensions,
            greedy_paragraphs,
            fence_fold: None,
        }
    }

    fn kind(&self, index: usize) -> Option<&Kind> {
        self.nodes.get(index).map(|node| &node.kind)
    }

    fn last_open_child(&self, index: usize) -> Option<usize> {
        let node = self.nodes.get(index)?;
        let &last = node.children.last()?;
        match self.nodes.get(last) {
            Some(child) if child.open => Some(last),
            _ => None,
        }
    }

    fn close(&mut self, index: usize) {
        if let Some(node) = self.nodes.get_mut(index) {
            node.open = false;
        }
    }

    fn append_child(&mut self, parent: usize, mut node: Node) -> usize {
        let index = self.nodes.len();
        node.parent = parent;
        self.nodes.push(node);
        if let Some(parent_node) = self.nodes.get_mut(parent) {
            parent_node.children.push(index);
        }
        index
    }

    fn parent(&self, index: usize) -> usize {
        self.nodes.get(index).map_or(0, |node| node.parent)
    }

    /// Whether a block of `kind` may be a direct child of `container`.
    fn can_contain(&self, container: usize, kind: &Kind) -> bool {
        match self.kind(container) {
            Some(
                Kind::Document
                | Kind::BlockQuote
                | Kind::Item(_)
                | Kind::FootnoteDef(_)
                | Kind::FencedDiv(..)
                | Kind::HtmlElement(_)
                | Kind::Definition { .. },
            ) => !matches!(kind, Kind::Item(_)),
            Some(Kind::List(_)) => matches!(kind, Kind::Item(_)),
            _ => false,
        }
    }

    /// Walk up from `container`, closing any block that cannot contain `kind` (e.g. a finished
    /// list when a non-item block follows), and return the nearest ancestor that can.
    fn place(&mut self, mut container: usize, kind: &Kind) -> usize {
        while !self.can_contain(container, kind) {
            self.close(container);
            let parent = self.parent(container);
            if parent == container {
                break;
            }
            container = parent;
        }
        container
    }

    /// Descend through the open containers, matching each one's continuation marker against the
    /// line. Leaves terminate the descent — they are handled by [`Parser::process_line`], not
    /// entered as containers.
    fn descend_containers(&mut self, cursor: &mut Cursor) -> Descent {
        let mut container = 0;
        let mut all_matched = true;
        // The fenced divs matched on this descent, innermost last, each paired with the line as it
        // stood at that div's own indentation (before it re-based its content). A close fence is
        // judged against this path: it is read at each div's level in turn, so one buried under a
        // div's re-base indent (or a nested item's deeper indent) reads as content instead.
        let mut div_path: Vec<(usize, String)> = Vec::new();
        loop {
            let Some(child) = self.last_open_child(container) else {
                break;
            };
            if !self.is_container(child) {
                break;
            }
            let div_fence_line =
                matches!(self.kind(child), Some(Kind::FencedDiv(..))).then(|| cursor.rest());
            match self.try_continue(child, cursor) {
                Continue::Matched => {
                    container = child;
                    if let Some(line) = div_fence_line {
                        div_path.push((child, line));
                    }
                }
                Continue::NotMatched => {
                    all_matched = false;
                    break;
                }
                Continue::MatchedLeaf => {
                    return Descent {
                        container,
                        all_matched,
                        div_path,
                        consumed: true,
                    };
                }
            }
        }
        Descent {
            container,
            all_matched,
            div_path,
            consumed: false,
        }
    }

    // The per-line state machine runs its container-matching and block-opening phases in sequence
    // over one shared cursor; splitting the phases into helpers would only thread that cursor through
    // extra signatures.
    #[allow(clippy::too_many_lines)]
    fn process_line(&mut self, line: &str, following: &[&str]) {
        let mut cursor = Cursor::new(line);

        // Phase 1: descend through open containers, matching each one's continuation marker.
        let Descent {
            mut container,
            all_matched,
            div_path,
            consumed,
        } = self.descend_containers(&mut cursor);
        if consumed {
            return;
        }

        // A bare colon-run line can close an open fenced div, popping everything nested inside it.
        if self.close_fenced_div(container, &div_path) {
            return;
        }

        // A matching close tag (`</tag>`) closes the innermost open HTML element and everything
        // nested under it. Any content before the tag on its line is the element's final content;
        // any content after is re-fed. The tag sits at the element's own level, so an inner block
        // (a list, a block quote) left unmatched on this line does not prevent the close.
        if self.close_html_element(container, &cursor) {
            return;
        }

        // An open raw TeX environment swallows this line verbatim until its matching `\end`.
        if self.continue_raw_tex(container, all_matched, &cursor) {
            return;
        }

        // An open code/html leaf (reachable only when every container matched) consumes the line.
        if all_matched
            && let Some(leaf) = self
                .last_open_child(container)
                .filter(|&c| !self.is_container(c))
            && matches!(
                self.kind(leaf),
                Some(
                    Kind::FencedCode(_)
                        | Kind::IndentedCode
                        | Kind::HtmlBlock(_)
                        | Kind::RawHtmlSpan { .. }
                )
            )
        {
            match self.try_continue(leaf, &mut cursor) {
                Continue::MatchedLeaf | Continue::Matched => return,
                Continue::NotMatched => self.close(leaf),
            }
        }

        let blank = cursor.is_blank();

        // A folding code fence (one that opened no code block) absorbs each following line into its
        // paragraph verbatim — no setext underline, table, or other opener may fire — until its
        // matching closing fence (kept as the last line) or a blank line ends the fold.
        if let Some(fence) = self.fence_fold.clone() {
            if all_matched
                && !blank
                && matches!(self.last_open_leaf_kind(container), Some(Kind::Paragraph))
            {
                if cursor.indent() <= 3 && cursor.is_closing_fence(fence.marker, fence.length) {
                    self.fence_fold = None;
                }
                self.add_line(container, false, false, &mut cursor);
                return;
            }
            self.fence_fold = None;
        }

        // A setext underline converts an open paragraph (directly under the matched container,
        // so fully matched) into a heading.
        if all_matched
            && !blank
            && let Some(para) = self
                .last_open_child(container)
                .filter(|&c| matches!(self.kind(c), Some(Kind::Paragraph)))
        {
            cursor.note_indent();
            if cursor.indent() < TAB_STOP
                && let Some(level) = cursor.setext_underline()
            {
                // Leading link reference definitions belong to neither the heading nor the
                // underline. Find the body that remains after them without registering them yet: the
                // underline forms a heading only over what remains.
                let text = self.node_text(para);
                let mut body = text.as_str();
                while let Some((_, _, rest)) =
                    scan::parse_link_reference_definition(body, self.greedy_paragraphs)
                {
                    body = rest;
                }
                // In the markdown family the underline heads a single-line paragraph only; a body of
                // two or more lines keeps the underline as ordinary continuation text instead.
                let multiline_body = self.greedy_paragraphs && body.trim_end().contains('\n');
                if !multiline_body {
                    let only_definitions = body.trim().is_empty();
                    // Pull the definitions out for real now, then head or consume what remains. If
                    // nothing remains, the paragraph was pure definitions — it is consumed and this
                    // line is reparsed as ordinary content (not an underline).
                    let column_zero = self.nodes.get(para).is_some_and(|node| node.indent == 0);
                    let remaining = self.extract_refs(&text, column_zero);
                    if let Some(node) = self.nodes.get_mut(para) {
                        node.text = remaining;
                    }
                    if only_definitions {
                        self.close(para);
                    } else {
                        self.convert_paragraph_to_heading(para, level);
                        return;
                    }
                }
            }
        }

        // An open multi-line construct — a grid table, a pipe table, or a line block — claims this
        // continuation line before the block openers below could read its leading `+`, `|`, `-`,
        // `>`, `#`, etc. as the start of a new block.
        if self.continue_open_construct(container, all_matched, blank, &cursor) {
            return;
        }

        // The deepest block open before this line opens any new ones. When a container went
        // unmatched in phase 1, this is the tip of the unmatched chain hanging below `matched`.
        let matched = container;
        let old_tip = self.deepest_open(matched);

        // Record the blank against the block it trails — this drives loose-list classification.
        // When every container matched, it lands on the deepest already-finalized block (or the
        // still-open container if it has no content yet), so a blank after an item's last block (or
        // after an empty item) marks the line blank even though the block was closed before this
        // line was read. When a container went unmatched, the blank ends that container at the
        // boundary: it attaches to the deepest matched container's last child, so a block quote (or
        // any block) that a blank line terminates still counts toward the enclosing list's
        // looseness.
        if blank {
            let target = if all_matched {
                self.blank_trails(old_tip)
            } else {
                self.nodes
                    .get(matched)
                    .and_then(|node| node.children.last().copied())
                    .unwrap_or(matched)
            };
            // A blank line that lands inside a still-open fenced div is internal to the div, not a
            // gap between the enclosing item's blocks, so it must not make that item's list loose.
            // (Once the div closes, a following blank trails it at the item's level and does count.)
            let internal_to_open_div = matches!(self.kind(target), Some(Kind::FencedDiv(..)))
                && self.nodes.get(target).is_some_and(|node| node.open);
            if !internal_to_open_div && let Some(node) = self.nodes.get_mut(target) {
                node.last_line_blank = true;
            }
        }

        // Phase 2: open new blocks at the matched container.
        let mut started_new = false;
        if !blank {
            loop {
                cursor.note_indent();
                if let Some(opened) = self.try_open(container, &mut cursor, following) {
                    started_new = true;
                    container = opened;
                    // Descend into the new container to open the next block on this line — but only
                    // if real content remains. A container marker trailed by whitespace alone (e.g.
                    // a bare `-` with spaces after) leaves an empty container: the leftover spaces
                    // are not a non-blank line and must not open an indented code block.
                    if self.is_container(container) && !cursor.is_blank() {
                        continue;
                    }
                }
                break;
            }
        }

        // Spec "close unmatched blocks": a container left unmatched in phase 1 stays open only to
        // absorb a lazy paragraph continuation (non-blank text that opens no new block into an open
        // paragraph). Otherwise it closes before the matched container is reused, so e.g. a blank
        // line ends a block quote rather than letting the next `>` rejoin it.
        let lazy = !all_matched
            && !blank
            && !started_new
            && matches!(self.kind(old_tip), Some(Kind::Paragraph));
        if !all_matched && !lazy {
            self.close_chain(old_tip, matched);
        }

        self.add_line(container, started_new, blank, &mut cursor);
    }

    /// Try each open multi-line construct in turn, returning `true` as soon as one absorbs the line.
    /// Grid runs first: its `+`-ruled border is unambiguous and a pipe table never opens with one.
    fn continue_open_construct(
        &mut self,
        container: usize,
        all_matched: bool,
        blank: bool,
        cursor: &Cursor,
    ) -> bool {
        self.continue_grid_table(container, all_matched, blank, cursor)
            || self.continue_pipe_table(container, all_matched, blank, cursor)
            || self.continue_line_block(container, all_matched, cursor)
            || self.continue_text_table(container, all_matched, blank, cursor)
    }

    /// Let an in-progress grid table claim its `+`/`|` continuation lines before the block openers
    /// run. A paragraph whose first line is a grid top border is a candidate; each following grid
    /// line is absorbed into it. A non-grid line ends the candidate: if the lines so far already
    /// form a complete table the paragraph closes (and builds as a table) so the new line starts
    /// fresh, otherwise the paragraph stays open to take the line as a lazy continuation. Returns
    /// `true` when the line was absorbed.
    fn continue_grid_table(
        &mut self,
        container: usize,
        all_matched: bool,
        blank: bool,
        cursor: &Cursor,
    ) -> bool {
        if !self.extensions.contains(Extension::GridTables) || !all_matched {
            return false;
        }
        let Some(leaf) = self
            .last_open_child(container)
            .filter(|&c| matches!(self.kind(c), Some(Kind::Paragraph)))
        else {
            return false;
        };
        let Some(text) = self.node_text_ref(leaf) else {
            return false;
        };
        let first = text.split('\n').next().unwrap_or("");
        if !grid::is_top_border(first) || blank {
            return false;
        }
        let line = cursor.rest();
        if grid::is_grid_line(&line) {
            self.append_text(leaf, line.trim_start_matches(' '));
            self.append_text(leaf, "\n");
            return true;
        }
        if grid::parse(text).is_some() {
            self.close(leaf);
        }
        false
    }

    /// Let an in-progress pipe table claim a continuation line before the block openers run,
    /// returning `true` when the line was absorbed as a table row and needs no further handling. A
    /// row without a pipe ends the table: the open paragraph closes and the line is reparsed.
    fn continue_pipe_table(
        &mut self,
        container: usize,
        all_matched: bool,
        blank: bool,
        cursor: &Cursor,
    ) -> bool {
        if !self.extensions.contains(Extension::PipeTables) || !all_matched || blank {
            return false;
        }
        let Some(leaf) = self
            .last_open_child(container)
            .filter(|&c| matches!(self.kind(c), Some(Kind::Paragraph | Kind::LineBlock)))
        else {
            return false;
        };
        let rest = cursor.rest();
        let Some(header) = self.node_text_ref(leaf) else {
            return false;
        };
        // A line block becomes a table only on its very first line: a delimiter row directly under
        // the opening `|` line reinterprets it as a table header. Past the first line the block is
        // committed to being a line block.
        if matches!(self.kind(leaf), Some(Kind::LineBlock)) {
            if !single_line(header)
                || !table::opens_table(header.trim_end(), &rest, self.greedy_paragraphs)
            {
                return false;
            }
            if let Some(node) = self.nodes.get_mut(leaf) {
                node.kind = Kind::Paragraph;
            }
            self.append_text(leaf, &rest);
            self.append_text(leaf, "\n");
            return true;
        }
        match table::classify_continuation(header, &rest, self.greedy_paragraphs) {
            table::Continuation::Absorb => {
                self.append_text(leaf, &rest);
                self.append_text(leaf, "\n");
                true
            }
            table::Continuation::Terminate => {
                self.close(leaf);
                false
            }
            table::Continuation::NotTable => false,
        }
    }

    /// Let an open line block claim its continuation lines before the block openers run. A `|` flush
    /// at the line start opens a new entry. A line led by whitespace continues the previous entry,
    /// but only while that entry holds content: a continuation under an empty entry, a flush-left
    /// non-bar line, and a wholly empty line all end the block (the line is then reparsed). Returns
    /// `true` when the line was absorbed.
    fn continue_line_block(
        &mut self,
        container: usize,
        all_matched: bool,
        cursor: &Cursor,
    ) -> bool {
        if !self.extensions.contains(Extension::LineBlocks) || !all_matched {
            return false;
        }
        let Some(block) = self
            .last_open_child(container)
            .filter(|&c| matches!(self.kind(c), Some(Kind::LineBlock)))
        else {
            return false;
        };
        let remaining = cursor.remaining();
        let absorb = is_line_block_marker(remaining)
            || (remaining.starts_with(' ')
                && self
                    .node_text_ref(block)
                    .is_some_and(|text| !last_entry_is_empty(text)));
        if absorb {
            self.append_text(block, &cursor.rest());
            self.append_text(block, "\n");
            true
        } else {
            self.close(block);
            false
        }
    }

    /// Feed a continuation line to an open raw TeX environment, returning `true` when the line was
    /// absorbed. Reachable only when every container matched, so the verbatim text stays aligned.
    fn continue_raw_tex(&mut self, container: usize, all_matched: bool, cursor: &Cursor) -> bool {
        if !all_matched {
            return false;
        }
        let Some(leaf) = self
            .last_open_child(container)
            .filter(|&c| matches!(self.kind(c), Some(Kind::RawTex { .. })))
        else {
            return false;
        };
        self.feed_raw_tex(leaf, cursor.remaining());
        true
    }

    /// Open a raw TeX environment when the cursor sits on a `\begin{NAME}` at the line start. The
    /// environment gathers lines verbatim through its matching `\end{NAME}` and renders as a
    /// `RawBlock` for `tex`. Math environments stay inline, so they fall through to a paragraph here.
    /// Unlike the foldable openers this one interrupts an open paragraph; a `\begin` that never finds
    /// its `\end` is settled back into a paragraph at end of input.
    ///
    /// Known limitations, both niche and exact in the common free-standing form:
    /// - When the environment directly interrupts an open paragraph with no blank line between, that
    ///   preceding paragraph renders as `Para` rather than the tighter `Plain`.
    /// - A math environment hands its body to the inline phase rather than being gathered verbatim
    ///   here, so a non-math `\begin{…}` sitting at column 0 *inside* a math environment opens a
    ///   fresh block environment there instead of staying part of the enclosing inline math span. A
    ///   nested environment indented or sharing a line with surrounding math — the usual way it is
    ///   written — stays within the span.
    fn open_raw_tex(&mut self, container: usize, cursor: &mut Cursor) -> Option<usize> {
        if !self.extensions.contains(Extension::RawTex) {
            return None;
        }
        let name = raw_tex_env_name(cursor.remaining(), b"begin")?;
        if is_math_environment(&name) {
            return None;
        }
        let line = cursor.rest();
        cursor.advance_chars(line.chars().count());
        let kind = Kind::RawTex { name, depth: 0 };
        let parent = self.place(container, &kind);
        let index = self.append_child(parent, Node::new(kind));
        self.feed_raw_tex(index, &line);
        Some(index)
    }

    /// Append one source `line` to an open raw TeX environment and advance its nesting depth. Each
    /// `\begin{NAME}` of the opener's own name deepens the nesting and each `\end{NAME}` lifts it;
    /// when the depth returns to zero the environment closes at that `\end`, dropping the trailing
    /// newline. Any content after the closing `\end` on the same line is re-fed as a fresh line.
    fn feed_raw_tex(&mut self, index: usize, line: &str) {
        let Some(Kind::RawTex { name, depth }) = self.kind(index).cloned() else {
            return;
        };
        let (new_depth, close_at) = raw_tex_scan(line, &name, depth);
        if let Some(end) = close_at {
            // The matching `\end` ends the environment; the closing newline is dropped, and any
            // content past the `\end` on this line is re-fed as a fresh line.
            self.append_text(index, line.get(..end).unwrap_or(line));
            self.set_raw_tex_depth(index, 0);
            self.close(index);
            let trailing = line.get(end..).unwrap_or("").to_owned();
            if !trailing.is_empty() {
                self.process_line(&trailing, &[]);
            }
            return;
        }
        self.append_text(index, line);
        self.append_text(index, "\n");
        self.set_raw_tex_depth(index, new_depth);
    }

    fn set_raw_tex_depth(&mut self, index: usize, value: usize) {
        if let Some(node) = self.nodes.get_mut(index)
            && let Kind::RawTex { depth, .. } = &mut node.kind
        {
            *depth = value;
        }
    }

    /// Open a block-level HTML element when the cursor sits on a recognized open tag. A `<div>`
    /// becomes an [`IrBlock::Div`] when `native_divs` is on; any other block tag (and a `<div>` when
    /// only `markdown_in_html_blocks` is on) keeps its tags as raw HTML around the parsed content.
    /// The whole open tag is consumed; any same-line remainder is re-fed so its content — including a
    /// close tag on the same line — flows through the normal line handling.
    ///
    /// When the element directly interrupts an open paragraph with no blank line between, that
    /// preceding paragraph reads tight — `Plain` rather than `Para` — under `markdown_in_html_blocks`.
    /// A self-closing tag (`<div/>`) is read as an ordinary open and stays open until end of input.
    fn open_html_element(
        &mut self,
        container: usize,
        indent: usize,
        cursor: &mut Cursor,
    ) -> Option<usize> {
        let native_divs = self.extensions.contains(Extension::NativeDivs);
        let markdown_in_html = self.extensions.contains(Extension::MarkdownInHtmlBlocks);
        if !native_divs && !markdown_in_html {
            return None;
        }
        let remaining = cursor.remaining();
        let open = html_element::parse_open_tag(remaining)?;
        let is_div = open.tag == "div";
        // A div renders as a native div only with `native_divs`; otherwise it (and every other block
        // tag) needs `markdown_in_html_blocks` to have its content parsed. A block tag governed by
        // neither extension falls through to the raw HTML-block reading.
        let as_div = is_div && native_divs;
        if !as_div && !markdown_in_html {
            return None;
        }
        // A paragraph still open here was not separated from the element by a blank line; with
        // `markdown_in_html_blocks` the element interrupts it as a block and it reads tight.
        if markdown_in_html {
            self.tighten_interrupted_paragraph(container);
        }
        let raw_open = remaining.get(..open.len).unwrap_or(remaining).to_owned();
        let trailing = remaining.get(open.len..).unwrap_or("").to_owned();
        // Consume the whole remainder so the line is fully read here; any content after the open tag
        // is handled by re-feeding `trailing` rather than by the cursor. The cursor advances one byte
        // per step, so the byte length is the right amount even with multibyte characters present.
        cursor.advance_chars(remaining.len());
        let kind = Kind::HtmlElement(HtmlElementInfo {
            tag: open.tag,
            attr: open.attr,
            raw_open: format!("{}{raw_open}", " ".repeat(indent)),
            raw_close: String::new(),
            as_div,
            tighten_last: false,
        });
        let parent = self.place(container, &kind);
        let index = self.append_child(parent, Node::new(kind));
        if !trailing.trim().is_empty() {
            self.process_line(&trailing, &[]);
        }
        Some(index)
    }

    /// The Markdown family reading raw HTML where inner content is not parsed: a block-level tag is
    /// kept verbatim rather than opened as a native div or a markdown-in-HTML element.
    fn markdown_raw_html(&self) -> bool {
        self.greedy_paragraphs
            && !self.extensions.contains(Extension::MarkdownInHtmlBlocks)
            && !self.extensions.contains(Extension::NativeDivs)
    }

    /// In the Markdown family reading raw HTML, a block-level HTML tag that starts the line opens a
    /// raw block. A non-self-closing open tag with a balanced matching close is a span running to that
    /// close (nested same-name tags and blank lines included); every other block tag — self-closing,
    /// void (no close ahead), or a bare close tag — is a single-line raw block. With
    /// `markdown_attribute` the block reads like the other block openers — it accepts up to three
    /// columns of indentation and interrupts an open paragraph (which then reads tight); without it
    /// the tag must stand at column zero and folds into an open paragraph as ordinary text instead.
    fn open_markdown_raw_html(
        &mut self,
        container: usize,
        indent: usize,
        in_paragraph: bool,
        cursor: &mut Cursor,
        following: &[&str],
    ) -> Option<usize> {
        enum Opener {
            /// A single-line raw block holding `line[..end]`.
            Single(usize),
            /// A multi-line span with the given tag name and open-nesting depth after its first line.
            Span(String, usize),
        }
        let interrupts = self.extensions.contains(Extension::MarkdownAttribute);
        let max_indent = if interrupts { 3 } else { 0 };
        if !self.markdown_raw_html() || indent > max_indent || (in_paragraph && !interrupts) {
            return None;
        }
        let line = cursor.remaining().to_owned();
        let opener = if let Some(open) = html_element::parse_open_tag(&line) {
            let after_tag = line.get(open.len..).unwrap_or("");
            let (line_depth, same_line) = if open.self_closing {
                (0, None)
            } else {
                html_element::scan_depth(after_tag, &open.tag, 1)
            };
            match same_line {
                Some(offset) => Opener::Single(open.len + offset),
                // A self-closing/void tag, or an open tag with no balanced close ahead: the tag alone
                // is the raw block, and anything after it on the line is parsed normally.
                None if line_depth == 0
                    || !self.raw_html_span_closes(container, line_depth, &open.tag, following) =>
                {
                    Opener::Single(open.len)
                }
                None => Opener::Span(open.tag, line_depth),
            }
        } else if let Some(len) = html_element::parse_close_tag(&line) {
            Opener::Single(len)
        } else {
            return None;
        };
        // The whole opener line is read here; content past a close tag is re-fed as a fresh line.
        cursor.advance_chars(line.len());
        if in_paragraph {
            let leaf = self.deepest_open(container);
            if matches!(self.kind(leaf), Some(Kind::Paragraph)) {
                if let Some(node) = self.nodes.get_mut(leaf) {
                    node.as_plain = true;
                }
                self.close(leaf);
            }
        }
        match opener {
            Opener::Single(end) => Some(self.emit_raw_html_leaf(container, &line, end)),
            Opener::Span(tag, depth) => {
                let kind = Kind::RawHtmlSpan { tag, depth };
                let parent = self.place(container, &kind);
                let index = self.append_child(parent, Node::new(kind));
                self.append_text(index, &line);
                self.append_text(index, "\n");
                Some(index)
            }
        }
    }

    /// Emit a single-line raw HTML block holding `line[..end]`, re-feeding any trailing content on the
    /// line as a fresh line, and return the closed leaf.
    fn emit_raw_html_leaf(&mut self, container: usize, line: &str, end: usize) -> usize {
        let kept = line.get(..end).unwrap_or(line).to_owned();
        let rest = line.get(end..).unwrap_or("").to_owned();
        let kind = Kind::RawHtmlSpan {
            tag: String::new(),
            depth: 0,
        };
        let parent = self.place(container, &kind);
        let index = self.append_child(parent, Node::new(kind));
        self.append_text(index, &kept);
        self.close(index);
        if !rest.trim().is_empty() {
            self.process_line(&rest, &[]);
        }
        index
    }

    /// Whether a raw HTML span opened at `depth` finds its balanced close somewhere in the following
    /// lines (read at the container's own indentation). A span cannot outlast its container.
    fn raw_html_span_closes(
        &self,
        container: usize,
        depth: usize,
        tag: &str,
        following: &[&str],
    ) -> bool {
        let path = self.container_path(container);
        let mut depth = depth;
        for line in following {
            let mut cursor = Cursor::new(line);
            if !self.strip_container_path(&path, &mut cursor) {
                return false;
            }
            let (next, close) = html_element::scan_depth(cursor.remaining(), tag, depth);
            if close.is_some() {
                return true;
            }
            depth = next;
        }
        false
    }

    fn text_tables_enabled(&self) -> bool {
        self.extensions.contains(Extension::SimpleTables)
            || self.extensions.contains(Extension::MultilineTables)
    }

    /// Let a dash-ruled table claim its lines before the block openers run. A single-line paragraph
    /// directly above a dash ruling is the header of a new table: the paragraph is retyped and the
    /// ruling folded onto it, so the rows below gather into one leaf. An already-open table leaf
    /// absorbs each further line, and a blank line settles it (see [`Parser::finalize_text_table`]).
    /// Returns `true` when the line was absorbed.
    fn continue_text_table(
        &mut self,
        container: usize,
        all_matched: bool,
        blank: bool,
        cursor: &Cursor,
    ) -> bool {
        if !self.text_tables_enabled() || !all_matched {
            return false;
        }
        let Some(leaf) = self.last_open_child(container) else {
            return false;
        };
        match self.kind(leaf) {
            Some(Kind::Paragraph) => {
                if blank {
                    return false;
                }
                let Some(header) = self.node_text_ref(leaf) else {
                    return false;
                };
                if !single_line(header) || !texttable::is_dash_line(cursor.remaining()) {
                    return false;
                }
                // A dash-ruled table has no cell delimiters: its columns are positional, and per-column
                // alignment is read from where the header text sits relative to the dash runs. So the
                // header and ruling must share one coordinate. The header reached here de-indented
                // through the paragraph path, so it is restored to the column it began at; the ruling
                // and the rows below keep their own leading whitespace.
                let header_indent = self.nodes.get(leaf).map_or(0, |node| node.indent);
                let ruling = cursor.rest();
                let header = format!("{}{header}", " ".repeat(header_indent));
                if let Some(node) = self.nodes.get_mut(leaf) {
                    node.kind = Kind::TextTable;
                    node.text = header;
                }
                self.append_text(leaf, &ruling);
                self.append_text(leaf, "\n");
                true
            }
            Some(Kind::TextTable) => {
                if blank {
                    let Some(text) = self.node_text_ref(leaf) else {
                        return false;
                    };
                    let first = text.split('\n').next().unwrap_or("");
                    // A header-led table (its first line is text, not a ruling) ends at the blank.
                    // A dash-led table ends only once its closing ruling has been read; until then a
                    // blank separates the multi-line rows of the body and is kept.
                    let settle = !texttable::is_dash_line(first)
                        || texttable::is_dash_line(last_nonempty_line(text));
                    if settle {
                        self.finalize_text_table(leaf);
                        return false;
                    }
                    self.append_text(leaf, "\n");
                    return true;
                }
                self.append_text(leaf, &cursor.rest_with_newline());
                true
            }
            _ => false,
        }
    }

    /// Settle an open dash-ruled table leaf. Its accumulated lines are parsed into a table: when they
    /// all belong to it the leaf closes as the table; when only a prefix does, the leaf keeps that
    /// prefix and the surplus lines are re-fed as following blocks; when they form no table the leaf
    /// is repurposed into the thematic break or paragraph its first line is, with the rest re-fed.
    fn finalize_text_table(&mut self, leaf: usize) {
        let text = self.node_text(leaf);
        let lines = split_table_lines(&text);
        match texttable::parse(&lines, self.extensions) {
            Some((_, consumed)) if consumed >= lines.len() => self.close(leaf),
            Some((_, consumed)) => {
                let kept = lines.get(..consumed).unwrap_or(&[]).join("\n");
                let rest = owned_lines(lines.get(consumed..).unwrap_or(&[]));
                if let Some(node) = self.nodes.get_mut(leaf) {
                    node.text = if kept.is_empty() {
                        kept
                    } else {
                        format!("{kept}\n")
                    };
                }
                self.close(leaf);
                self.refeed_lines(&rest);
            }
            None => {
                let first = lines.first().copied().unwrap_or("");
                let rest = owned_lines(lines.get(1..).unwrap_or(&[]));
                if let Some(node) = self.nodes.get_mut(leaf) {
                    if is_thematic_dash_line(first) {
                        node.kind = Kind::ThematicBreak;
                        node.text = String::new();
                    } else {
                        node.kind = Kind::Paragraph;
                        node.text = format!("{first}\n");
                    }
                }
                self.close(leaf);
                self.refeed_lines(&rest);
            }
        }
    }

    /// Re-feed a run of buffered lines through the line handler, each seeing the ones after it as
    /// its look-ahead so a fenced code block among them can still find its closing fence.
    fn refeed_lines(&mut self, lines: &[String]) {
        let refs: Vec<&str> = lines.iter().map(String::as_str).collect();
        for index in 0..refs.len() {
            let line = refs.get(index).copied().unwrap_or("");
            let following = refs.get(index + 1..).unwrap_or(&[]);
            self.process_line(line, following);
        }
    }

    /// Settle every dash-ruled table leaf still open at end of input. Re-feeding surplus lines may
    /// open a fresh candidate, which the next pass settles; each pass strictly shrinks the work.
    fn finalize_open_text_tables(&mut self) {
        while let Some(leaf) = self.open_text_table_leaf() {
            self.finalize_text_table(leaf);
        }
    }

    fn open_text_table_leaf(&self) -> Option<usize> {
        (0..self.nodes.len()).find(|&index| {
            matches!(self.kind(index), Some(Kind::TextTable))
                && self.nodes.get(index).is_some_and(|node| node.open)
        })
    }

    /// Close `tip` and each ancestor up to (but not including) `until`.
    fn close_chain(&mut self, mut tip: usize, until: usize) {
        while tip != until {
            self.close(tip);
            let parent = self.parent(tip);
            if parent == tip {
                break;
            }
            tip = parent;
        }
    }

    /// The block a trailing blank line attaches to: descend through finalized last-children so the
    /// blank lands on the content it follows (e.g. a closed code block) rather than its still-open
    /// container. Stops at an empty container, which the blank then trails directly.
    ///
    /// Descent follows the list structure only. Loose-list classification reads the same
    /// List/Item chain, so the blank must mark a block on it: descending into a closed block quote
    /// or fenced div would bury the mark where the classification never looks, leaving the list
    /// wrongly tight. Such a block is itself the trailing block, so the blank stops there.
    fn blank_trails(&self, mut index: usize) -> usize {
        while let Some(&last) = self.nodes.get(index).and_then(|node| node.children.last()) {
            if self.nodes.get(last).is_some_and(|node| !node.open) {
                index = last;
                if !matches!(self.kind(index), Some(Kind::List(_) | Kind::Item(_))) {
                    break;
                }
            } else {
                break;
            }
        }
        index
    }

    fn deepest_open(&self, mut index: usize) -> usize {
        while let Some(child) = self.last_open_child(index) {
            index = child;
        }
        index
    }

    /// Whether an open footnote definition sits in the chain strictly below `container` — that is,
    /// the paragraph a line would lazily continue is that definition's body. A definition marker then
    /// ends the open definition and starts a new one rather than folding into it.
    fn footnote_def_open_below(&self, container: usize) -> bool {
        let mut index = self.deepest_open(container);
        while index != container {
            if matches!(self.kind(index), Some(Kind::FootnoteDef(_))) {
                return true;
            }
            let parent = self.parent(index);
            if parent == index {
                break;
            }
            index = parent;
        }
        false
    }

    /// Mark the open paragraph interrupted by a block opener under `container` so it renders tight
    /// (`Plain`). A no-op when the deepest open block is not a paragraph.
    fn tighten_interrupted_paragraph(&mut self, container: usize) {
        let leaf = self.deepest_open(container);
        if matches!(self.kind(leaf), Some(Kind::Paragraph))
            && let Some(node) = self.nodes.get_mut(leaf)
        {
            node.as_plain = true;
        }
    }

    /// If the current line closes an open fenced div, close that div and everything nested inside it
    /// — a colon fence preempts even an open code block — and return `true`. It is honored only when
    /// the descent reached the innermost open div, so a fence shallower than a still-open nested div
    /// stays ordinary content (which an enclosing div may then hold) rather than closing that div or
    /// an ancestor. `div_path` holds the divs matched on this line, innermost last, each paired with
    /// the line as it stood at that div's indentation.
    fn close_fenced_div(&mut self, container: usize, div_path: &[(usize, String)]) -> bool {
        if !self.extensions.contains(Extension::FencedDivs) {
            return false;
        }
        let Some((inner, inner_line)) = div_path.last() else {
            return false;
        };
        if self.innermost_open_div() != Some(*inner) {
            return false;
        }
        let Some(count) = div_close_fence(inner_line) else {
            return false;
        };
        let Some(target) = self.div_close_target(div_path, count) else {
            return false;
        };
        let tip = self.deepest_open(container);
        let stop = self.parent(target);
        self.close_chain(tip, stop);
        true
    }

    /// If this line carries the matching close tag of the innermost open HTML element, close that
    /// element and return `true`. Content preceding the tag on its line is fed as the element's final
    /// content (which is then tightened to `Plain`); content after the tag is re-fed as a fresh line.
    fn close_html_element(&mut self, container: usize, cursor: &Cursor) -> bool {
        if !self.extensions.contains(Extension::NativeDivs)
            && !self.extensions.contains(Extension::MarkdownInHtmlBlocks)
        {
            return false;
        }
        let Some(element) = self.innermost_open_html_element() else {
            return false;
        };
        let line = cursor.remaining();
        let trimmed = line.trim_start_matches(' ');
        let leading = line.len() - trimmed.len();
        if leading > 3 {
            return false;
        }
        let (found, as_div) = match self.kind(element) {
            Some(Kind::HtmlElement(info)) => {
                let Some(found) = html_element::find_close_tag(trimmed, &info.tag) else {
                    return false;
                };
                (found, info.as_div)
            }
            _ => return false,
        };
        let before = trimmed.get(..found.start).unwrap_or("");
        let close_tag = trimmed.get(found.start..found.end).unwrap_or("").to_owned();
        let after = trimmed.get(found.end..).unwrap_or("").to_owned();
        let trails = !before.trim().is_empty();
        if trails {
            self.process_line(before, &[]);
        }
        // Whether the element's final content block tightens from `Para` to `Plain`. A native div
        // tightens only when the close tag physically trails content on its own line. A raw element
        // tightens whenever no blank line separates its last content from the close tag — which holds
        // exactly when a paragraph is still open at the close (a blank line would have closed it).
        let tighten = if as_div {
            trails
        } else {
            matches!(self.kind(self.deepest_open(element)), Some(Kind::Paragraph))
        };
        // The deepest open block under the element is the close boundary's chain tip.
        let tip = self.deepest_open(container);
        self.close_chain(tip, element);
        if let Some(node) = self.nodes.get_mut(element)
            && let Kind::HtmlElement(info) = &mut node.kind
        {
            info.raw_close = close_tag;
            info.tighten_last = tighten;
            node.open = false;
        }
        if !after.trim().is_empty() {
            self.process_line(&after, &[]);
        }
        true
    }

    /// The innermost open HTML element anywhere in the tree, or `None` when none is open.
    fn innermost_open_html_element(&self) -> Option<usize> {
        let mut node = self.deepest_open(0);
        loop {
            if matches!(self.kind(node), Some(Kind::HtmlElement(_))) {
                return Some(node);
            }
            let parent = self.parent(node);
            if parent == node {
                return None;
            }
            node = parent;
        }
    }

    /// The innermost open fenced div anywhere in the tree, or `None` when none is open.
    fn innermost_open_div(&self) -> Option<usize> {
        let mut node = self.deepest_open(0);
        loop {
            if matches!(self.kind(node), Some(Kind::FencedDiv(..))) {
                return Some(node);
            }
            let parent = self.parent(node);
            if parent == node {
                return None;
            }
            node = parent;
        }
    }

    /// Choose which fenced div a closing run of `count` colons shuts. The matched divs are read
    /// innermost first, each paired with the closing line as it stood at that div's indentation; the
    /// first div long enough to be closed by `count` colons is the target. A div the closing line
    /// sits more than three columns into is unreachable and, with every div outside it indented at
    /// least as far, ends the search — the line is ordinary content rather than a fence.
    fn div_close_target(&self, div_path: &[(usize, String)], count: usize) -> Option<usize> {
        for (node, line) in div_path.iter().rev() {
            let leading = line.len() - line.trim_start_matches(' ').len();
            if leading > 3 {
                return None;
            }
            if let Some(Kind::FencedDiv(info)) = self.kind(*node)
                && info.fence <= count
            {
                return Some(*node);
            }
        }
        None
    }

    fn is_container(&self, index: usize) -> bool {
        matches!(
            self.kind(index),
            Some(
                Kind::Document
                    | Kind::BlockQuote
                    | Kind::List(_)
                    | Kind::Item(_)
                    | Kind::FootnoteDef(_)
                    | Kind::FencedDiv(..)
                    | Kind::HtmlElement(_)
                    | Kind::DefinitionList
                    | Kind::DefinitionItem { .. }
                    | Kind::Definition { .. }
            )
        )
    }

    fn convert_paragraph_to_heading(&mut self, para: usize, level: i32) {
        if let Some(node) = self.nodes.get_mut(para) {
            node.kind = Kind::Heading(level);
            node.open = false;
            node.text = node.text.trim().to_owned();
        }
    }

    /// Try to continue an open container (block quote / list item) or open leaf on this line.
    fn try_continue(&mut self, index: usize, cursor: &mut Cursor) -> Continue {
        match self.kind(index).cloned() {
            // A list (and the two grouping levels of a definition list) is a transparent container:
            // it consumes nothing and defers to its items.
            Some(Kind::List(_) | Kind::DefinitionList | Kind::DefinitionItem { .. }) => {
                Continue::Matched
            }
            // An HTML element is transparent: it consumes no marker and lets its inner lines flow to
            // the openers below. Its matching close tag is detected separately in `process_line`.
            Some(Kind::HtmlElement(_)) => Continue::Matched,
            // A definition body continues under its content indent, like a list item — except that
            // an as-yet-empty body survives a blank line, so a deferred indented paragraph still
            // joins it.
            Some(Kind::Definition { indent }) => {
                self.continue_item_like(index, indent, true, cursor)
            }
            // A fenced div re-bases its content to the column it opened at: it consumes up to that
            // many leading columns, then stays open until a matching close fence (handled in
            // `process_line`) or end of input.
            Some(Kind::FencedDiv(info)) => {
                cursor.advance_columns(info.indent);
                Continue::Matched
            }
            Some(Kind::BlockQuote) => {
                let checkpoint = cursor.checkpoint();
                cursor.skip_up_to_three_spaces();
                if cursor.peek() == Some(b'>') {
                    cursor.advance_one();
                    cursor.consume_optional_space();
                    Continue::Matched
                } else {
                    // Restore the speculatively consumed indentation so phase 2 sees the line's
                    // true indent (e.g. a non-continued line that is itself indented code).
                    cursor.reset_to(checkpoint);
                    Continue::NotMatched
                }
            }
            Some(Kind::Item(info)) => self.continue_item_like(index, info.indent, false, cursor),
            // A footnote definition's content continues under a four-column indent, the same as a
            // list item; an unindented non-blank line ends it (an open paragraph may still take it
            // as a lazy continuation, handled by the caller).
            Some(Kind::FootnoteDef(_)) => {
                if cursor.is_blank() {
                    if self.nodes.get(index).is_some_and(|n| n.children.is_empty()) {
                        Continue::NotMatched
                    } else {
                        Continue::Matched
                    }
                } else if cursor.indent() >= TAB_STOP {
                    cursor.advance_columns(TAB_STOP);
                    Continue::Matched
                } else {
                    Continue::NotMatched
                }
            }
            Some(Kind::FencedCode(fence)) => {
                self.continue_fenced(index, &fence, cursor);
                Continue::MatchedLeaf
            }
            Some(Kind::IndentedCode) => {
                if cursor.is_blank() {
                    cursor.advance_up_to_columns(TAB_STOP);
                    self.append_text(index, &cursor.rest_with_newline());
                    Continue::MatchedLeaf
                } else if cursor.indent() >= TAB_STOP {
                    cursor.advance_columns(TAB_STOP);
                    self.append_text(index, &cursor.rest_with_newline());
                    Continue::MatchedLeaf
                } else {
                    Continue::NotMatched
                }
            }
            Some(Kind::HtmlBlock(kind)) => {
                self.continue_html(index, kind, cursor);
                Continue::MatchedLeaf
            }
            Some(Kind::RawHtmlSpan { tag, depth }) => {
                self.continue_raw_html_span(index, &tag, depth, cursor);
                Continue::MatchedLeaf
            }
            _ => Continue::NotMatched,
        }
    }

    /// Continue a content container whose lines belong to it under a fixed `indent` (a list item or
    /// a definition body): a non-blank line continues it when indented to the content column, which
    /// is then consumed. A blank line continues it once it has content; when it is still empty,
    /// `blank_keeps_empty` decides — a list item ends, while a definition body waits for a deferred
    /// indented paragraph.
    fn continue_item_like(
        &self,
        index: usize,
        indent: usize,
        blank_keeps_empty: bool,
        cursor: &mut Cursor,
    ) -> Continue {
        if cursor.is_blank() {
            if !blank_keeps_empty && self.nodes.get(index).is_some_and(|n| n.children.is_empty()) {
                Continue::NotMatched
            } else {
                Continue::Matched
            }
        } else if cursor.indent() >= indent {
            cursor.advance_columns(indent);
            Continue::Matched
        } else {
            Continue::NotMatched
        }
    }

    fn continue_fenced(&mut self, index: usize, fence: &FenceInfo, cursor: &mut Cursor) {
        let indent = cursor.indent();
        if indent <= 3 && cursor.is_closing_fence(fence.marker, fence.length) {
            if let Some(node) = self.nodes.get_mut(index) {
                node.open = false;
            }
            return;
        }
        cursor.advance_up_to_columns(fence.indent);
        let content = cursor.rest_with_newline();
        self.append_text(index, &content);
    }

    fn continue_html(&mut self, index: usize, kind: u8, cursor: &mut Cursor) {
        // Types 6 and 7 are terminated by a blank line, which is not part of the block.
        if matches!(kind, 6 | 7) && cursor.is_blank() {
            self.close(index);
            return;
        }
        let line = cursor.rest();
        self.append_text(index, &line);
        self.append_text(index, "\n");
        if html_block::closes(kind, &line) {
            self.close(index);
        }
    }

    /// Continue an open raw HTML span: absorb this line verbatim (blank lines included), tracking the
    /// nesting of same-name tags. When a close tag brings the depth to zero, the span ends with that
    /// tag; any content after it on the line is re-fed as a fresh line.
    fn continue_raw_html_span(
        &mut self,
        index: usize,
        tag: &str,
        depth: usize,
        cursor: &mut Cursor,
    ) {
        let line = cursor.rest();
        let (new_depth, close) = html_element::scan_depth(&line, tag, depth);
        if let Some(offset) = close {
            let kept = line.get(..offset).unwrap_or(&line).to_owned();
            let rest = line.get(offset..).unwrap_or("").to_owned();
            self.append_text(index, &kept);
            self.set_raw_html_depth(index, 0);
            self.close(index);
            if !rest.trim().is_empty() {
                self.process_line(&rest, &[]);
            }
        } else {
            self.append_text(index, &line);
            self.append_text(index, "\n");
            self.set_raw_html_depth(index, new_depth);
        }
    }

    fn set_raw_html_depth(&mut self, index: usize, value: usize) {
        if let Some(node) = self.nodes.get_mut(index)
            && let Kind::RawHtmlSpan { depth, .. } = &mut node.kind
        {
            *depth = value;
        }
    }

    /// How a greedy paragraph (the markdown dialect) absorbs a following block opener. The foldable
    /// openers — a block quote, heading, thematic break, fenced div, or footnote definition —
    /// continue an open paragraph as a lazy line rather than interrupting it, even across a container
    /// the line did not match (`> a` then `# b`); only a blank line, a fenced code block, or an HTML
    /// block ends it. The block-quote and heading folds are gated further on the
    /// `blank_before_blockquote` and `blank_before_header` toggles, so dropping a toggle lets that
    /// opener interrupt again. A list marker is structural: it still opens a sibling item in an open
    /// list or a sublist inside an item, and folds only where it would otherwise *start* a fresh list
    /// — when the paragraph is the container's own last child and the container is not itself a list
    /// item or other indented item body. The `lists_without_preceding_blankline` toggle drops that
    /// last fold, so a fresh list interrupts the paragraph instead.
    fn greedy_gates(&self, container: usize, in_paragraph: bool) -> GreedyGates {
        if !self.greedy_paragraphs {
            return GreedyGates::default();
        }
        let fresh_list_into_paragraph = !self
            .extensions
            .contains(Extension::ListsWithoutPrecedingBlankline)
            && !matches!(
                self.kind(container),
                Some(Kind::Item(_) | Kind::Definition { .. } | Kind::FootnoteDef(_))
            )
            && matches!(
                self.last_open_child(container)
                    .and_then(|child| self.kind(child)),
                Some(Kind::Paragraph)
            );
        GreedyGates {
            foldable: in_paragraph,
            list_start: fresh_list_into_paragraph,
            blockquote: in_paragraph && self.extensions.contains(Extension::BlankBeforeBlockquote),
            heading: in_paragraph && self.extensions.contains(Extension::BlankBeforeHeader),
        }
    }

    /// Whether a scanned code fence actually opens a fenced code block. Pure `CommonMark` always
    /// recognizes a fence. The Markdown dialect instead gates each fence character on its own
    /// extension — a backtick fence on `backtick_code_blocks`, a tilde fence on `fenced_code_blocks`
    /// — and, lacking any extension that gives a richer info string meaning, requires the info string
    /// to be a single bare language token: an info string carrying inner whitespace or a brace then
    /// names no language and the fence is left to fold into a paragraph.
    fn fence_opener_accepted(&self, fence: &FenceInfo) -> bool {
        if !self.greedy_paragraphs {
            return true;
        }
        let marker_allowed = match fence.marker {
            b'`' => self.extensions.contains(Extension::BacktickCodeBlocks),
            b'~' => self.extensions.contains(Extension::FencedCodeBlocks),
            _ => false,
        };
        if !marker_allowed {
            return false;
        }
        // A brace-delimited attribute block, or a raw-output marker, gives a non-bare info string
        // meaning; the finalizer then interprets it. Without any of those extensions only a bare
        // language token is accepted.
        if self.extensions.contains(Extension::FencedCodeAttributes)
            || self.extensions.contains(Extension::Attributes)
            || self.extensions.contains(Extension::RawAttribute)
        {
            return true;
        }
        !fence
            .info
            .trim()
            .chars()
            .any(|ch| ch.is_whitespace() || ch == '{' || ch == '}')
    }

    /// Whether an opening code fence has a matching closing fence ahead, within the same container.
    /// In the Markdown dialect a fenced code block must be closed: an unclosed fence — one that would
    /// run to the container's end — does not open, and its lines fold into a paragraph instead. Pure
    /// `CommonMark` lets an unclosed fence run to the end, so there a fence always opens.
    ///
    /// The closing fence is judged at the fence's own container level, so each look-ahead line first
    /// replays the open containers' continuation markers; a line that breaks the chain (a block quote
    /// losing its `>`, a list item losing its indent) cannot carry the close.
    fn fence_reaches_close(&self, container: usize, fence: &FenceInfo, following: &[&str]) -> bool {
        if !self.greedy_paragraphs {
            return true;
        }
        let path = self.container_path(container);
        for line in following {
            let mut cursor = Cursor::new(line);
            if !self.strip_container_path(&path, &mut cursor) {
                return false;
            }
            if cursor.indent() <= 3 && cursor.is_closing_fence(fence.marker, fence.length) {
                return true;
            }
        }
        false
    }

    /// The chain of open containers from the document root down to `container`, root first.
    fn container_path(&self, container: usize) -> Vec<usize> {
        let mut path = Vec::new();
        let mut index = container;
        loop {
            path.push(index);
            let parent = self.parent(index);
            if parent == index {
                break;
            }
            index = parent;
        }
        path.reverse();
        path
    }

    /// Replay each container in `path` against a look-ahead `cursor`, read-only, consuming its
    /// continuation marker and leaving the cursor at the content column. Returns whether every
    /// container still matched. A blank line keeps an indent-based container (a list item, a
    /// definition body) open as interior content, but a block quote requires its `>` on every line.
    fn strip_container_path(&self, path: &[usize], cursor: &mut Cursor) -> bool {
        for &index in path {
            match self.kind(index) {
                Some(
                    Kind::Document
                    | Kind::List(_)
                    | Kind::DefinitionList
                    | Kind::DefinitionItem { .. }
                    | Kind::HtmlElement(_),
                ) => {}
                Some(Kind::BlockQuote) => {
                    cursor.skip_up_to_three_spaces();
                    if cursor.peek() == Some(b'>') {
                        cursor.advance_one();
                        cursor.consume_optional_space();
                    } else {
                        return false;
                    }
                }
                Some(Kind::FencedDiv(info)) => cursor.advance_columns(info.indent),
                Some(Kind::Item(ItemInfo { indent, .. }) | Kind::Definition { indent }) => {
                    let indent = *indent;
                    if !cursor.is_blank() {
                        if cursor.indent() >= indent {
                            cursor.advance_columns(indent);
                        } else {
                            return false;
                        }
                    }
                }
                Some(Kind::FootnoteDef(_)) => {
                    if !cursor.is_blank() {
                        if cursor.indent() >= TAB_STOP {
                            cursor.advance_columns(TAB_STOP);
                        } else {
                            return false;
                        }
                    }
                }
                _ => return false,
            }
        }
        true
    }

    /// Try to open a new block at the current cursor position inside `container`.
    // A flat dispatch over the block openers, tried in precedence order; it reads best as one sequence.
    #[allow(clippy::too_many_lines)]
    fn try_open(
        &mut self,
        container: usize,
        cursor: &mut Cursor,
        following: &[&str],
    ) -> Option<usize> {
        let indent = cursor.indent();
        let in_paragraph = matches!(self.last_open_leaf_kind(container), Some(Kind::Paragraph));
        let gates = self.greedy_gates(container, in_paragraph);

        if indent >= TAB_STOP && !in_paragraph {
            cursor.advance_columns(TAB_STOP);
            let parent = self.place(container, &Kind::IndentedCode);
            let index = self.append_child(parent, Node::new(Kind::IndentedCode));
            self.append_text(index, &cursor.rest_with_newline());
            return Some(index);
        }

        if indent < TAB_STOP {
            cursor.skip_indent();
            if let Some(block) = self.open_raw_tex(container, cursor) {
                return Some(block);
            }
            if !gates.blockquote && cursor.peek() == Some(b'>') {
                cursor.advance_one();
                cursor.consume_optional_space();
                let parent = self.place(container, &Kind::BlockQuote);
                return Some(self.append_child(parent, Node::new(Kind::BlockQuote)));
            }
            // A footnote definition opens here; its content is then gathered by the enclosing
            // container loop, the same as a block quote's. Like the other openers it folds into a
            // greedy paragraph rather than interrupting it — except when that paragraph is an open
            // definition's own body, since a definition marker always ends the preceding definition
            // and starts a new one.
            if (!gates.foldable || self.footnote_def_open_below(container))
                && self.extensions.contains(Extension::Footnotes)
                && let Some(label) = cursor.footnote_def_marker()
            {
                let key = scan::normalize_label(&label);
                let parent = self.place(container, &Kind::FootnoteDef(key.clone()));
                return Some(self.append_child(parent, Node::new(Kind::FootnoteDef(key))));
            }
            // A fenced div opens on a colon-run line carrying a valid attribute spec; it may
            // interrupt a paragraph. The whole fence line is consumed, so the div opens empty.
            if !gates.foldable && self.extensions.contains(Extension::FencedDivs) {
                let opener = div_open_fence(cursor.remaining());
                if let Some((count, attr)) = opener {
                    let width = cursor.remaining().chars().count();
                    cursor.advance_chars(width);
                    let kind = Kind::FencedDiv(DivInfo {
                        fence: count,
                        indent,
                        attr,
                    });
                    let parent = self.place(container, &kind);
                    return Some(self.append_child(parent, Node::new(kind)));
                }
            }
            // CommonMark permits up to three columns of indentation before an ATX opener; the
            // Markdown dialect requires the hashes to start at the left margin. A space after the
            // hash run is required in CommonMark and under `space_in_atx_header`; when that
            // extension is off in a Markdown dialect, a hash run glued to text opens a heading.
            let require_space =
                !self.greedy_paragraphs || self.extensions.contains(Extension::SpaceInAtxHeader);
            if !gates.heading
                && (!self.greedy_paragraphs || indent == 0)
                && let Some(level) = cursor.atx_heading(self.greedy_paragraphs, require_space)
            {
                let parent = self.place(container, &Kind::Heading(level));
                let index = self.append_child(parent, Node::new(Kind::Heading(level)));
                self.append_text(index, &strip_atx_closing(&cursor.rest(), require_space));
                self.close(index);
                return Some(index);
            }
            let fence_checkpoint = cursor.checkpoint();
            if let Some(fence) = cursor.fenced_code_start() {
                // In the Markdown family a tilde fence does not interrupt an open paragraph: its
                // opener line becomes ordinary continuation text and the lines after it are still
                // read normally, so a heading or other opener among them may still fire. A backtick
                // fence still interrupts.
                let folds_into_paragraph =
                    in_paragraph && self.greedy_paragraphs && fence.marker == b'~';
                if folds_into_paragraph {
                    cursor.reset_to(fence_checkpoint);
                } else if self.fence_opener_accepted(&fence)
                    && self.fence_reaches_close(container, &fence, following)
                {
                    let kind = Kind::FencedCode(fence);
                    let parent = self.place(container, &kind);
                    return Some(self.append_child(parent, Node::new(kind)));
                } else {
                    // The fence opens no code block; its opener line folds into a paragraph and the
                    // lines up to its matching close (if any) follow as that paragraph's text.
                    if self.greedy_paragraphs {
                        self.fence_fold = Some(fence);
                    }
                    cursor.reset_to(fence_checkpoint);
                }
            }
            // A recognized block-level HTML element whose inner content is parsed as markdown takes
            // precedence over the raw HTML-block reading, when the governing extension is on.
            if let Some(block) = self.open_html_element(container, indent, cursor) {
                return Some(block);
            }
            // With inner HTML not parsed, a block-level tag at the left margin spans to its balanced
            // close as one raw block.
            if let Some(block) =
                self.open_markdown_raw_html(container, indent, in_paragraph, cursor, following)
            {
                return Some(block);
            }
            // In that same reading, the block-level HTML kinds (6 and 7) are handled above or left as
            // inline text; only the container-agnostic kinds (comment, script/pre/style, processing
            // instruction, declaration, CDATA) still form a raw block here.
            if let Some(kind) = html_block::classify(cursor.remaining(), !in_paragraph)
                && !(self.markdown_raw_html() && matches!(kind, 6 | 7))
            {
                let parent = self.place(container, &Kind::HtmlBlock(kind));
                let index = self.append_child(parent, Node::new(Kind::HtmlBlock(kind)));
                // The start line keeps its leading indentation (always spaces after normalization).
                let line = format!("{}{}", " ".repeat(indent), cursor.rest());
                self.append_text(index, &line);
                self.append_text(index, "\n");
                if html_block::closes(kind, &line) {
                    self.close(index);
                }
                return Some(index);
            }
            // A dash ruling at the start of a fresh block opens a header-less table candidate: its
            // rows and closing ruling gather into the leaf, settled when the block closes. A
            // paragraph directly above would instead make it a headed table (claimed before the
            // openers run), so the candidate only opens where no paragraph is open. It preempts the
            // thematic break a lone dash ruling would otherwise be — a candidate that yields no table
            // settles back into that break.
            if self.text_tables_enabled()
                && !in_paragraph
                && texttable::opens_dash_table(cursor.remaining())
            {
                let parent = self.place(container, &Kind::TextTable);
                let index = self.append_child(parent, Node::new(Kind::TextTable));
                // The ruling keeps its leading indentation: a dash-ruled table's columns are
                // positional, so every line must share one left margin (here, the rows below).
                let line = format!("{}{}", " ".repeat(indent), cursor.rest());
                self.append_text(index, &line);
                self.append_text(index, "\n");
                return Some(index);
            }
            if !gates.foldable && cursor.thematic_break() {
                let parent = self.place(container, &Kind::ThematicBreak);
                let index = self.append_child(parent, Node::new(Kind::ThematicBreak));
                self.close(index);
                return Some(index);
            }
            if let Some(block) = self.open_line_block(container, indent, in_paragraph, cursor) {
                return Some(block);
            }
            // A definition marker turns the preceding paragraph into a term, or adds a definition to
            // the open entry. Its content is then opened by the enclosing loop inside the new body.
            if self.extensions.contains(Extension::DefinitionLists)
                && let Some(body) = self.open_definition(container, indent, cursor)
            {
                return Some(body);
            }
            if !gates.list_start
                && let Some(list) = self.list_marker(container, indent, cursor)
            {
                return Some(list);
            }
            // Under `lists_without_preceding_blankline` a line that has a list-marker shape ends a
            // greedy paragraph even when no enabled construct opens there: it starts a fresh
            // paragraph rather than folding into the open one. Three shapes break the paragraph:
            //   - a definition marker (`:`/`~`) when no definition list opens here;
            //   - an example-list marker (`(@)`, `(@label)`) when example lists are off;
            //   - any other enumerator shape carrying content on its line — judged with every
            //     enumerator style allowed, so independent of which styles actually form a list.
            // A decimal enumerator closed by a single `)` (`2)`) is the one exception for that last
            // shape — too easily ordinary prose — so it neither breaks the paragraph nor opens a
            // list. The first two shapes break regardless of any trailing content.
            if in_paragraph
                && self
                    .extensions
                    .contains(Extension::ListsWithoutPrecedingBlankline)
            {
                let definition_shape = cursor.definition_marker_at().is_some();
                let example_shape = matches!(
                    cursor.list_marker_at(true, true, false),
                    Some(marker) if matches!(marker.style, ListNumberStyle::Example)
                );
                let enumerator_shape =
                    cursor
                        .list_marker_at(true, false, false)
                        .is_some_and(|marker| {
                            !(marker.blank_after
                                || matches!(marker.style, ListNumberStyle::Decimal)
                                    && matches!(marker.delim, ListNumberDelim::OneParen))
                        });
                if definition_shape || example_shape || enumerator_shape {
                    if let Some(paragraph) = self
                        .last_open_child(container)
                        .filter(|&child| matches!(self.kind(child), Some(Kind::Paragraph)))
                    {
                        self.close(paragraph);
                    }
                    let parent = self.place(container, &Kind::Paragraph);
                    return Some(self.append_child(parent, Node::new(Kind::Paragraph)));
                }
            }
        }
        None
    }

    fn last_open_leaf_kind(&self, container: usize) -> Option<Kind> {
        let leaf = self.deepest_open(container);
        self.kind(leaf).cloned()
    }

    /// Open a line block on a `|` flush at the line start. A line block never interrupts a paragraph
    /// and never carries leading indentation; its whole line is its first entry, with later lines
    /// claimed by `continue_line_block` before the openers run.
    fn open_line_block(
        &mut self,
        container: usize,
        indent: usize,
        in_paragraph: bool,
        cursor: &mut Cursor,
    ) -> Option<usize> {
        if !self.extensions.contains(Extension::LineBlocks)
            || indent != 0
            || in_paragraph
            || !is_line_block_marker(cursor.remaining())
        {
            return None;
        }
        let raw = cursor.rest();
        cursor.advance_chars(raw.chars().count());
        let parent = self.place(container, &Kind::LineBlock);
        let index = self.append_child(parent, Node::new(Kind::LineBlock));
        self.append_text(index, &raw);
        self.append_text(index, "\n");
        Some(index)
    }

    /// Open a definition body at a `:`/`~` marker, returning the new [`Kind::Definition`] container
    /// the enclosing loop then fills. The marker either starts a fresh definition of the open entry
    /// (when the cursor sits directly in a [`Kind::DefinitionItem`]) or, when the container's last
    /// child is a paragraph, turns that paragraph into a term — extending an immediately preceding
    /// definition list or beginning a new one. A marker in any other position is not consumed.
    fn open_definition(
        &mut self,
        container: usize,
        marker_indent: usize,
        cursor: &mut Cursor,
    ) -> Option<usize> {
        let blank_after = cursor.definition_marker_at()?;
        let item = if matches!(self.kind(container), Some(Kind::DefinitionItem { .. })) {
            container
        } else {
            self.start_definition_item(container)?
        };
        let indent = Self::consume_definition_marker(marker_indent, blank_after, cursor);
        Some(self.append_child(item, Node::new(Kind::Definition { indent })))
    }

    /// Turn the container's last child — which must be a non-empty paragraph — into a definition
    /// term, returning the [`Kind::DefinitionItem`] that now holds it. The term joins an immediately
    /// preceding definition list, else opens a new one. Returns `None` when there is no term
    /// paragraph to consume, leaving the marker as ordinary text.
    fn start_definition_item(&mut self, container: usize) -> Option<usize> {
        let &term_index = self.nodes.get(container)?.children.last()?;
        let term_node = self.nodes.get(term_index)?;
        if !matches!(term_node.kind, Kind::Paragraph) || term_node.text.trim().is_empty() {
            return None;
        }
        // A paragraph that is itself a grid or pipe table is not a definition term; a following `:`
        // line is its caption, not a definition marker.
        if self.extensions.contains(Extension::GridTables)
            && grid::parse(term_node.text.trim()).is_some()
        {
            return None;
        }
        if self.extensions.contains(Extension::PipeTables)
            && table::try_parse(term_node.text.trim(), self.greedy_paragraphs).is_some()
        {
            return None;
        }
        let term = term_node.text.trim().to_owned();
        let tight = !term_node.last_line_blank;
        let previous = self
            .nodes
            .get(container)
            .and_then(|node| node.children.iter().rev().nth(1).copied());
        let list = match previous {
            Some(prev) if matches!(self.kind(prev), Some(Kind::DefinitionList)) => {
                self.reopen_definition_list(prev);
                if let Some(node) = self.nodes.get_mut(container) {
                    node.children.pop();
                }
                prev
            }
            _ => {
                if let Some(node) = self.nodes.get_mut(container) {
                    node.children.pop();
                }
                self.append_child(container, Node::new(Kind::DefinitionList))
            }
        };
        Some(self.append_child(list, Node::new(Kind::DefinitionItem { term, tight })))
    }

    /// Reopen a definition list to accept a further term, closing the entry it last held so the new
    /// item descends as a sibling rather than nesting under the old one.
    fn reopen_definition_list(&mut self, list: usize) {
        if let Some(node) = self.nodes.get_mut(list) {
            node.open = true;
        }
        if let Some(&last_item) = self.nodes.get(list).and_then(|node| node.children.last()) {
            self.close(last_item);
        }
    }

    /// Consume a definition marker (`:`/`~` plus its following spaces) and return the column its
    /// content begins at. One through four spaces widen the content indent by that many columns;
    /// five or more collapse to a single column. An empty marker takes no content column at all, so
    /// its body begins one column past the marker — deferred indented lines join it as their own
    /// paragraph rather than continuing it.
    fn consume_definition_marker(
        marker_indent: usize,
        blank_after: bool,
        cursor: &mut Cursor,
    ) -> usize {
        cursor.advance_chars(1);
        let after_marker = cursor.indent();
        let content_offset = if blank_after {
            0
        } else if after_marker > TAB_STOP {
            1
        } else {
            after_marker
        };
        if !blank_after {
            cursor.advance_columns(content_offset);
        }
        marker_indent + 1 + content_offset
    }

    /// Try to open a list item (and its containing list) at the cursor.
    fn list_marker(
        &mut self,
        container: usize,
        marker_indent: usize,
        cursor: &mut Cursor,
    ) -> Option<usize> {
        let fancy = self.extensions.contains(Extension::FancyLists);
        let example = self.extensions.contains(Extension::ExampleLists);
        // The greedy Markdown dialect without fancy lists still recognizes the `#.` auto-number
        // placeholder, but its ordered lists are limited to the period delimiter: a `)`-delimited
        // enumerator such as `1)` is left as prose.
        let plain_ordered = self.greedy_paragraphs && !fancy;
        let parsed = cursor.list_marker_at(fancy, example, plain_ordered)?;
        if plain_ordered
            && !parsed.bullet
            && !matches!(
                parsed.delim,
                ListNumberDelim::DefaultDelim | ListNumberDelim::Period
            )
        {
            return None;
        }

        // These restrictions apply only when the marker would interrupt a *bare* paragraph (one not
        // already inside a list): an empty item cannot interrupt, and an ordered marker may only
        // interrupt when it is a decimal `1.`/`1)` — any other enumerator (a non-1 start, or an
        // alphabetic/roman/parenthesized one) is too easily confused with running prose. Inside an
        // open list any marker is allowed — a matching one continues the list, a differing one ends
        // it and begins a new sibling list.
        //
        // The paragraph must be a direct child of the container the marker opens into: a paragraph
        // hanging in a deeper, unmatched container (left open only for a possible lazy continuation)
        // is at a different level, so the marker starts a fresh list rather than interrupting it.
        let in_paragraph = self
            .last_open_child(container)
            .is_some_and(|child| matches!(self.kind(child), Some(Kind::Paragraph)));
        let inside_list = matches!(self.kind(container), Some(Kind::List(_)));
        if in_paragraph && !inside_list {
            if parsed.blank_after {
                return None;
            }
            // Where paragraphs are greedy, a fresh list never interrupts one (that is suppressed
            // before the marker is read), so this branch is reached only for a marker indented into
            // an item body — a sublist, which opens regardless of its start enumerator.
            let decimal_one = matches!(parsed.style, ListNumberStyle::Decimal) && parsed.start == 1;
            if !self.greedy_paragraphs && !parsed.bullet && !decimal_one {
                return None;
            }
        }

        cursor.advance_chars(parsed.marker_width);
        let after_marker = cursor.indent();
        // 1–4 spaces after the marker all count toward the content indent; 5+ collapse to one and
        // the rest become leading indentation of the item's content (an indented code block).
        let content_offset = if parsed.blank_after || after_marker > TAB_STOP {
            1
        } else {
            after_marker
        };
        if !parsed.blank_after {
            cursor.advance_columns(content_offset);
        }
        let item_indent = marker_indent + parsed.marker_width + content_offset;

        let list_index = self.ensure_list(container, &parsed);
        let item = Node::new(Kind::Item(ItemInfo {
            indent: item_indent,
            example_label: parsed.example_label.clone(),
        }));
        Some(self.append_child(list_index, item))
    }

    /// Reuse the matching open list for this marker, else start a new one. `container` may itself
    /// be the open list (a continuing item) or the list's parent (a fresh or restarted list).
    fn ensure_list(&mut self, container: usize, parsed: &ListMarkerParse) -> usize {
        if self.list_matches(container, parsed) {
            return container;
        }
        let info = list_info(parsed);
        let parent = self.place(container, &Kind::List(info.clone()));
        if let Some(last) = self.last_open_child(parent) {
            if self.list_matches(last, parsed) {
                return last;
            }
            if matches!(self.kind(last), Some(Kind::List(_))) {
                self.close(last);
            }
        }
        // A lone `i`/`I` enumerator is ambiguous between roman one and the ninth letter. When the
        // new list directly follows another list it reads as alphabetic; opening a document or
        // following any other block it reads as roman (the value chosen by `parse_enum_body`).
        let info = if self.preceding_is_list(parent) {
            demote_lone_roman(info)
        } else {
            info
        };
        self.append_child(parent, Node::new(Kind::List(info)))
    }

    /// Whether `parent`'s last child — open or closed — is a list, so a new sibling list abuts it.
    fn preceding_is_list(&self, parent: usize) -> bool {
        self.nodes
            .get(parent)
            .and_then(|node| node.children.last().copied())
            .is_some_and(|child| matches!(self.kind(child), Some(Kind::List(_))))
    }

    fn list_matches(&self, index: usize, parsed: &ListMarkerParse) -> bool {
        let Some(Kind::List(info)) = self.kind(index) else {
            return false;
        };
        if info.bullet != parsed.bullet {
            return false;
        }
        if info.bullet {
            // Bullet lists group by the marker character: switching `-`/`+`/`*` starts a new list.
            return info.marker == parsed.marker;
        }
        // A `#` placeholder continues any ordered list, adopting the list's own style and delimiter.
        if parsed.hash {
            return true;
        }
        // Ordered lists group by delimiter and by whether this marker reads as a continuation of the
        // list's established number style.
        info.delim == parsed.delim && continues_ordered(info.style, parsed)
    }

    fn add_line(&mut self, container: usize, started_new: bool, blank: bool, cursor: &mut Cursor) {
        if blank {
            let deepest = self.deepest_open(container);
            if matches!(self.kind(deepest), Some(Kind::Paragraph)) {
                self.close(deepest);
            }
            return;
        }

        if started_new {
            // The opener attached its own leaf; only a freshly-opened paragraph or container
            // (block quote / list item with trailing content) still needs this line's text.
            let leaf = self.deepest_open(container);
            match self.kind(leaf).cloned() {
                Some(Kind::Paragraph) => {
                    self.note_paragraph_indent(leaf, cursor);
                    self.append_text(leaf, &cursor.rest());
                    self.append_text(leaf, "\n");
                }
                Some(
                    Kind::Heading(_)
                    | Kind::ThematicBreak
                    | Kind::LineBlock
                    | Kind::TextTable
                    | Kind::IndentedCode
                    | Kind::FencedCode(_)
                    | Kind::HtmlBlock(_)
                    | Kind::RawTex { .. },
                ) => {}
                _ => {
                    // An opener whose own line carries no content (a bare marker) leaves its
                    // container empty rather than seeding an empty paragraph.
                    let rest = cursor.rest();
                    if !rest.trim().is_empty() {
                        let index = self.append_child(leaf, Node::new(Kind::Paragraph));
                        self.note_paragraph_indent(index, cursor);
                        self.append_text(index, &rest);
                        self.append_text(index, "\n");
                    }
                }
            }
            return;
        }

        // No new block opened: continue an open paragraph, lazily crossing any unmatched
        // containers, or start a fresh paragraph in the matched container.
        let deepest = self.deepest_open(0);
        if matches!(self.kind(deepest), Some(Kind::Paragraph)) {
            self.append_text(deepest, &cursor.rest());
            self.append_text(deepest, "\n");
            return;
        }

        let parent = self.place(container, &Kind::Paragraph);
        let index = self.append_child(parent, Node::new(Kind::Paragraph));
        self.note_paragraph_indent(index, cursor);
        self.append_text(index, &cursor.rest());
        self.append_text(index, "\n");
    }

    /// Record the column a freshly opened paragraph's first line began at, so a dash ruling on the
    /// following line can read a headed table's alignment against the header's true position. Only an
    /// empty paragraph is its first line; a continuation must not overwrite the recorded column.
    fn note_paragraph_indent(&mut self, index: usize, cursor: &Cursor) {
        let indent = cursor.noted_indent();
        if let Some(node) = self.nodes.get_mut(index)
            && node.text.is_empty()
        {
            node.indent = indent;
        }
    }

    fn append_text(&mut self, index: usize, text: &str) {
        if let Some(node) = self.nodes.get_mut(index) {
            node.text.push_str(text);
        }
    }

    fn finish(mut self) -> (Vec<IrBlock>, RefMap, FootnoteDefs, ExampleMap) {
        // Pre-pass: pull link reference definitions out of every paragraph.
        for index in 0..self.nodes.len() {
            if matches!(self.kind(index), Some(Kind::Paragraph)) {
                let text = self.node_text(index);
                let column_zero = self.nodes.get(index).is_some_and(|node| node.indent == 0);
                let stripped = self.extract_refs(&text, column_zero);
                if let Some(node) = self.nodes.get_mut(index) {
                    node.text = stripped;
                }
            }
        }
        let mut footnotes = self.collect_footnotes();
        for blocks in footnotes.values_mut() {
            attach_table_captions(blocks, self.extensions);
        }
        let examples = self.number_examples();
        let mut blocks = self.build_children(0);
        attach_table_captions(&mut blocks, self.extensions);
        (blocks, self.refs, footnotes, examples)
    }

    /// Number every example-list item in one document-wide sequence and record the label→number map.
    /// Each example list's `start` becomes its first item's number; the map drives `@label`
    /// references during the inline phase.
    fn number_examples(&mut self) -> ExampleMap {
        let mut counter = 0;
        let mut map = ExampleMap::new();
        self.number_examples_in(0, &mut counter, &mut map);
        map
    }

    /// Walk `index` and its descendants in document order, assigning example numbers. Items are
    /// visited before the content nested beneath them, so a nested example list continues the same
    /// sequence in reading order.
    fn number_examples_in(&mut self, index: usize, counter: &mut i32, map: &mut ExampleMap) {
        let Some(node) = self.nodes.get(index) else {
            return;
        };
        let is_example =
            matches!(&node.kind, Kind::List(info) if info.style == ListNumberStyle::Example);
        let children = node.children.clone();
        if !is_example {
            for child in children {
                self.number_examples_in(child, counter, map);
            }
            return;
        }
        let mut start = None;
        for item in children {
            let Some(item_node) = self.nodes.get(item) else {
                continue;
            };
            let Kind::Item(info) = &item_node.kind else {
                continue;
            };
            let label = info.example_label.clone();
            let item_children = item_node.children.clone();
            start.get_or_insert(next_example_number(label, counter, map));
            for child in item_children {
                self.number_examples_in(child, counter, map);
            }
        }
        if let Some(start) = start
            && let Some(node) = self.nodes.get_mut(index)
            && let Kind::List(info) = &mut node.kind
        {
            info.start = start;
        }
    }

    /// Gather every footnote definition's block content, keyed by its normalized label. Definitions
    /// are visited in document order (node-creation order); when a label repeats, the first wins.
    fn collect_footnotes(&self) -> FootnoteDefs {
        let mut footnotes = FootnoteDefs::new();
        for index in 0..self.nodes.len() {
            if let Some(Kind::FootnoteDef(key)) = self.kind(index)
                && !footnotes.contains_key(key)
            {
                footnotes.insert(key.clone(), self.build_children(index));
            }
        }
        footnotes
    }

    fn node_text(&self, index: usize) -> String {
        self.nodes
            .get(index)
            .map(|node| node.text.clone())
            .unwrap_or_default()
    }

    /// Borrow a node's accumulated text without copying. Continuation checks that only inspect the
    /// buffer use this; callers that mutate the node afterward take the owned [`Self::node_text`].
    fn node_text_ref(&self, index: usize) -> Option<&str> {
        self.nodes.get(index).map(|node| node.text.as_str())
    }

    /// Pull leading definitions off `text` and return what remains. Link reference definitions are
    /// always eligible; an abbreviation definition (`abbreviations`) requires its host paragraph to
    /// begin flush at the container's left edge, so `column_zero` gates it.
    fn extract_refs(&mut self, text: &str, column_zero: bool) -> String {
        let abbreviations = column_zero && self.extensions.contains(Extension::Abbreviations);
        let mut remaining = text;
        loop {
            if let Some((label, def, rest)) =
                scan::parse_link_reference_definition(remaining, self.greedy_paragraphs)
            {
                self.refs.entry(label).or_insert(def);
                remaining = rest;
                continue;
            }
            if abbreviations && let Some(rest) = scan::parse_abbreviation_definition(remaining) {
                remaining = rest;
                continue;
            }
            break;
        }
        remaining.to_owned()
    }

    fn build_children(&self, index: usize) -> Vec<IrBlock> {
        let Some(node) = self.nodes.get(index) else {
            return Vec::new();
        };
        let mut out = Vec::new();
        for &child in &node.children {
            // A raw HTML element contributes three blocks — its open tag, its parsed content, and its
            // close tag — flattened into this list rather than nested under a single block.
            if let Some(Kind::HtmlElement(info)) = self.kind(child)
                && !info.as_div
            {
                out.push(IrBlock::RawHtml(info.raw_open.clone()));
                let mut content = self.build_children(child);
                if info.tighten_last {
                    tighten_last_block(&mut content);
                }
                out.append(&mut content);
                // An element left open at end of input has no close tag; emit one only when present.
                if !info.raw_close.is_empty() {
                    out.push(IrBlock::RawHtml(info.raw_close.clone()));
                }
                continue;
            }
            if let Some(block) = self.build_block(child) {
                out.push(block);
            }
        }
        out
    }

    fn build_block(&self, index: usize) -> Option<IrBlock> {
        let node = self.nodes.get(index)?;
        let block = match &node.kind {
            // A footnote definition is lifted out of the body into the footnote map; its former
            // container stays but empties. The two grouping levels of a definition list carry no
            // block of their own — the list is built from its items, each item from its definitions.
            Kind::Document
            | Kind::Item(_)
            | Kind::FootnoteDef(_)
            | Kind::DefinitionItem { .. }
            | Kind::Definition { .. } => return None,
            Kind::Paragraph => {
                let trimmed = node.text.trim();
                if trimmed.is_empty() {
                    return None;
                }
                if self.extensions.contains(Extension::GridTables)
                    && let Some(table) = grid::parse(trimmed)
                {
                    IrBlock::GridTable(Box::new(table))
                } else if self.extensions.contains(Extension::PipeTables)
                    && let Some((alignments, header, rows)) =
                        table::try_parse(trimmed, self.greedy_paragraphs)
                {
                    IrBlock::Table {
                        alignments,
                        header,
                        rows,
                        caption: None,
                        attr: Attr::default(),
                    }
                } else if node.as_plain {
                    IrBlock::Plain(trimmed.to_owned())
                } else {
                    IrBlock::Para(trimmed.to_owned())
                }
            }
            Kind::LineBlock => IrBlock::LineBlock(line_block_lines(&node.text)),
            Kind::TextTable => {
                let lines = split_table_lines(&node.text);
                let (table, _) = texttable::parse(&lines, self.extensions)?;
                IrBlock::TextTable(Box::new(table))
            }
            Kind::DefinitionList => self.build_definition_list(index),
            Kind::Heading(level) => IrBlock::Heading(*level, node.text.trim().to_owned()),
            Kind::ThematicBreak => IrBlock::ThematicBreak,
            Kind::IndentedCode => {
                IrBlock::CodeBlock(Attr::default(), strip_trailing_blank_lines(&node.text))
            }
            Kind::FencedCode(fence) => {
                // A closing fence drops the final newline; a block ended by end-of-input (still
                // open) keeps it.
                let text = if node.open {
                    node.text.clone()
                } else {
                    strip_one_trailing_newline(&node.text)
                };
                // An info string that is exactly `{=FORMAT}` marks the fence's contents as raw
                // output for FORMAT, emitted verbatim rather than as a code block.
                if self.extensions.contains(Extension::RawAttribute)
                    && let Some(format) = raw_block_format(&fence.info)
                {
                    IrBlock::RawBlock(Format(format), text)
                } else {
                    IrBlock::CodeBlock(fence_attr(&fence.info, self.extensions), text)
                }
            }
            Kind::HtmlBlock(kind) => IrBlock::RawHtml(self.finalize_html_block(node, *kind)),
            Kind::RawHtmlSpan { .. } => {
                IrBlock::RawHtml(node.text.trim_end_matches('\n').to_owned())
            }
            Kind::RawTex { .. } => {
                // A closed environment is verbatim raw TeX. One left open at end of input never
                // found its `\end`, so its lines are ordinary text: they fall back to a paragraph.
                if node.open {
                    let trimmed = node.text.trim();
                    if trimmed.is_empty() {
                        return None;
                    }
                    IrBlock::Para(trimmed.to_owned())
                } else {
                    IrBlock::RawBlock(Format("tex".to_owned()), node.text.clone())
                }
            }
            Kind::BlockQuote => {
                if self.extensions.contains(Extension::Alerts)
                    && let Some(alert) = self.build_alert(index)
                {
                    alert
                } else {
                    IrBlock::BlockQuote(self.build_children(index))
                }
            }
            Kind::FencedDiv(info) => IrBlock::Div(info.attr.clone(), self.build_children(index)),
            Kind::HtmlElement(info) => {
                // The raw form is emitted as three blocks (open tag, content, close tag), spliced
                // into the parent by `build_children`; only the div form is a single block here.
                if !info.as_div {
                    return None;
                }
                let mut children = self.build_children(index);
                if info.tighten_last {
                    tighten_last_block(&mut children);
                }
                IrBlock::Div(info.attr.clone(), children)
            }
            Kind::List(info) => self.build_list(index, info),
        };
        Some(block)
    }

    /// Finalize a raw HTML block's text. The markdown dialect drops a block's final newline; the
    /// strict dialect instead pads an unterminated kind 1–5 block, which closes only on an explicit
    /// end tag, so reaching end-of-input with it still open surfaces as a trailing blank line.
    fn finalize_html_block(&self, node: &Node, kind: u8) -> String {
        let mut text = node.text.clone();
        if self.greedy_paragraphs {
            if text.ends_with('\n') {
                text.pop();
            }
        } else if node.open && matches!(kind, 1..=5) {
            text.push('\n');
        }
        text
    }

    /// A blockquote whose first content line is exactly an alert marker `[!TYPE]` (with `TYPE` one of
    /// the recognized kinds, and nothing but trailing whitespace after the `]`) becomes a `Div`
    /// classed by the lowercased type. The broad Markdown dialect requires the uppercase spelling;
    /// the `CommonMark` engine accepts any casing. Its first child is a titled `Div` holding the
    /// type's display name; the marker line is stripped from the quote's first paragraph, and the
    /// rest of the quote's content follows. Returns `None` when the first line is not a clean marker,
    /// leaving the blockquote as an ordinary `BlockQuote`.
    fn build_alert(&self, index: usize) -> Option<IrBlock> {
        let node = self.nodes.get(index)?;
        let &first = node.children.first()?;
        let first_node = self.nodes.get(first)?;
        if !matches!(first_node.kind, Kind::Paragraph) {
            return None;
        }
        // The marker must occupy the paragraph's first line, with no leading whitespace and only
        // trailing whitespace after the closing bracket; inspecting the raw (untrimmed) text keeps
        // a leading space — which disables the marker — visible.
        let (marker_line, rest_of_para) = match first_node.text.split_once('\n') {
            Some((line, rest)) => (line, Some(rest)),
            None => (first_node.text.as_str(), None),
        };
        // Known limitation: a marker indented two or more columns inside the quote (e.g. `>  [!NOTE]`)
        // is not an alert, but the block phase has already folded that insignificant paragraph indent
        // away by this point, so the marker still reads as clean here. Markers at zero or one column
        // — the conventional spelling — are classified correctly.
        let alert_type = alert_marker_type(marker_line, self.greedy_paragraphs)?;

        let title = IrBlock::Div(
            Attr {
                id: String::new(),
                classes: vec!["title".to_owned()],
                attributes: Vec::new(),
            },
            vec![IrBlock::Para(alert_type.title.to_owned())],
        );

        let mut content = vec![title];
        // Anything left on the marker's own paragraph after dropping its first line stays a paragraph.
        if let Some(rest) = rest_of_para {
            let trimmed = rest.trim();
            if !trimmed.is_empty() {
                content.push(IrBlock::Para(trimmed.to_owned()));
            }
        }
        for &child in node.children.iter().skip(1) {
            if let Some(block) = self.build_block(child) {
                content.push(block);
            }
        }

        Some(IrBlock::Div(
            Attr {
                id: String::new(),
                classes: vec![alert_type.class.to_owned()],
                attributes: Vec::new(),
            },
            content,
        ))
    }

    /// Build a definition list from its item and definition containers. Each item contributes its
    /// term text and the block content of each `:`/`~` definition; a tight item demotes its
    /// definitions' top-level paragraphs to `Plain`.
    fn build_definition_list(&self, index: usize) -> IrBlock {
        let mut items = Vec::new();
        if let Some(list) = self.nodes.get(index) {
            for &item_index in &list.children {
                let Some(Kind::DefinitionItem { term, tight }) = self.kind(item_index) else {
                    continue;
                };
                let mut definitions = Vec::new();
                if let Some(item) = self.nodes.get(item_index) {
                    for &def_index in &item.children {
                        let mut blocks = self.build_children(def_index);
                        if *tight {
                            demote_loose_paragraphs(&mut blocks);
                        }
                        definitions.push(blocks);
                    }
                }
                items.push(IrDefItem {
                    term: term.clone(),
                    definitions,
                });
            }
        }
        IrBlock::DefinitionList(items)
    }

    fn build_list(&self, index: usize, info: &ListInfo) -> IrBlock {
        let tight = self.list_is_tight(index);
        let mut items = Vec::new();
        if let Some(node) = self.nodes.get(index) {
            for &item in &node.children {
                let mut blocks = self.build_children(item);
                if tight {
                    demote_loose_paragraphs(&mut blocks);
                }
                items.push(blocks);
            }
        }
        if info.bullet {
            IrBlock::BulletList(items)
        } else {
            // The Markdown dialect honors an ordered list's start number only when the `startnum`
            // extension is enabled; with it disabled every ordered list begins at 1. CommonMark and
            // GFM have no such extension and always honor the start number.
            let start = if self.greedy_paragraphs && !self.extensions.contains(Extension::Startnum)
            {
                1
            } else {
                info.start
            };
            // Without fancy lists the greedy Markdown dialect does not distinguish enumerator styles
            // or delimiters: every ordered list carries the default style and delimiter.
            let (style, delim) =
                if self.greedy_paragraphs && !self.extensions.contains(Extension::FancyLists) {
                    (ListNumberStyle::DefaultStyle, ListNumberDelim::DefaultDelim)
                } else {
                    (info.style, info.delim)
                };
            let attrs = ListAttributes {
                start,
                style,
                delim,
            };
            IrBlock::OrderedList(attrs, items)
        }
    }

    /// A list is tight unless a blank line separates two of its items, or separates two blocks
    /// within an item (`CommonMark` §5.3).
    fn list_is_tight(&self, index: usize) -> bool {
        let Some(list) = self.nodes.get(index) else {
            return true;
        };
        for (position, &item) in list.children.iter().enumerate() {
            let has_next_item = position + 1 < list.children.len();
            if has_next_item && self.ends_with_blank_line(item) {
                return false;
            }
            if let Some(item_node) = self.nodes.get(item) {
                for (child_position, &child) in item_node.children.iter().enumerate() {
                    let has_next = has_next_item || child_position + 1 < item_node.children.len();
                    if has_next && self.ends_with_blank_line(child) {
                        return false;
                    }
                }
            }
        }
        true
    }

    /// Whether `index` (or the tail of its last-child chain through lists and items) was followed
    /// by a blank line.
    fn ends_with_blank_line(&self, mut index: usize) -> bool {
        loop {
            let Some(node) = self.nodes.get(index) else {
                return false;
            };
            if node.last_line_blank {
                return true;
            }
            if matches!(node.kind, Kind::List(_) | Kind::Item(_)) {
                match node.children.last() {
                    Some(&last) => index = last,
                    None => return false,
                }
            } else {
                return false;
            }
        }
    }
}

/// Tighten an HTML element's final content block from `Para` to `Plain` when no blank line
/// separated it from the close tag.
fn tighten_last_block(blocks: &mut [IrBlock]) {
    if let Some(block) = blocks.last_mut()
        && let IrBlock::Para(text) = block
    {
        *block = IrBlock::Plain(std::mem::take(text));
    }
}

/// In a tight list, item paragraphs render as `Plain` rather than `Para`.
pub(crate) fn demote_loose_paragraphs(blocks: &mut [IrBlock]) {
    for block in blocks {
        if let IrBlock::Para(text) = block {
            *block = IrBlock::Plain(std::mem::take(text));
        }
    }
}

/// Attach table captions: a paragraph led by `Table:`, `table:`, or `:` becomes the caption of the
/// table — pipe, dash-ruled, or grid — immediately before it, or, failing that, immediately after
/// it. The caption attaches to the nearer uncaptioned table and is removed from the block list; with
/// no such table it stays an ordinary paragraph. Working in document order, a caption above a table
/// is reached first, so it wins over one below. The pass recurses into nested block containers first.
fn attach_table_captions(blocks: &mut Vec<IrBlock>, ext: Extensions) {
    for block in blocks.iter_mut() {
        match block {
            IrBlock::Div(_, children) | IrBlock::BlockQuote(children) => {
                attach_table_captions(children, ext);
            }
            IrBlock::BulletList(items) | IrBlock::OrderedList(_, items) => {
                for item in items {
                    attach_table_captions(item, ext);
                }
            }
            IrBlock::DefinitionList(items) => {
                for item in items {
                    for definition in &mut item.definitions {
                        attach_table_captions(definition, ext);
                    }
                }
            }
            _ => {}
        }
    }
    if !ext.contains(Extension::TableCaptions) {
        return;
    }
    let mut i = 0;
    while i < blocks.len() {
        let Some(caption) = caption_text(blocks.get(i)) else {
            i += 1;
            continue;
        };
        let attached = (i >= 1 && set_table_caption(blocks, i - 1, &caption, ext))
            || (i + 1 < blocks.len() && set_table_caption(blocks, i + 1, &caption, ext));
        if attached {
            blocks.remove(i);
        } else {
            i += 1;
        }
    }
}

/// The caption text of a paragraph block led by a `Table:`/`table:`/`:` marker, with the marker
/// stripped; `None` for any other block.
fn caption_text(block: Option<&IrBlock>) -> Option<String> {
    let IrBlock::Para(text) = block? else {
        return None;
    };
    let (first, rest) = match text.split_once('\n') {
        Some((first, rest)) => (first, Some(rest)),
        None => (text.as_str(), None),
    };
    let body = strip_caption_marker(first)?;
    Some(match rest {
        Some(rest) => format!("{body}\n{rest}"),
        None => body.to_owned(),
    })
}

/// Strip a leading `Table:`, `table:`, or `:` caption marker and the spaces after it, returning the
/// remaining first-line text; `None` when no marker is present. Only the marker's first letter may
/// vary in case, so `TABLE:` is not a marker.
fn strip_caption_marker(first: &str) -> Option<&str> {
    for marker in ["Table:", "table:"] {
        if let Some(rest) = first.strip_prefix(marker) {
            return Some(rest.trim_start());
        }
    }
    first.strip_prefix(':').map(str::trim_start)
}

/// Set `text` as the caption of the table at `index`, if that block is a pipe, dash-ruled, or grid
/// table that has no caption yet. Returns whether the caption was attached. With
/// [`Extension::TableAttributes`] enabled, a trailing `{…}` attribute block on the caption is split
/// off and applied to the table's outer attributes; the remaining text becomes the caption.
fn set_table_caption(blocks: &mut [IrBlock], index: usize, text: &str, ext: Extensions) -> bool {
    let (caption_slot, attr_slot) = match blocks.get_mut(index) {
        Some(IrBlock::Table { caption, attr, .. }) => (caption, attr),
        Some(IrBlock::TextTable(table)) => (&mut table.caption, &mut table.attr),
        Some(IrBlock::GridTable(table)) => (&mut table.caption, &mut table.attr),
        _ => return false,
    };
    if caption_slot.is_some() {
        return false;
    }
    let (body, parsed) = if ext.contains(Extension::TableAttributes) {
        split_trailing_attr(text)
    } else {
        (text, None)
    };
    *caption_slot = Some(body.to_owned());
    if let Some(parsed) = parsed {
        *attr_slot = parsed;
    }
    true
}

/// Split a trailing `{…}` attribute block off the end of a caption. Returns the caption text with the
/// block and any whitespace before it removed, alongside the parsed attributes. When the text has no
/// well-formed trailing attribute block, the text is returned unchanged with `None`.
fn split_trailing_attr(text: &str) -> (&str, Option<Attr>) {
    let trimmed = text.trim_end();
    if !trimmed.ends_with('}') {
        return (text, None);
    }
    // The trailing block opens at some `{`; find the one whose attribute parse consumes exactly to
    // the end. Earlier `{` characters stay part of the caption text.
    for (open, _) in trimmed.char_indices().filter(|&(_, ch)| ch == '{') {
        if let Some(rest) = trimmed.get(open..)
            && let Some((attr, consumed)) = attr::parse_attributes(rest)
            && consumed == rest.len()
        {
            let body = trimmed.get(..open).map_or("", str::trim_end);
            return (body, Some(attr));
        }
    }
    (text, None)
}

enum Continue {
    Matched,
    MatchedLeaf,
    NotMatched,
}

/// Math environments are rendered inline rather than as block-level raw TeX, so a `\begin` opening
/// one is not a block environment. The base name is matched exactly; a single trailing `*` (the
/// unnumbered variant) counts as the same environment.
fn is_math_environment(name: &str) -> bool {
    const MATH_ENVS: &[&str] = &[
        "equation",
        "align",
        "gather",
        "multline",
        "eqnarray",
        "flalign",
        "alignat",
        "displaymath",
        "math",
        "dmath",
    ];
    let base = name.strip_suffix('*').unwrap_or(name);
    MATH_ENVS.contains(&base)
}

/// If `s` begins with `\<keyword>` (optionally followed by spaces) then a braced `{name}`, return
/// the literal brace content. The leading backslash must not itself be escaped — callers pass the
/// raw slice from a line start, where this holds. The brace content runs to the first `}` and may be
/// empty; it is compared exactly elsewhere, so inner spaces are significant.
fn raw_tex_env_name(s: &str, keyword: &[u8]) -> Option<String> {
    let after_backslash = s.strip_prefix('\\')?;
    let after_keyword = after_backslash.strip_prefix(std::str::from_utf8(keyword).ok()?)?;
    let after_spaces = after_keyword.trim_start_matches(' ');
    let body = after_spaces.strip_prefix('{')?;
    let close = body.find('}')?;
    body.get(..close).map(str::to_owned)
}

/// Scan one source `line` of an open environment named `name`, starting at nesting `depth`. Returns
/// the depth after the line and, when the environment's matching `\end{name}` is reached (depth back
/// to zero), the byte offset just past that `\end{...}`. Backslash escapes are honored: a `\\`
/// consumes both characters so an escaped command never counts toward the depth.
fn raw_tex_scan(line: &str, name: &str, mut depth: usize) -> (usize, Option<usize>) {
    let bytes = line.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes.get(i) != Some(&b'\\') {
            i += 1;
            continue;
        }
        // An escaped backslash consumes both bytes and starts no command.
        if bytes.get(i + 1) == Some(&b'\\') {
            i += 2;
            continue;
        }
        let rest = line.get(i..).unwrap_or("");
        if raw_tex_env_name(rest, b"begin").as_deref() == Some(name) {
            depth += 1;
            i += 1;
            continue;
        }
        if raw_tex_env_name(rest, b"end").as_deref() == Some(name) {
            depth = depth.saturating_sub(1);
            // Advance past this `\end{...}` so the close offset lands just after its brace.
            let end_off = rest.find('}').map_or(line.len(), |brace| i + brace + 1);
            if depth == 0 {
                return (0, Some(end_off));
            }
            i = end_off;
            continue;
        }
        i += 1;
    }
    (depth, None)
}

/// The number for an example item, given its `@label` (or `None` for the anonymous `@`). A new or
/// anonymous item advances the shared counter; a repeated label reuses its first number.
fn next_example_number(label: Option<String>, counter: &mut i32, map: &mut ExampleMap) -> i32 {
    if let Some(label) = &label
        && let Some(&number) = map.get(label)
    {
        return number;
    }
    *counter += 1;
    if let Some(label) = label {
        map.insert(label, *counter);
    }
    *counter
}

fn list_info(parsed: &ListMarkerParse) -> ListInfo {
    ListInfo {
        bullet: parsed.bullet,
        marker: parsed.marker,
        style: parsed.style,
        delim: parsed.delim,
        start: parsed.start,
    }
}

/// Reread a lone roman `i`/`I` (the only roman enumerator whose start is one) as the ninth letter
/// of its alphabet. Any other list info is returned unchanged.
fn demote_lone_roman(info: ListInfo) -> ListInfo {
    let style = match info.style {
        ListNumberStyle::LowerRoman if info.start == 1 => ListNumberStyle::LowerAlpha,
        ListNumberStyle::UpperRoman if info.start == 1 => ListNumberStyle::UpperAlpha,
        _ => return info,
    };
    ListInfo {
        style,
        start: 9,
        ..info
    }
}

/// Whether `marker` reads as a continuation of an ordered list whose established style is
/// `list_style` (the delimiter is checked separately). The list's first item fixes the style; each
/// later marker is reread in that style rather than its own:
///
/// - a decimal list takes only decimal markers;
/// - an alphabetic list takes any single letter of its case (so `h. i. j.` is one list, `i` read as
///   the ninth letter);
/// - a roman list takes any roman numeral of its case, plus the single letters whose position is a
///   roman value (`a`, `e`, `j`) — the same letters a roman sequence can reach.
fn continues_ordered(list_style: ListNumberStyle, marker: &ListMarkerParse) -> bool {
    use ListNumberStyle::{Decimal, LowerAlpha, LowerRoman, UpperAlpha, UpperRoman};
    let lower = matches!(marker.style, LowerAlpha | LowerRoman);
    let upper = matches!(marker.style, UpperAlpha | UpperRoman);
    match list_style {
        Decimal => matches!(marker.style, Decimal),
        LowerAlpha => lower && marker.single_letter,
        UpperAlpha => upper && marker.single_letter,
        LowerRoman => lower && continues_roman(marker),
        UpperRoman => upper && continues_roman(marker),
        // An example list groups every example marker of the same delimiter, regardless of label.
        ListNumberStyle::Example => matches!(marker.style, ListNumberStyle::Example),
        ListNumberStyle::DefaultStyle => false,
    }
}

/// Whether `marker` reads as a roman numeral continuing a roman list: a multi-letter roman, the lone
/// roman `i`/`I`, or a single letter whose alphabet position is itself a roman digit or a roman
/// value (`a`=1, `e`=5, `j`=10).
fn continues_roman(marker: &ListMarkerParse) -> bool {
    if !marker.single_letter {
        return matches!(
            marker.style,
            ListNumberStyle::LowerRoman | ListNumberStyle::UpperRoman
        );
    }
    matches!(
        marker.style,
        ListNumberStyle::LowerRoman | ListNumberStyle::UpperRoman
    ) || matches!(marker.start, 1 | 3 | 4 | 5 | 9 | 10 | 12 | 13 | 22 | 24)
}

/// If a fence's info string is exactly an attribute block holding only a raw-format marker — a `{`,
/// optional whitespace, `=`, a format name, optional whitespace, then `}` — return that name. The
/// fence's contents are then raw output for that format. A format name is one run of letters,
/// digits, `-`, or `_`; anything else (extra attributes, a space inside the name, a stray symbol)
/// is not a raw marker and the fence stays an ordinary code block.
fn raw_block_format(info: &str) -> Option<String> {
    let inner = info.trim().strip_prefix('{')?.strip_suffix('}')?;
    // The `=` immediately precedes the name: `{= html}` (a gap after `=`) is not a raw marker,
    // while surrounding whitespace (`{ =html }`) is allowed.
    let name = inner.trim_start().strip_prefix('=')?.trim_end();
    if name.is_empty() || !name.chars().all(is_format_name_char) {
        return None;
    }
    Some(name.to_owned())
}

pub(super) fn is_format_name_char(ch: char) -> bool {
    ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_')
}

fn fence_attr(info: &str, extensions: Extensions) -> Attr {
    let info = info.trim();
    if info.is_empty() {
        return Attr::default();
    }
    // With fenced-code attributes enabled, a `{…}` info string is a full attribute block; the whole
    // info must be the block, else it falls back to the bare-language reading.
    if (extensions.contains(Extension::FencedCodeAttributes)
        || extensions.contains(Extension::Attributes))
        && info.starts_with('{')
        && let Some((parsed, consumed)) = attr::parse_attributes(info)
        && info
            .get(consumed..)
            .is_some_and(|rest| rest.trim().is_empty())
    {
        return parsed;
    }
    let language = info.split_whitespace().next().unwrap_or("");
    Attr {
        id: String::new(),
        classes: vec![language.to_owned()],
        attributes: Vec::new(),
    }
}

/// If `line` (already past any container markers and leading indent) opens a fenced div — a run of
/// three or more colons followed by a valid attribute spec — return the colon count and the parsed
/// attributes. A bare colon run with no spec is not an opener (it can only close).
fn div_open_fence(line: &str) -> Option<(usize, Attr)> {
    let after_colons = line.trim_start_matches(':');
    let count = line.len() - after_colons.len();
    if count < 3 {
        return None;
    }
    let attr = div_open_attr(after_colons.trim())?;
    Some((count, attr))
}

/// The recognized alert kinds: the marker spelling (recognized only in all-uppercase), the lowercased
/// class applied to the wrapping div, and the display title.
struct AlertType {
    class: &'static str,
    title: &'static str,
}

const ALERT_TYPES: &[(&str, AlertType)] = &[
    (
        "note",
        AlertType {
            class: "note",
            title: "Note",
        },
    ),
    (
        "tip",
        AlertType {
            class: "tip",
            title: "Tip",
        },
    ),
    (
        "important",
        AlertType {
            class: "important",
            title: "Important",
        },
    ),
    (
        "warning",
        AlertType {
            class: "warning",
            title: "Warning",
        },
    ),
    (
        "caution",
        AlertType {
            class: "caution",
            title: "Caution",
        },
    ),
];

/// If `line` is exactly an alert marker `[!TYPE]` followed by only trailing whitespace — with no
/// leading whitespace and a recognized `TYPE` — return its kind. The broad Markdown dialect
/// (`uppercase_only`) admits only the all-uppercase spelling `[!NOTE]`; the `CommonMark` engine
/// accepts any casing (`[!note]`, `[!Note]`).
fn alert_marker_type(line: &str, uppercase_only: bool) -> Option<&'static AlertType> {
    let inner = line.strip_prefix("[!")?;
    let close = inner.find(']')?;
    let name = inner.get(..close)?;
    // Only whitespace may follow the closing bracket.
    if !inner.get(close + 1..)?.chars().all(char::is_whitespace) {
        return None;
    }
    if uppercase_only && name.bytes().any(|b| b.is_ascii_lowercase()) {
        return None;
    }
    ALERT_TYPES
        .iter()
        .find(|(spelling, _)| name.eq_ignore_ascii_case(spelling))
        .map(|(_, ty)| ty)
}

/// Parse a fenced-div opener's attribute spec (the text after the colons, already trimmed). It is
/// either a single brace block of valid attributes or a single bare word taken verbatim as the sole
/// class; anything else (empty, multiple words, junk after a brace) is not a valid opener.
fn div_open_attr(spec: &str) -> Option<Attr> {
    if spec.is_empty() {
        return None;
    }
    if spec.starts_with('{')
        && let Some((attr, consumed)) = attr::parse_attributes_first_id(spec)
        && attr::is_non_empty(&attr)
        && spec
            .get(consumed..)
            .is_some_and(|rest| rest.trim().is_empty())
    {
        return Some(attr);
    }
    // Bare-word form: a single whitespace-free token becomes the sole class, kept verbatim (a
    // leading dot is not stripped).
    if spec.chars().any(char::is_whitespace) {
        return None;
    }
    Some(Attr {
        id: String::new(),
        classes: vec![spec.to_owned()],
        attributes: Vec::new(),
    })
}

/// If `line` (already past any container markers) is a closing div fence — up to three spaces of
/// indent, then a run of three or more colons, then only whitespace — return the colon count.
fn div_close_fence(line: &str) -> Option<usize> {
    let after_spaces = line.trim_start_matches(' ');
    if line.len() - after_spaces.len() > 3 {
        return None;
    }
    let after_colons = after_spaces.trim_start_matches(':');
    let count = after_spaces.len() - after_colons.len();
    if count < 3 || !after_colons.trim().is_empty() {
        return None;
    }
    Some(count)
}

fn strip_one_trailing_newline(text: &str) -> String {
    text.strip_suffix('\n').unwrap_or(text).to_owned()
}

/// A line opens or extends a line block when a `|` sits at its start, followed by a space or the
/// line's end.
fn is_line_block_marker(line: &str) -> bool {
    line == "|" || line.starts_with("| ")
}

/// Whether `text` (a node's accumulated lines, each terminated by a newline) holds exactly one
/// non-empty line.
fn single_line(text: &str) -> bool {
    let body = text.strip_suffix('\n').unwrap_or(text);
    !body.is_empty() && !body.contains('\n')
}

/// Split an accumulated table leaf's text into its physical lines, dropping the trailing empty piece
/// left by the final newline.
fn split_table_lines(text: &str) -> Vec<&str> {
    let mut lines: Vec<&str> = text.split('\n').collect();
    if lines.last() == Some(&"") {
        lines.pop();
    }
    lines
}

fn owned_lines(lines: &[&str]) -> Vec<String> {
    lines.iter().map(|line| (*line).to_owned()).collect()
}

/// The last non-blank physical line of an accumulated leaf's text, scanning back from the end so the
/// cost is the length of that line rather than the whole accumulation.
fn last_nonempty_line(text: &str) -> &str {
    text.trim_end_matches('\n')
        .rsplit('\n')
        .find(|line| !line.trim().is_empty())
        .unwrap_or("")
}

/// Whether a dash-only line is a thematic break: three or more dashes, with spaces allowed between
/// them. Used to settle a dash-ruled table candidate that turned out not to be a table.
fn is_thematic_dash_line(line: &str) -> bool {
    texttable::is_dash_line(line) && line.bytes().filter(|byte| *byte == b'-').count() >= 3
}

/// Whether a line block's current (final) entry is empty: its last line is a `|` marker carrying no
/// content. A content-bearing line stays non-empty once written, so checking the final line alone is
/// enough — an empty entry is only ever followed by another marker line, never folded into.
fn last_entry_is_empty(text: &str) -> bool {
    let last = text
        .trim_end_matches('\n')
        .rsplit('\n')
        .next()
        .unwrap_or("");
    last.strip_prefix('|')
        .is_some_and(|rest| rest.trim_matches([' ', '\t']).is_empty())
}

/// Split a line block's accumulated raw lines into prepared per-entry strings. A `|`-led line opens
/// a new entry — its `|` and one following space dropped, any remaining leading spaces kept as
/// non-breaking spaces so they survive inline parsing — while any other line continues the previous
/// entry, joined to it by a single space.
fn line_block_lines(text: &str) -> Vec<String> {
    let mut entries: Vec<String> = Vec::new();
    for raw in text.lines() {
        if let Some(rest) = raw.strip_prefix('|') {
            let rest = rest.strip_prefix(' ').unwrap_or(rest);
            // Trailing whitespace is dropped first, so an all-space entry collapses to empty
            // rather than to a run of preserved leading spaces.
            entries.push(preserve_leading_spaces(rest.trim_end_matches([' ', '\t'])));
        } else if let Some(last) = entries.last_mut() {
            last.push(' ');
            last.push_str(raw.trim());
        } else {
            entries.push(raw.trim().to_owned());
        }
    }
    // A whitespace-only continuation folds nothing into its entry but leaves a dangling separator
    // space; drop any such trailing run, leaving preserved leading spaces untouched.
    for entry in &mut entries {
        let kept = entry.trim_end_matches([' ', '\t']).len();
        entry.truncate(kept);
    }
    entries
}

/// Replace a run of leading ASCII spaces with non-breaking spaces.
fn preserve_leading_spaces(s: &str) -> String {
    let trimmed = s.trim_start_matches(' ');
    let spaces = s.len() - trimmed.len();
    let mut out = String::with_capacity(s.len() + spaces);
    for _ in 0..spaces {
        out.push('\u{a0}');
    }
    out.push_str(trimmed);
    out
}

/// Drop trailing whitespace-only lines (and the final line ending), keeping interior blank lines.
fn strip_trailing_blank_lines(text: &str) -> String {
    let mut lines: Vec<&str> = text.split('\n').collect();
    while lines.last().is_some_and(|line| line.trim().is_empty()) {
        lines.pop();
    }
    lines.join("\n")
}

/// Trim an ATX heading's content: drop surrounding spaces/tabs and an optional closing run of `#`
/// (which must be preceded by whitespace or form the whole line, else it belongs to the content).
fn strip_atx_closing(content: &str, require_preceding_space: bool) -> String {
    let trimmed = content.trim_matches([' ', '\t']);
    let without_hashes = trimmed.trim_end_matches('#');
    if without_hashes.len() == trimmed.len() {
        return trimmed.to_owned();
    }
    // A closing hash run always terminates the heading when the dialect does not require a space
    // after the opener; otherwise the run must be set off from the content by whitespace.
    if !require_preceding_space
        || without_hashes.is_empty()
        || without_hashes.ends_with([' ', '\t'])
    {
        without_hashes.trim_end_matches([' ', '\t']).to_owned()
    } else {
        trimmed.to_owned()
    }
}

/// Recognition of block-level HTML elements whose inner content is parsed as markdown: scanning an
/// open tag (name, attributes, extent) and locating its matching close tag. Pure functions over the
/// raw line text.
mod html_element {
    use carta_ast::Attr;

    /// A recognized open tag at the start of a line.
    pub(super) struct OpenTag {
        /// The lowercased tag name.
        pub(super) tag: String,
        /// Attributes parsed from the tag (`id`, `class`, and other key/values).
        pub(super) attr: Attr,
        /// Byte length of the whole tag, up to and including the closing `>`.
        pub(super) len: usize,
        /// Whether the tag closes itself (`<div/>`), so it opens no element to balance.
        pub(super) self_closing: bool,
    }

    /// A located close tag within a line.
    pub(super) struct CloseTag {
        /// Byte offset where `</` begins.
        pub(super) start: usize,
        /// Byte offset just past the closing `>`.
        pub(super) end: usize,
    }

    /// Block-level tag names whose elements carry parsed markdown content. Inline tags (`em`, `span`,
    /// `a`, …) and unrecognized names are left for the inline phase as raw HTML.
    const BLOCK_TAGS: &[&str] = &[
        "address",
        "article",
        "aside",
        "base",
        "basefont",
        "blockquote",
        "body",
        "caption",
        "center",
        "col",
        "colgroup",
        "dd",
        "details",
        "dialog",
        "dir",
        "div",
        "dl",
        "dt",
        "fieldset",
        "figcaption",
        "figure",
        "footer",
        "form",
        "frame",
        "frameset",
        "h1",
        "h2",
        "h3",
        "h4",
        "h5",
        "h6",
        "head",
        "header",
        "hr",
        "html",
        "iframe",
        "legend",
        "li",
        "link",
        "main",
        "menu",
        "menuitem",
        "nav",
        "noframes",
        "ol",
        "optgroup",
        "option",
        "p",
        "param",
        "search",
        "section",
        "summary",
        "table",
        "tbody",
        "td",
        "tfoot",
        "th",
        "thead",
        "title",
        "tr",
        "track",
        "ul",
    ];

    fn is_block_tag(name: &str) -> bool {
        BLOCK_TAGS.contains(&name)
    }

    /// If `s` begins with a recognized block-level HTML open tag, return its name, attributes, and
    /// byte extent. A self-closing tag (`<div/>`) parses as an ordinary open tag here.
    pub(super) fn parse_open_tag(s: &str) -> Option<OpenTag> {
        let bytes = s.as_bytes();
        if bytes.first() != Some(&b'<') {
            return None;
        }
        let mut i = 1;
        let name_start = i;
        if !bytes.get(i).is_some_and(u8::is_ascii_alphabetic) {
            return None;
        }
        i += 1;
        while bytes
            .get(i)
            .is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'-')
        {
            i += 1;
        }
        let name = s.get(name_start..i)?.to_ascii_lowercase();
        if !is_block_tag(&name) {
            return None;
        }
        let mut attr = Attr::default();
        loop {
            let after_ws = skip_ws(bytes, i);
            // A `>` (optionally preceded by a self-closing `/`) ends the tag.
            let self_closing = bytes.get(after_ws) == Some(&b'/');
            let close = if self_closing { after_ws + 1 } else { after_ws };
            if bytes.get(close) == Some(&b'>') {
                return Some(OpenTag {
                    tag: name,
                    attr,
                    len: close + 1,
                    self_closing,
                });
            }
            // An attribute must be separated from the name (or a previous attribute) by whitespace.
            if after_ws == i {
                return None;
            }
            i = read_attribute(bytes, after_ws, &mut attr)?;
        }
    }

    /// Read one `name[=value]` attribute starting at `start`, folding it into `attr`, and return the
    /// index just past it. `id` sets the identifier, `class` adds whitespace-separated classes (the
    /// first `class` wins), and any other name becomes a key/value pair in source order.
    fn read_attribute(bytes: &[u8], start: usize, attr: &mut Attr) -> Option<usize> {
        let mut i = start;
        let name_start = i;
        if !bytes
            .get(i)
            .is_some_and(|b| b.is_ascii_alphabetic() || matches!(b, b'_' | b':'))
        {
            return None;
        }
        i += 1;
        while bytes
            .get(i)
            .is_some_and(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b':' | b'-'))
        {
            i += 1;
        }
        let name = ascii_lower(bytes.get(name_start..i)?);
        let probe = skip_ws(bytes, i);
        let mut value = String::new();
        let mut end = i;
        if bytes.get(probe) == Some(&b'=') {
            let (val, next) = read_value(bytes, probe + 1)?;
            value = val;
            end = next;
        }
        match name.as_str() {
            "id" => attr.id = value,
            "class" => {
                if attr.classes.is_empty() {
                    attr.classes = value.split_whitespace().map(str::to_owned).collect();
                }
            }
            _ => attr.attributes.push((name, value)),
        }
        Some(end)
    }

    /// Read an attribute value (quoted or bare) starting at `start`, returning it and the index just
    /// past it. A started-but-unterminated value is malformed.
    fn read_value(bytes: &[u8], start: usize) -> Option<(String, usize)> {
        let i = skip_ws(bytes, start);
        match bytes.get(i) {
            Some(quote @ (b'"' | b'\'')) => {
                let quote = *quote;
                let value_start = i + 1;
                let mut j = value_start;
                while bytes.get(j).is_some_and(|b| *b != quote) {
                    j += 1;
                }
                if bytes.get(j) != Some(&quote) {
                    return None;
                }
                Some((bytes_to_string(bytes.get(value_start..j)?), j + 1))
            }
            Some(_) => {
                let value_start = i;
                let mut j = i;
                while bytes.get(j).is_some_and(|b| {
                    !matches!(b, b' ' | b'\t' | b'"' | b'\'' | b'=' | b'<' | b'>' | b'`')
                }) {
                    j += 1;
                }
                if j == value_start {
                    return None;
                }
                Some((bytes_to_string(bytes.get(value_start..j)?), j))
            }
            None => None,
        }
    }

    /// Locate the first matching close tag `</name>` (with optional trailing whitespace before `>`)
    /// in `s`, returning its byte range. The name match is case-insensitive.
    pub(super) fn find_close_tag(s: &str, tag: &str) -> Option<CloseTag> {
        let bytes = s.as_bytes();
        let mut i = 0;
        while i < bytes.len() {
            if bytes.get(i) == Some(&b'<')
                && bytes.get(i + 1) == Some(&b'/')
                && let Some(end) = close_tag_at(bytes, i, tag)
            {
                return Some(CloseTag { start: i, end });
            }
            i += 1;
        }
        None
    }

    /// If a close tag for `tag` begins at `start`, return the index just past its `>`.
    fn close_tag_at(bytes: &[u8], start: usize, tag: &str) -> Option<usize> {
        let name_start = start + 2;
        let mut i = name_start;
        while bytes
            .get(i)
            .is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'-')
        {
            i += 1;
        }
        let name = ascii_lower(bytes.get(name_start..i)?);
        if name != tag {
            return None;
        }
        i = skip_ws(bytes, i);
        (bytes.get(i) == Some(&b'>')).then_some(i + 1)
    }

    /// If `s` begins with a block-level close tag (`</div>`, optional whitespace before `>`), return
    /// its byte length. A bare close tag at a line start stands alone as a raw block.
    pub(super) fn parse_close_tag(s: &str) -> Option<usize> {
        let bytes = s.as_bytes();
        if bytes.first() != Some(&b'<') || bytes.get(1) != Some(&b'/') {
            return None;
        }
        let name_start = 2;
        let mut i = name_start;
        while bytes
            .get(i)
            .is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'-')
        {
            i += 1;
        }
        let name = s.get(name_start..i)?.to_ascii_lowercase();
        if !is_block_tag(&name) {
            return None;
        }
        i = skip_ws(bytes, i);
        (bytes.get(i) == Some(&b'>')).then_some(i + 1)
    }

    /// Walk `s` from the given open-nesting `depth`, tracking only tags named `tag`: each non-self-
    /// closing open raises the depth, each close lowers it, and any other tag is skipped whole so a
    /// `>` inside its attributes cannot be miscounted. Returns the depth after `s` and, when a close
    /// brings the depth to zero within `s`, the byte offset just past that close tag.
    pub(super) fn scan_depth(s: &str, tag: &str, mut depth: usize) -> (usize, Option<usize>) {
        let bytes = s.as_bytes();
        let mut i = 0;
        while i < bytes.len() {
            if bytes.get(i) == Some(&b'<') {
                if let Some(open) = parse_open_tag(s.get(i..).unwrap_or("")) {
                    if open.tag == tag && !open.self_closing {
                        depth += 1;
                    }
                    i += open.len;
                    continue;
                }
                if let Some(end) = close_tag_at(bytes, i, tag) {
                    depth = depth.saturating_sub(1);
                    if depth == 0 {
                        return (0, Some(end));
                    }
                    i = end;
                    continue;
                }
            }
            i += 1;
        }
        (depth, None)
    }

    fn skip_ws(bytes: &[u8], mut i: usize) -> usize {
        while bytes.get(i).is_some_and(|b| matches!(b, b' ' | b'\t')) {
            i += 1;
        }
        i
    }

    fn ascii_lower(bytes: &[u8]) -> String {
        bytes_to_string(bytes).to_ascii_lowercase()
    }

    fn bytes_to_string(bytes: &[u8]) -> String {
        String::from_utf8_lossy(bytes).into_owned()
    }
}

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

    #[test]
    fn recognizes_the_three_caption_markers() {
        assert_eq!(strip_caption_marker("Table: A caption"), Some("A caption"));
        assert_eq!(strip_caption_marker("table: A caption"), Some("A caption"));
        assert_eq!(strip_caption_marker(": A caption"), Some("A caption"));
    }

    #[test]
    fn drops_the_spaces_after_the_marker() {
        assert_eq!(strip_caption_marker("Table:caption"), Some("caption"));
        assert_eq!(strip_caption_marker("Table:    caption"), Some("caption"));
        assert_eq!(strip_caption_marker(":caption"), Some("caption"));
    }

    #[test]
    fn only_the_first_letter_may_vary_in_case() {
        assert_eq!(strip_caption_marker("TABLE: x"), None);
        assert_eq!(strip_caption_marker("TAble: x"), None);
        assert_eq!(strip_caption_marker("tABLE: x"), None);
    }

    #[test]
    fn a_space_before_the_colon_is_not_a_marker() {
        assert_eq!(strip_caption_marker("Table : x"), None);
        assert_eq!(strip_caption_marker("table : x"), None);
    }

    #[test]
    fn a_line_without_a_marker_is_rejected() {
        assert_eq!(strip_caption_marker("Just a paragraph"), None);
        assert_eq!(strip_caption_marker("Tablexyz"), None);
    }

    use super::raw_block_format;

    #[test]
    fn plain_raw_format_marker_is_recognized() {
        assert_eq!(raw_block_format("{=html}"), Some("html".to_owned()));
        assert_eq!(raw_block_format("{=latex}"), Some("latex".to_owned()));
        assert_eq!(raw_block_format("{=html-foo}"), Some("html-foo".to_owned()));
        assert_eq!(raw_block_format("{=html_foo}"), Some("html_foo".to_owned()));
        assert_eq!(raw_block_format("{=html5}"), Some("html5".to_owned()));
    }

    #[test]
    fn whitespace_around_the_marker_is_tolerated() {
        assert_eq!(raw_block_format("{ =html}"), Some("html".to_owned()));
        assert_eq!(raw_block_format("{=html }"), Some("html".to_owned()));
        assert_eq!(raw_block_format("  {=html}  "), Some("html".to_owned()));
    }

    #[test]
    fn a_gap_after_the_equals_is_not_a_marker() {
        assert_eq!(raw_block_format("{= html}"), None);
    }

    #[test]
    fn extra_attributes_or_an_empty_format_are_not_markers() {
        assert_eq!(raw_block_format("{=html .foo}"), None);
        assert_eq!(raw_block_format("{=html foo}"), None);
        assert_eq!(raw_block_format("{=}"), None);
        assert_eq!(raw_block_format("{}"), None);
    }

    #[test]
    fn a_symbol_in_the_format_name_is_not_a_marker() {
        assert_eq!(raw_block_format("{=ht.ml}"), None);
        assert_eq!(raw_block_format("{=ht/ml}"), None);
        assert_eq!(raw_block_format("{=ht+ml}"), None);
        assert_eq!(raw_block_format("{=ht:ml}"), None);
    }

    #[test]
    fn an_ordinary_info_string_is_not_a_marker() {
        assert_eq!(raw_block_format("html"), None);
        assert_eq!(raw_block_format("=html"), None);
        assert_eq!(raw_block_format("{.html}"), None);
    }

    use super::{IrBlock, is_math_environment, parse, raw_tex_env_name, raw_tex_scan};
    use carta_ast::Format;
    use carta_core::presets;

    fn blocks(input: &str) -> Vec<IrBlock> {
        parse(input, presets::MARKDOWN, true).0
    }

    #[test]
    fn reads_the_begin_environment_name() {
        assert_eq!(
            raw_tex_env_name("\\begin{center}", b"begin").as_deref(),
            Some("center")
        );
        assert_eq!(
            raw_tex_env_name("\\begin {center}", b"begin").as_deref(),
            Some("center")
        );
        assert_eq!(
            raw_tex_env_name("\\end{a}rest", b"end").as_deref(),
            Some("a")
        );
        assert_eq!(
            raw_tex_env_name("\\begin{ a }", b"begin").as_deref(),
            Some(" a ")
        );
        assert_eq!(raw_tex_env_name("\\begin{}", b"begin").as_deref(), Some(""));
        // A bare word, a missing brace, or the wrong keyword is not a match.
        assert_eq!(raw_tex_env_name("\\beginabc", b"begin"), None);
        assert_eq!(raw_tex_env_name("\\begin center", b"begin"), None);
        assert_eq!(raw_tex_env_name("begin{a}", b"begin"), None);
    }

    #[test]
    fn math_environments_are_excluded() {
        assert!(is_math_environment("equation"));
        assert!(is_math_environment("align*"));
        assert!(is_math_environment("math"));
        assert!(is_math_environment("dmath"));
        assert!(!is_math_environment("center"));
        assert!(!is_math_environment("align**"));
        assert!(!is_math_environment("xalignat"));
        assert!(!is_math_environment("Equation"));
    }

    #[test]
    fn scan_tracks_depth_and_finds_the_close() {
        // The opener line alone opens at depth one and does not close.
        assert_eq!(raw_tex_scan("\\begin{a}", "a", 0), (1, None));
        // A matching end on a content line returns the offset past its brace.
        let (depth, close) = raw_tex_scan("\\end{a}rest", "a", 1);
        assert_eq!(depth, 0);
        assert_eq!(close, Some("\\end{a}".len()));
        // An unrelated end name is content, not a close.
        assert_eq!(raw_tex_scan("\\end{c}", "a", 1), (1, None));
        // Same-name nesting deepens and lifts the count.
        assert_eq!(raw_tex_scan("\\begin{a}\\end{a}", "a", 1), (1, None));
        // An escaped command does not count toward the depth.
        assert_eq!(raw_tex_scan("\\\\end{a}", "a", 1), (1, None));
    }

    #[test]
    fn a_full_environment_becomes_a_raw_tex_block() {
        let out = blocks("\\begin{center}\nx\n\\end{center}\nafter\n");
        assert!(matches!(
            out.first(),
            Some(IrBlock::RawBlock(Format(fmt), body))
                if fmt == "tex" && body == "\\begin{center}\nx\n\\end{center}"
        ));
        assert!(matches!(out.get(1), Some(IrBlock::Para(p)) if p == "after"));
    }

    #[test]
    fn a_single_line_environment_closes_on_its_own_line() {
        let out = blocks("\\begin{center}x\\end{center}\ny\n");
        assert!(matches!(
            out.first(),
            Some(IrBlock::RawBlock(Format(fmt), body))
                if fmt == "tex" && body == "\\begin{center}x\\end{center}"
        ));
        assert!(matches!(out.get(1), Some(IrBlock::Para(p)) if p == "y"));
    }

    #[test]
    fn an_unclosed_environment_falls_back_to_a_paragraph() {
        let out = blocks("\\begin{center}\nx\ny\n");
        assert_eq!(out.len(), 1);
        assert!(matches!(out.first(), Some(IrBlock::Para(_))));
    }

    #[test]
    fn a_math_environment_stays_out_of_a_raw_block() {
        // An \begin opening a math environment is not a block-level raw TeX environment.
        let out = blocks("\\begin{align}\nx\n\\end{align}\n");
        assert!(!matches!(out.first(), Some(IrBlock::RawBlock(..))));
    }

    #[test]
    fn an_indented_begin_is_a_code_block() {
        let out = blocks("    \\begin{center}\n    x\n    \\end{center}\n");
        assert!(matches!(out.first(), Some(IrBlock::CodeBlock(..))));
    }

    #[test]
    fn the_extension_off_leaves_the_syntax_literal() {
        let out = parse(
            "\\begin{center}\nx\n\\end{center}\n",
            presets::COMMONMARK,
            false,
        )
        .0;
        assert_eq!(out.len(), 1);
        assert!(matches!(out.first(), Some(IrBlock::Para(_))));
    }

    use super::alert_marker_type;

    fn gfm_blocks(input: &str) -> Vec<IrBlock> {
        parse(input, presets::GFM, false).0
    }

    #[test]
    fn alert_marker_recognizes_every_kind() {
        assert_eq!(
            alert_marker_type("[!NOTE]", true).map(|t| t.class),
            Some("note")
        );
        assert_eq!(
            alert_marker_type("[!TIP]", true).map(|t| t.class),
            Some("tip")
        );
        assert_eq!(
            alert_marker_type("[!IMPORTANT]", true).map(|t| t.class),
            Some("important")
        );
        assert_eq!(
            alert_marker_type("[!WARNING]", true).map(|t| t.class),
            Some("warning")
        );
        assert_eq!(
            alert_marker_type("[!CAUTION]", true).map(|t| t.title),
            Some("Caution")
        );
    }

    #[test]
    fn alert_marker_casing_depends_on_the_dialect() {
        // The broad Markdown dialect admits only the uppercase spelling.
        assert!(alert_marker_type("[!note]", true).is_none());
        assert!(alert_marker_type("[!Tip]", true).is_none());
        assert!(alert_marker_type("[!wArNiNg]", true).is_none());
        // The CommonMark engine accepts any casing.
        assert_eq!(
            alert_marker_type("[!note]", false).map(|t| t.class),
            Some("note")
        );
        assert_eq!(
            alert_marker_type("[!Tip]", false).map(|t| t.class),
            Some("tip")
        );
    }

    #[test]
    fn alert_marker_allows_only_trailing_whitespace() {
        assert!(alert_marker_type("[!NOTE]", true).is_some());
        assert!(alert_marker_type("[!NOTE]   ", true).is_some());
        assert!(alert_marker_type("[!NOTE]\t", true).is_some());
        // Anything other than whitespace after the bracket disqualifies the marker.
        assert!(alert_marker_type("[!NOTE] hi", true).is_none());
        assert!(alert_marker_type("[!NOTE]x", true).is_none());
    }

    #[test]
    fn alert_marker_rejects_unknown_or_malformed_markers() {
        assert!(alert_marker_type("[!FOO]", true).is_none());
        assert!(alert_marker_type("[!]", true).is_none());
        assert!(alert_marker_type("[NOTE]", true).is_none());
        assert!(alert_marker_type(" [!NOTE]", true).is_none());
        assert!(alert_marker_type("[!NOTE", true).is_none());
    }

    #[test]
    fn an_alert_blockquote_becomes_a_titled_div() {
        let out = gfm_blocks("> [!NOTE]\n> This is a note.\n");
        let Some(IrBlock::Div(attr, content)) = out.first() else {
            panic!("expected a div, got {out:?}");
        };
        assert_eq!(attr.classes, vec!["note".to_owned()]);
        let Some(IrBlock::Div(title_attr, title)) = content.first() else {
            panic!("expected a title div");
        };
        assert_eq!(title_attr.classes, vec!["title".to_owned()]);
        assert!(matches!(title.as_slice(), [IrBlock::Para(t)] if t == "Note"));
        assert!(matches!(content.get(1), Some(IrBlock::Para(t)) if t == "This is a note."));
    }

    #[test]
    fn a_marker_only_alert_carries_just_its_title() {
        let out = gfm_blocks("> [!TIP]\n");
        let Some(IrBlock::Div(attr, content)) = out.first() else {
            panic!("expected a div");
        };
        assert_eq!(attr.classes, vec!["tip".to_owned()]);
        assert_eq!(content.len(), 1);
        assert!(matches!(content.first(), Some(IrBlock::Div(..))));
    }

    #[test]
    fn an_alert_preserves_richer_body_content() {
        let out = gfm_blocks("> [!WARNING]\n> # Heading\n");
        let Some(IrBlock::Div(_, content)) = out.first() else {
            panic!("expected a div");
        };
        assert!(matches!(content.get(1), Some(IrBlock::Heading(1, _))));
    }

    #[test]
    fn an_unknown_marker_leaves_the_blockquote_intact() {
        let out = gfm_blocks("> [!FOO]\n> x\n");
        assert!(matches!(out.first(), Some(IrBlock::BlockQuote(_))));
    }

    #[test]
    fn trailing_text_on_the_marker_line_leaves_the_blockquote_intact() {
        let out = gfm_blocks("> [!NOTE] hello\n> x\n");
        assert!(matches!(out.first(), Some(IrBlock::BlockQuote(_))));
    }

    #[test]
    fn alerts_off_leaves_the_marker_literal() {
        let out = parse("> [!NOTE]\n> x\n", presets::COMMONMARK, true).0;
        assert!(matches!(out.first(), Some(IrBlock::BlockQuote(_))));
    }

    use super::split_trailing_attr;

    fn table_attr_and_caption(input: &str) -> (carta_ast::Attr, Option<String>) {
        let out = blocks(input);
        match out.into_iter().next() {
            Some(IrBlock::Table { attr, caption, .. }) => (attr, caption),
            Some(IrBlock::TextTable(table)) => (table.attr, table.caption),
            Some(IrBlock::GridTable(table)) => (table.attr, table.caption),
            other => panic!("expected a table, got {other:?}"),
        }
    }

    #[test]
    fn split_trailing_attr_strips_the_block() {
        let (body, attr) = split_trailing_attr("My cap {#t .w}");
        assert_eq!(body, "My cap");
        let attr = attr.expect("attr parsed");
        assert_eq!(attr.id, "t");
        assert_eq!(attr.classes, ["w"]);
    }

    #[test]
    fn split_trailing_attr_keeps_non_trailing_braces_literal() {
        // Only the last block at the very end is an attribute block.
        let (body, attr) = split_trailing_attr("Cap {#x} {#y}");
        assert_eq!(body, "Cap {#x}");
        assert_eq!(attr.expect("attr parsed").id, "y");
        // A block followed by more text is not trailing and stays untouched.
        assert_eq!(
            split_trailing_attr("Cap {#x} more"),
            ("Cap {#x} more", None)
        );
    }

    #[test]
    fn split_trailing_attr_rejects_malformed_blocks() {
        assert_eq!(split_trailing_attr("Cap {#x").0, "Cap {#x");
        assert!(split_trailing_attr("Cap {#x").1.is_none());
        assert_eq!(split_trailing_attr("Cap {bad !!}").0, "Cap {bad !!}");
        assert!(split_trailing_attr("Cap {bad !!}").1.is_none());
        assert_eq!(split_trailing_attr("plain text").0, "plain text");
    }

    #[test]
    fn caption_attributes_attach_to_the_table() {
        let (attr, caption) = table_attr_and_caption("| a |\n|---|\n| 1 |\n\n: My cap {#t .w}\n");
        assert_eq!(attr.id, "t");
        assert_eq!(attr.classes, ["w"]);
        assert_eq!(caption.as_deref(), Some("My cap"));
    }

    #[test]
    fn caption_keyvals_attach_to_the_table() {
        let (attr, _) = table_attr_and_caption("| a |\n|---|\n| 1 |\n\n: c {key=val}\n");
        assert_eq!(attr.attributes, [("key".to_owned(), "val".to_owned())]);
    }

    #[test]
    fn caption_without_a_block_leaves_attr_empty() {
        let (attr, caption) = table_attr_and_caption("| a |\n|---|\n| 1 |\n\n: just a caption\n");
        assert!(attr.id.is_empty() && attr.classes.is_empty() && attr.attributes.is_empty());
        assert_eq!(caption.as_deref(), Some("just a caption"));
    }

    #[test]
    fn caption_attributes_are_inert_without_the_extension() {
        // With table attributes disabled, the trailing block on a caption is kept verbatim as
        // caption text rather than split off onto the table's attributes.
        let mut table = blocks("| a |\n|---|\n| 1 |\n");
        assert!(super::set_table_caption(
            &mut table,
            0,
            "c {#t}",
            presets::COMMONMARK
        ));
        let (attr, caption) = match table.into_iter().next() {
            Some(IrBlock::Table { attr, caption, .. }) => (attr, caption),
            Some(IrBlock::TextTable(t)) => (t.attr, t.caption),
            other => panic!("expected a table, got {other:?}"),
        };
        assert!(attr.id.is_empty());
        assert_eq!(caption.as_deref(), Some("c {#t}"));
    }
}

#[cfg(test)]
mod html_element_tests {
    use super::{IrBlock, html_element, parse};
    use carta_core::{Extension, Extensions, presets};

    fn md(input: &str) -> Vec<IrBlock> {
        parse(input, presets::MARKDOWN, true).0
    }

    fn with(input: &str, exts: &[Extension]) -> Vec<IrBlock> {
        parse(input, Extensions::from_list(exts), true).0
    }

    #[test]
    fn div_becomes_a_div_with_parsed_attributes_and_content() {
        let out = md("<div class=\"n\" id=\"d\">\n\n*hi* there\n\n</div>\n");
        let [IrBlock::Div(attr, content)] = out.as_slice() else {
            panic!("expected one div, got {out:?}");
        };
        assert_eq!(attr.id, "d");
        assert_eq!(attr.classes, vec!["n".to_owned()]);
        assert!(attr.attributes.is_empty());
        assert!(matches!(content.as_slice(), [IrBlock::Para(_)]));
    }

    #[test]
    fn div_attributes_split_class_keep_id_and_preserve_keyval_order() {
        let out = md("<div data-z=\"1\" id=\"i\" data-a=\"2\" class=\"a b\">\n\nx\n\n</div>\n");
        let [IrBlock::Div(attr, _)] = out.as_slice() else {
            panic!("expected one div, got {out:?}");
        };
        assert_eq!(attr.id, "i");
        assert_eq!(attr.classes, vec!["a".to_owned(), "b".to_owned()]);
        assert_eq!(
            attr.attributes,
            vec![
                ("data-z".to_owned(), "1".to_owned()),
                ("data-a".to_owned(), "2".to_owned()),
            ]
        );
    }

    #[test]
    fn nested_divs_balance_into_a_tree() {
        let out =
            md("<div class=\"outer\">\n\n<div class=\"inner\">\n\ntext\n\n</div>\n\n</div>\n");
        let [IrBlock::Div(outer, outer_children)] = out.as_slice() else {
            panic!("expected one outer div, got {out:?}");
        };
        assert_eq!(outer.classes, vec!["outer".to_owned()]);
        let [IrBlock::Div(inner, inner_children)] = outer_children.as_slice() else {
            panic!("expected one inner div, got {outer_children:?}");
        };
        assert_eq!(inner.classes, vec!["inner".to_owned()]);
        assert!(matches!(inner_children.as_slice(), [IrBlock::Para(_)]));
    }

    #[test]
    fn div_final_block_tightens_only_when_the_close_tag_trails_content() {
        // Close tag on its own line keeps the final block as `Para`, even without blank lines.
        let para = md("<div>\nfoo\n</div>\n");
        assert!(matches!(
            para.as_slice(),
            [IrBlock::Div(_, c)] if matches!(c.as_slice(), [IrBlock::Para(_)])
        ));
        // Close tag trailing content on the same line tightens the final block to `Plain`.
        let plain = md("<div>\nfoo\nbar</div>\n");
        assert!(matches!(
            plain.as_slice(),
            [IrBlock::Div(_, c)] if matches!(c.as_slice(), [IrBlock::Plain(_)])
        ));
        // An earlier block stays `Para`; only the trailing one tightens.
        let mixed = md("<div>\n\nfoo\n\nbar</div>\n");
        let [IrBlock::Div(_, content)] = mixed.as_slice() else {
            panic!("expected one div, got {mixed:?}");
        };
        assert!(matches!(
            content.as_slice(),
            [IrBlock::Para(_), IrBlock::Plain(_)]
        ));
    }

    #[test]
    fn multibyte_attribute_values_do_not_leak_into_following_content() {
        // The open tag is consumed by byte length, so a multibyte character in an attribute value
        // leaves no stray bytes (e.g. the trailing `>`) to be re-read as a spurious block.
        let out = md("<div class=\"café\">\n\nx\n\n</div>\n");
        let [IrBlock::Div(attr, content)] = out.as_slice() else {
            panic!("expected one div, got {out:?}");
        };
        assert_eq!(attr.classes, vec!["café".to_owned()]);
        assert!(matches!(content.as_slice(), [IrBlock::Para(_)]));
    }

    #[test]
    fn content_after_the_close_tag_is_a_following_block() {
        let out = md("<div>\nfoo\n</div>more\n");
        assert!(matches!(
            out.as_slice(),
            [IrBlock::Div(..), IrBlock::Para(_)]
        ));
    }

    #[test]
    fn raw_html_block_trailing_newline_depends_on_dialect() {
        // A raw HTML block (here a verbatim `<pre>`) keeps its final newline in the strict dialect
        // and drops it in the markdown dialect.
        let input = "<pre>\nhi\n</pre>\n";
        let strict = parse(input, presets::COMMONMARK, false).0;
        let [IrBlock::RawHtml(text)] = strict.as_slice() else {
            panic!("expected one raw HTML block, got {strict:?}");
        };
        assert_eq!(text, "<pre>\nhi\n</pre>\n");

        let markdown = parse(input, presets::COMMONMARK, true).0;
        let [IrBlock::RawHtml(text)] = markdown.as_slice() else {
            panic!("expected one raw HTML block, got {markdown:?}");
        };
        assert_eq!(text, "<pre>\nhi\n</pre>");
    }

    #[test]
    fn non_div_block_tag_keeps_raw_tags_around_parsed_content() {
        let out = md("<section class=\"n\">\n\n*hi*\n\n</section>\n");
        let [
            IrBlock::RawHtml(open),
            IrBlock::Para(_),
            IrBlock::RawHtml(close),
        ] = out.as_slice()
        else {
            panic!("expected raw-open, para, raw-close; got {out:?}");
        };
        assert_eq!(open, "<section class=\"n\">");
        assert_eq!(close, "</section>");
    }

    #[test]
    fn raw_element_final_block_tightens_when_no_blank_precedes_the_close() {
        // No blank line before the close tag: the final block is `Plain`.
        let tight = md("<section>\nfoo\n</section>\n");
        assert!(matches!(
            tight.as_slice(),
            [IrBlock::RawHtml(_), IrBlock::Plain(_), IrBlock::RawHtml(_)]
        ));
        // A blank line before the close tag keeps the final block `Para`.
        let loose = md("<section>\nfoo\n\n</section>\n");
        assert!(matches!(
            loose.as_slice(),
            [IrBlock::RawHtml(_), IrBlock::Para(_), IrBlock::RawHtml(_)]
        ));
    }

    #[test]
    fn native_divs_off_renders_a_div_as_a_raw_element() {
        let out = with(
            "<div class=\"n\">\n*hi*\n</div>\n",
            &[Extension::MarkdownInHtmlBlocks],
        );
        let [
            IrBlock::RawHtml(open),
            IrBlock::Plain(_),
            IrBlock::RawHtml(close),
        ] = out.as_slice()
        else {
            panic!("expected raw div fallback, got {out:?}");
        };
        assert_eq!(open, "<div class=\"n\">");
        assert_eq!(close, "</div>");
    }

    #[test]
    fn both_extensions_off_spans_a_block_element_to_its_balanced_close() {
        // With neither extension, a block-level tag at the left margin is kept verbatim as one raw
        // block spanning to its balanced close — blank lines included — rather than parsed as a div.
        let out = with("<div>\n\nfoo\n\n</div>\n", &[]);
        let [IrBlock::RawHtml(html)] = out.as_slice() else {
            panic!("expected one raw HTML block, got {out:?}");
        };
        assert_eq!(html, "<div>\n\nfoo\n\n</div>");
    }

    #[test]
    fn inline_and_unknown_tags_are_not_block_elements() {
        // `<em>`/`<span>` are inline and `<custom>` is unrecognized: none open a block element, so
        // none produce a div.
        for input in ["<em>\n\nx\n\n</em>\n", "<custom>\n\nx\n\n</custom>\n"] {
            let out = md(input);
            assert!(
                !out.iter().any(|b| matches!(b, IrBlock::Div(..))),
                "{input:?} should not produce a div, got {out:?}"
            );
        }
    }

    #[test]
    fn an_unclosed_element_closes_at_end_of_input_without_a_close_tag() {
        let out = md("<div>\n\nfoo\n");
        let [IrBlock::Div(_, content)] = out.as_slice() else {
            panic!("expected one div, got {out:?}");
        };
        assert!(matches!(content.as_slice(), [IrBlock::Para(_)]));
        // A raw element left open emits no trailing close tag.
        let raw = md("<section>\n\nfoo\n");
        assert!(
            !raw.iter()
                .any(|b| matches!(b, IrBlock::RawHtml(t) if t.contains("</section>"))),
            "an unclosed raw element should emit no close tag, got {raw:?}"
        );
    }

    #[test]
    fn parse_open_tag_reads_name_attributes_and_extent() {
        let tag = html_element::parse_open_tag("<div id=\"x\" class=\"a b\" data-k=v>rest")
            .expect("a div open tag");
        assert_eq!(tag.tag, "div");
        assert_eq!(tag.attr.id, "x");
        assert_eq!(tag.attr.classes, vec!["a".to_owned(), "b".to_owned()]);
        assert_eq!(
            tag.attr.attributes,
            vec![("data-k".to_owned(), "v".to_owned())]
        );
        // The extent stops just past the `>`, leaving any same-line remainder.
        assert_eq!(tag.len, "<div id=\"x\" class=\"a b\" data-k=v>".len());
    }

    #[test]
    fn parse_open_tag_rejects_non_block_and_malformed_tags() {
        assert!(html_element::parse_open_tag("<em>").is_none());
        assert!(html_element::parse_open_tag("<custom>").is_none());
        assert!(html_element::parse_open_tag("not a tag").is_none());
        assert!(html_element::parse_open_tag("<div class=\"oops>").is_none());
    }

    #[test]
    fn parse_open_tag_keeps_only_the_first_class_attribute() {
        let tag = html_element::parse_open_tag("<div class=\"a\" class=\"b\">").expect("a div");
        assert_eq!(tag.attr.classes, vec!["a".to_owned()]);
    }

    #[test]
    fn parse_open_tag_records_a_valueless_attribute_as_an_empty_value() {
        let tag = html_element::parse_open_tag("<div hidden class=\"a\">").expect("a div");
        assert_eq!(tag.attr.classes, vec!["a".to_owned()]);
        assert_eq!(
            tag.attr.attributes,
            vec![("hidden".to_owned(), String::new())]
        );
    }

    #[test]
    fn find_close_tag_locates_the_matching_name_and_skips_unrelated_ones() {
        let found = html_element::find_close_tag("foo</div>bar", "div").expect("a close tag");
        assert_eq!(&"foo</div>bar"[found.start..found.end], "</div>");
        // A different name is not the match.
        assert!(html_element::find_close_tag("</span>", "div").is_none());
        // Trailing whitespace before `>` is allowed; a bare name is not a close tag.
        assert!(html_element::find_close_tag("</div >", "div").is_some());
        assert!(html_element::find_close_tag("no tag here", "div").is_none());
    }

    #[test]
    fn parse_open_tag_flags_a_self_closing_tag() {
        assert!(
            html_element::parse_open_tag("<div/>")
                .expect("a div")
                .self_closing
        );
        assert!(
            html_element::parse_open_tag("<hr />")
                .expect("an hr")
                .self_closing
        );
        assert!(
            !html_element::parse_open_tag("<div>")
                .expect("a div")
                .self_closing
        );
    }

    #[test]
    fn parse_close_tag_matches_a_leading_block_close_tag() {
        assert_eq!(
            html_element::parse_close_tag("</div>rest"),
            Some("</div>".len())
        );
        assert_eq!(
            html_element::parse_close_tag("</div  >"),
            Some("</div  >".len())
        );
        // Only a block-level name, only at the very start.
        assert_eq!(html_element::parse_close_tag("</span>"), None);
        assert_eq!(html_element::parse_close_tag("x</div>"), None);
        assert_eq!(html_element::parse_close_tag("<div>"), None);
    }

    #[test]
    fn scan_depth_balances_nested_same_name_tags() {
        // A same-name open raises the depth; the matching close returns it to zero mid-line.
        let (depth, close) = html_element::scan_depth("<div>a</div></div>", "div", 1);
        assert_eq!(depth, 0);
        assert_eq!(close, Some("<div>a</div>".len() + "</div>".len()));
        // A self-closing same-name tag does not raise the depth.
        assert_eq!(html_element::scan_depth("<div/>", "div", 1), (1, None));
        // A different tag's `>` inside its attributes is skipped whole.
        assert_eq!(
            html_element::scan_depth("<td x=\">\">", "div", 1),
            (1, None)
        );
    }
}

#[cfg(test)]
mod dialect_tests {
    use super::{IrBlock, parse};
    use carta_core::{Extension, Extensions, presets};

    /// Parse with a given extension set in the Markdown dialect (greedy paragraphs).
    fn markdown_with(input: &str, extensions: Extensions) -> Vec<IrBlock> {
        parse(input, extensions, true).0
    }

    /// Parse with a given extension set in the `CommonMark` family (non-greedy paragraphs).
    fn strict_with(input: &str, extensions: Extensions) -> Vec<IrBlock> {
        parse(input, extensions, false).0
    }

    fn ordered_start(blocks: &[IrBlock]) -> Option<i32> {
        match blocks {
            [IrBlock::OrderedList(attrs, _)] => Some(attrs.start),
            _ => None,
        }
    }

    fn heading_level(blocks: &[IrBlock]) -> Option<i32> {
        match blocks {
            [IrBlock::Heading(level, _)] => Some(*level),
            _ => None,
        }
    }

    #[test]
    fn markdown_honors_start_number_when_startnum_enabled() {
        // The default Markdown preset enables `startnum`, so the list begins at its written number.
        assert!(presets::MARKDOWN.contains(Extension::Startnum));
        let blocks = markdown_with("3. a\n4. b\n", presets::MARKDOWN);
        assert_eq!(ordered_start(&blocks), Some(3));
    }

    #[test]
    fn markdown_forces_start_to_one_when_startnum_disabled() {
        let extensions = {
            let mut set = presets::MARKDOWN;
            set.remove(Extension::Startnum);
            set
        };
        assert!(!extensions.contains(Extension::Startnum));
        let blocks = markdown_with("3. a\n4. b\n", extensions);
        assert_eq!(ordered_start(&blocks), Some(1));
    }

    #[test]
    fn commonmark_always_honors_start_number() {
        // CommonMark has no `startnum` extension; the written number is always kept.
        let blocks = strict_with("3. a\n4. b\n", presets::COMMONMARK);
        assert_eq!(ordered_start(&blocks), Some(3));
        let gfm = strict_with("3. a\n4. b\n", presets::GFM);
        assert_eq!(ordered_start(&gfm), Some(3));
    }

    #[test]
    fn markdown_setext_underline_needs_a_single_line_paragraph() {
        // A single line above the underline forms a heading in the markdown dialect.
        let one = markdown_with("one line\n===\n", presets::MARKDOWN);
        assert_eq!(heading_level(&one), Some(1));
        // Two or more lines keep the underline as ordinary paragraph text: no heading forms, and the
        // `===` line is retained as part of the paragraph.
        let many = markdown_with("line one\nline two\n===\n", presets::MARKDOWN);
        assert!(matches!(many.as_slice(), [IrBlock::Para(text)] if text.contains("===")));
        // A leading reference definition does not count toward the line budget: the single content
        // line still heads.
        let refd = markdown_with("[x]: /u\ncontent\n===\n", presets::MARKDOWN);
        assert_eq!(heading_level(&refd), Some(1));
        // The CommonMark family heads a multi-line paragraph, per its setext rule.
        let cm = strict_with("line one\nline two\n===\n", presets::COMMONMARK);
        assert_eq!(heading_level(&cm), Some(1));
    }

    #[test]
    fn markdown_reads_seven_hashes_as_level_seven() {
        let blocks = markdown_with("####### h\n", presets::MARKDOWN);
        assert_eq!(heading_level(&blocks), Some(7));
    }

    #[test]
    fn markdown_reads_eight_hashes_as_level_eight() {
        let blocks = markdown_with("######## h\n", presets::MARKDOWN);
        assert_eq!(heading_level(&blocks), Some(8));
    }

    #[test]
    fn markdown_does_not_cap_deep_heading_levels() {
        let blocks = markdown_with("############## deep\n", presets::MARKDOWN);
        assert_eq!(heading_level(&blocks), Some(14));
    }

    #[test]
    fn commonmark_reads_seven_hashes_as_a_paragraph() {
        let blocks = strict_with("####### h\n", presets::COMMONMARK);
        assert!(matches!(blocks.as_slice(), [IrBlock::Para(_)]));
        let gfm = strict_with("####### h\n", presets::GFM);
        assert!(matches!(gfm.as_slice(), [IrBlock::Para(_)]));
    }

    #[test]
    fn deep_heading_still_requires_a_space_after_the_hashes() {
        // Seven hashes glued to content is not a heading in either dialect.
        let blocks = markdown_with("#######nospace\n", presets::MARKDOWN);
        assert!(matches!(blocks.as_slice(), [IrBlock::Para(_)]));
    }

    #[test]
    fn classic_dialect_reads_a_hash_run_glued_to_text_as_a_heading() {
        // With space_in_atx_header off, a hash run needs no following space.
        for input in ["#heading\n", "##heading\n", "###heading\n"] {
            let blocks = markdown_with(input, presets::MARKDOWN_STRICT_READ);
            assert_eq!(
                heading_level(&blocks),
                i32::try_from(input.bytes().take_while(|&b| b == b'#').count()).ok(),
                "expected heading for {input:?}, got {blocks:?}"
            );
        }
    }

    #[test]
    fn classic_dialect_strips_a_glued_closing_hash_run() {
        // With space_in_atx_header off, a trailing hash run always terminates the heading,
        // even glued to the content; an interior hash is kept.
        let cases = [
            ("#foo#\n", "foo"),
            ("#foo ###\n", "foo"),
            ("#foo#bar#\n", "foo#bar"),
        ];
        for (input, want) in cases {
            let blocks = markdown_with(input, presets::MARKDOWN_STRICT_READ);
            match blocks.as_slice() {
                [IrBlock::Heading(1, text)] => assert_eq!(text, want, "for {input:?}"),
                other => panic!("expected level-1 heading for {input:?}, got {other:?}"),
            }
        }
    }

    #[test]
    fn extended_dialect_requires_a_space_after_the_hash_run() {
        // space_in_atx_header is on in the extended dialect: a glued run is a paragraph.
        let blocks = markdown_with("#heading\n", presets::MARKDOWN);
        assert!(matches!(blocks.as_slice(), [IrBlock::Para(_)]));
    }

    #[test]
    fn commonmark_requires_a_space_after_the_hash_run() {
        let blocks = strict_with("#heading\n", presets::COMMONMARK);
        assert!(matches!(blocks.as_slice(), [IrBlock::Para(_)]));
    }

    #[test]
    fn markdown_rejects_an_indented_atx_heading() {
        // The Markdown dialect requires the hash run to start at the left margin.
        for input in ["  # h\n", "   ###### h\n", "   ####### h\n"] {
            let blocks = markdown_with(input, presets::MARKDOWN);
            assert!(
                matches!(blocks.as_slice(), [IrBlock::Para(_)]),
                "expected paragraph for {input:?}, got {blocks:?}"
            );
        }
    }

    #[test]
    fn commonmark_allows_up_to_three_spaces_before_an_atx_heading() {
        let blocks = strict_with("   ###### h\n", presets::COMMONMARK);
        assert_eq!(heading_level(&blocks), Some(6));
    }

    use carta_ast::{ListNumberDelim, ListNumberStyle};

    /// The (start, style, delim) of a single ordered list, or `None` for anything else.
    fn ordered_attrs(blocks: &[IrBlock]) -> Option<(i32, ListNumberStyle, ListNumberDelim)> {
        match blocks {
            [IrBlock::OrderedList(attrs, _)] => Some((attrs.start, attrs.style, attrs.delim)),
            _ => None,
        }
    }

    fn list_item_count(blocks: &[IrBlock]) -> usize {
        match blocks {
            [IrBlock::OrderedList(_, items)] => items.len(),
            _ => 0,
        }
    }

    // --- Gap 3: multi-letter roman-numeral ordered lists ---

    #[test]
    fn markdown_reads_a_multi_letter_roman_list() {
        // `II.`/`III.` are unambiguously roman: the list is UpperRoman starting at two.
        let blocks = markdown_with("II. two\nIII. three\n", presets::MARKDOWN);
        assert_eq!(
            ordered_attrs(&blocks),
            Some((2, ListNumberStyle::UpperRoman, ListNumberDelim::Period))
        );
        assert_eq!(list_item_count(&blocks), 2);
    }

    #[test]
    fn markdown_reads_a_lowercase_roman_paren_list() {
        let blocks = markdown_with("ii) a\niii) b\n", presets::MARKDOWN);
        assert_eq!(
            ordered_attrs(&blocks),
            Some((2, ListNumberStyle::LowerRoman, ListNumberDelim::OneParen))
        );
    }

    #[test]
    fn markdown_computes_the_start_ordinal_from_the_roman_value() {
        // `IV` is four; the list begins there.
        let blocks = markdown_with("IV. a\nV. b\n", presets::MARKDOWN);
        assert_eq!(
            ordered_attrs(&blocks),
            Some((4, ListNumberStyle::UpperRoman, ListNumberDelim::Period))
        );
    }

    #[test]
    fn markdown_reads_a_two_place_roman_numeral() {
        // `XII` is twelve: the tens and ones places combine.
        let blocks = markdown_with("XII. a\nXIII. b\n", presets::MARKDOWN);
        assert_eq!(
            ordered_attrs(&blocks),
            Some((12, ListNumberStyle::UpperRoman, ListNumberDelim::Period))
        );
    }

    #[test]
    fn markdown_reads_a_thousands_roman_numeral() {
        let blocks = markdown_with("MII. a\nMIII. b\n", presets::MARKDOWN);
        assert_eq!(
            ordered_attrs(&blocks),
            Some((1002, ListNumberStyle::UpperRoman, ListNumberDelim::Period))
        );
    }

    #[test]
    fn markdown_keeps_a_lone_capital_letter_marker_as_a_paragraph() {
        // A single uppercase letter followed by a period and one space is ambiguous with an initial
        // (`I. only` could be a name), so it stays a paragraph rather than opening a list.
        let blocks = markdown_with("I. only\n", presets::MARKDOWN);
        assert!(
            matches!(blocks.as_slice(), [IrBlock::Para(_)]),
            "expected a paragraph, got {blocks:?}"
        );
    }

    #[test]
    fn markdown_reads_a_lone_capital_letter_marker_with_two_spaces_as_a_list() {
        // Two spaces after the marker disambiguate it from an initial, so the single `I` opens a
        // one-letter roman list (value one).
        let blocks = markdown_with("I.  only\n", presets::MARKDOWN);
        assert_eq!(
            ordered_attrs(&blocks),
            Some((1, ListNumberStyle::UpperRoman, ListNumberDelim::Period))
        );
    }

    // --- Gap 4: `#.` fancy hash-marker ordered lists ---

    #[test]
    fn markdown_reads_a_hash_period_list() {
        let blocks = markdown_with("#. one\n#. two\n", presets::MARKDOWN);
        assert_eq!(
            ordered_attrs(&blocks),
            Some((
                1,
                ListNumberStyle::DefaultStyle,
                ListNumberDelim::DefaultDelim
            ))
        );
        assert_eq!(list_item_count(&blocks), 2);
    }

    #[test]
    fn markdown_reads_a_hash_paren_list() {
        let blocks = markdown_with("#) one\n#) two\n", presets::MARKDOWN);
        assert_eq!(
            ordered_attrs(&blocks),
            Some((1, ListNumberStyle::DefaultStyle, ListNumberDelim::OneParen))
        );
    }

    #[test]
    fn commonmark_does_not_read_a_hash_marker_as_a_list() {
        // The fancy hash marker is a Markdown-dialect feature; CommonMark keeps it literal.
        let blocks = strict_with("#. one\n#. two\n", presets::COMMONMARK);
        assert!(
            ordered_attrs(&blocks).is_none(),
            "CommonMark should not form a list from `#.`, got {blocks:?}"
        );
    }
}

#[cfg(test)]
mod abbreviation_tests {
    use super::{IrBlock, parse};
    use carta_core::{Extension, Extensions};

    fn with_abbr(input: &str) -> Vec<IrBlock> {
        parse(
            input,
            Extensions::from_list(&[Extension::Abbreviations]),
            true,
        )
        .0
    }

    fn plain(input: &str) -> Vec<IrBlock> {
        parse(input, Extensions::empty(), true).0
    }

    #[test]
    fn a_definition_at_the_left_edge_is_consumed() {
        let out = with_abbr("*[HTML]: markup\n\nBody.\n");
        assert!(
            matches!(out.as_slice(), [IrBlock::Para(p)] if p == "Body."),
            "definition should be dropped, leaving only the body: {out:?}"
        );
    }

    #[test]
    fn a_definition_is_stripped_from_a_paragraph_front() {
        let out = with_abbr("*[HTML]: markup\nmore text\n");
        assert!(
            matches!(out.as_slice(), [IrBlock::Para(p)] if p == "more text"),
            "only the definition line should be removed: {out:?}"
        );
    }

    #[test]
    fn consecutive_definitions_are_all_consumed() {
        let out = with_abbr("*[A]: x\n*[B]: y\nmore\n");
        assert!(
            matches!(out.as_slice(), [IrBlock::Para(p)] if p == "more"),
            "both definitions should be removed: {out:?}"
        );
    }

    #[test]
    fn an_indented_definition_is_left_as_text() {
        // A definition must sit flush at the container's left edge; one space in front keeps it a
        // paragraph.
        let out = with_abbr(" *[HTML]: markup\n\nBody.\n");
        assert_eq!(
            out.len(),
            2,
            "indented definition stays a paragraph: {out:?}"
        );
    }

    #[test]
    fn without_the_extension_a_definition_is_ordinary_text() {
        let out = plain("*[HTML]: markup\n\nBody.\n");
        assert_eq!(
            out.len(),
            2,
            "no consumption without the extension: {out:?}"
        );
    }
}

#[cfg(test)]
mod fence_interrupt_tests {
    use super::{IrBlock, parse};
    use carta_core::{Extension, Extensions};

    fn md(input: &str, exts: &[Extension]) -> Vec<IrBlock> {
        parse(input, Extensions::from_list(exts), true).0
    }

    #[test]
    fn a_tilde_fence_does_not_interrupt_a_paragraph() {
        let out = md("text\n~~~\ncode\n~~~\n", &[Extension::FencedCodeBlocks]);
        assert!(
            matches!(out.as_slice(), [IrBlock::Para(_)]),
            "a tilde fence folds into the open paragraph: {out:?}"
        );
    }

    #[test]
    fn a_tilde_fence_opens_a_block_at_the_top_level() {
        let out = md("~~~\ncode\n~~~\n", &[Extension::FencedCodeBlocks]);
        assert!(
            matches!(out.as_slice(), [IrBlock::CodeBlock(..)]),
            "a top-level tilde fence still opens a code block: {out:?}"
        );
    }

    #[test]
    fn a_backtick_fence_still_interrupts_a_paragraph() {
        let out = md("text\n```\ncode\n```\n", &[Extension::BacktickCodeBlocks]);
        assert!(
            matches!(out.as_slice(), [IrBlock::Para(_), IrBlock::CodeBlock(..)]),
            "a backtick fence interrupts the paragraph: {out:?}"
        );
    }

    #[test]
    fn an_opener_after_a_non_interrupting_tilde_still_fires() {
        // The tilde line folds in, but the following heading is read normally rather than absorbed.
        let out = md(
            "text\n~~~\n# h\n~~~\nmore\n",
            &[Extension::FencedCodeBlocks],
        );
        assert!(
            matches!(out.get(1), Some(IrBlock::Heading(1, _))),
            "a heading after a non-interrupting tilde fence still opens: {out:?}"
        );
    }
}

#[cfg(test)]
mod raw_html_span_tests {
    use super::{IrBlock, parse};
    use carta_core::{Extension, Extensions};

    /// The Markdown family reading raw HTML where inner content is not parsed (the column-zero,
    /// no-interrupt gate: neither `markdown_attribute` nor the div/markdown-in-HTML extensions).
    fn strict(input: &str) -> Vec<IrBlock> {
        parse(input, Extensions::empty(), true).0
    }

    /// The same reading with `markdown_attribute`, which lets the block indent and interrupt.
    fn attr(input: &str) -> Vec<IrBlock> {
        parse(
            input,
            Extensions::from_list(&[Extension::MarkdownAttribute]),
            true,
        )
        .0
    }

    #[test]
    fn a_block_element_spans_to_its_balanced_close() {
        let out = strict("<div>\nx\n\ny\n</div>\n");
        let [IrBlock::RawHtml(html)] = out.as_slice() else {
            panic!("expected one raw HTML block, got {out:?}");
        };
        assert_eq!(html, "<div>\nx\n\ny\n</div>");
    }

    #[test]
    fn nested_same_name_tags_balance() {
        let out = strict("<div>\n<div>\na\n</div>\nb\n</div>\n");
        let [IrBlock::RawHtml(html)] = out.as_slice() else {
            panic!("expected one raw HTML block, got {out:?}");
        };
        assert_eq!(html, "<div>\n<div>\na\n</div>\nb\n</div>");
    }

    #[test]
    fn a_void_tag_is_a_single_line_block_and_the_rest_parses() {
        let out = strict("<hr>\ntext\n");
        let [IrBlock::RawHtml(html), IrBlock::Para(text)] = out.as_slice() else {
            panic!("expected a single-tag raw block then a paragraph, got {out:?}");
        };
        assert_eq!(html, "<hr>");
        assert_eq!(text, "text");
    }

    #[test]
    fn a_self_closing_tag_is_a_single_line_block() {
        let out = strict("<div/>\ntext\n");
        assert!(
            matches!(out.first(), Some(IrBlock::RawHtml(h)) if h == "<div/>"),
            "a self-closing tag opens no span: {out:?}"
        );
    }

    #[test]
    fn a_bare_close_tag_stands_alone() {
        let out = strict("</div>\ntext\n");
        let [IrBlock::RawHtml(html), IrBlock::Para(_)] = out.as_slice() else {
            panic!("expected a lone close tag then a paragraph, got {out:?}");
        };
        assert_eq!(html, "</div>");
    }

    #[test]
    fn an_open_and_close_on_one_line_re_feeds_the_trailing_text() {
        let out = strict("<div>x</div> tail\n");
        let [IrBlock::RawHtml(html), IrBlock::Para(text)] = out.as_slice() else {
            panic!("expected a raw block then the trailing text, got {out:?}");
        };
        assert_eq!(html, "<div>x</div>");
        assert_eq!(text, "tail");
    }

    #[test]
    fn an_unclosed_open_tag_is_the_tag_alone() {
        let out = strict("<div>\nx\n\ny\n");
        let [IrBlock::RawHtml(html), IrBlock::Para(a), IrBlock::Para(b)] = out.as_slice() else {
            panic!("expected the tag alone then two paragraphs, got {out:?}");
        };
        assert_eq!(html, "<div>");
        assert_eq!(a, "x");
        assert_eq!(b, "y");
    }

    #[test]
    fn an_inline_or_unknown_tag_opens_no_block() {
        for input in ["<span>x</span>\ntext\n", "<foo>\nx\n</foo>\n"] {
            let out = strict(input);
            assert!(
                !out.iter().any(|b| matches!(b, IrBlock::RawHtml(_))),
                "a non-block tag stays inline: {out:?}"
            );
        }
    }

    #[test]
    fn without_markdown_attribute_an_indented_tag_is_inline() {
        let out = strict("   <div>\nx\n</div>\n");
        assert!(
            !out.iter().any(|b| matches!(b, IrBlock::RawHtml(_))),
            "an indented tag folds into a paragraph: {out:?}"
        );
    }

    #[test]
    fn with_markdown_attribute_an_indented_tag_opens_a_block() {
        let out = attr("   <div>\nx\n</div>\n");
        let [IrBlock::RawHtml(html)] = out.as_slice() else {
            panic!("expected one raw HTML block, got {out:?}");
        };
        assert_eq!(html, "<div>\nx\n</div>");
    }

    #[test]
    fn without_markdown_attribute_the_block_folds_into_a_paragraph() {
        let out = strict("text\n<div>\nx\n</div>\n");
        assert!(
            matches!(out.as_slice(), [IrBlock::Para(_)]),
            "the block does not interrupt the paragraph: {out:?}"
        );
    }

    #[test]
    fn with_markdown_attribute_the_block_interrupts_a_paragraph() {
        let out = attr("text\n<div>\nx\n</div>\n");
        let [IrBlock::Plain(text), IrBlock::RawHtml(html)] = out.as_slice() else {
            panic!("expected a tight paragraph then a raw block, got {out:?}");
        };
        assert_eq!(text, "text");
        assert_eq!(html, "<div>\nx\n</div>");
    }
}