panache-parser 0.22.0

Lossless CST parser and syntax wrappers for Pandoc markdown, Quarto, and RMarkdown
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
//! Block parser dispatcher for organizing block-level parsing.
//!
//! This module provides a trait-based abstraction for block parsers,
//! making it easier to add new block types and reducing duplication in parse_inner_content.
//!
//! Design principles:
//! - Single-pass parsing preserved (no backtracking)
//! - Each block parser operates independently
//! - Inline parsing still integrated (called from within block parsing)
//! - Maintains exact CST structure and losslessness

use crate::options::{Dialect, ParserOptions};
use rowan::GreenNodeBuilder;
use std::any::Any;

use super::diagnostics::Diagnostics;

use super::blocks::admonitions::{AdmonitionOpen, try_parse_admonition_open};
use super::blocks::blockquotes::{
    can_start_blockquote, count_blockquote_markers, emit_one_blockquote_marker,
    strip_n_blockquote_markers,
};
use super::blocks::code_blocks::{
    CodeBlockType, FenceInfo, InfoString, is_closing_fence, is_gfm_math_fence,
    parse_fenced_code_block, parse_fenced_math_block, try_parse_fence_open,
};
use super::blocks::container_prefix::{
    ContainerPrefix, StrippedLines, bq_outer_of_list, strip_list_indent,
};
use super::blocks::definition_lists::{
    next_line_is_definition_marker, try_parse_definition_marker,
};
use super::blocks::fenced_divs::{DivFenceInfo, is_div_closing_fence, try_parse_div_fence_open};
use super::blocks::figures::parse_figure;
use super::blocks::headings::{
    emit_atx_heading, emit_setext_heading, try_parse_atx_heading, try_parse_setext_heading,
};
use super::blocks::horizontal_rules::{emit_horizontal_rule, try_parse_horizontal_rule};
use super::blocks::html_blocks::{
    HtmlBlockType, SoftbreakFusion, is_pandoc_inline_block_tag_name, is_pandoc_void_block_tag_name,
    pandoc_html_open_tag_closes, parse_html_block_with_wrapper, probe_open_tag_line_has_close_gt,
    try_parse_html_block_start,
};
use super::blocks::indented_code::{is_indented_code_line, parse_indented_code_block};
use super::blocks::latex_envs::LatexEnvInfo;
use super::blocks::line_blocks::{parse_line_block, try_parse_line_block_start};
use super::blocks::lists::{
    ListDelimiter, ListMarker, OrderedMarker, is_content_nested_bullet_marker,
    try_parse_list_marker,
};
use super::blocks::metadata::{
    YamlContentOutcome, collect_yaml_content, emit_yaml_block, find_yaml_block_closing_pos,
    prepare_yaml_content, try_parse_mmd_title_block, try_parse_pandoc_title_block,
    try_parse_yaml_block,
};
use super::blocks::myst_directives::{
    DirectiveOpen, DirectiveOption, is_directive_closing_fence, try_parse_directive_open,
    try_parse_directive_option,
};
use super::blocks::myst_targets::{
    BlockBreak, Target, is_comment_line, try_parse_block_break, try_parse_target,
};
use super::blocks::raw_blocks;
use super::blocks::raw_blocks::extract_environment_name;
use super::blocks::reference_links::{
    ReferenceSpans, line_is_mmd_link_attribute_continuation, reference_definition_spans,
    try_parse_footnote_marker, try_parse_reference_definition, try_parse_reference_definition_lax,
};
use super::blocks::tables::{
    is_caption_followed_by_table, try_parse_grid_table, try_parse_multiline_table,
    try_parse_pipe_table, try_parse_simple_table,
};
use super::inlines::links::{LinkScanContext, try_parse_inline_image};
use super::inlines::svelte::{SvelteKind, emit_svelte_template, try_parse_svelte_template};
use super::utils::attributes::{emit_div_info_node, parse_html_tag_attributes};
use super::utils::container_stack::{byte_index_at_column, leading_indent};
use super::utils::helpers::{strip_newline, trim_end_newlines};
use super::utils::marker_utils::parse_blockquote_marker_info;
use super::utils::tree_copy::copy_green_node;

/// Information about list indentation context.
///
/// Used by block parsers that need to handle indentation stripping
/// when parsing inside list items (e.g., fenced code blocks).
#[derive(Debug, Clone, Copy)]
pub(crate) struct ListIndentInfo {
    /// Number of columns to strip for list content
    pub content_col: usize,
}

/// Context passed to block parsers for decision-making.
///
/// Contains immutable references to parser state that block parsers need
/// to check conditions (e.g., blank line before, blockquote depth, etc.).
pub(crate) struct BlockContext<'a> {
    /// Whether there was a blank line before this line (relaxed, container-aware)
    pub has_blank_before: bool,

    /// Whether there was a strict blank line before this line (no container exceptions)
    pub has_blank_before_strict: bool,

    /// Whether we're currently inside a fenced div (container-owned state)
    pub in_fenced_div: bool,

    /// Expected closer of the innermost open MyST directive, as
    /// `(fence_char, min_count)`. `None` when not inside a directive. Lets
    /// `MystDirectiveCloseParser` match a closing fence against the opener.
    pub myst_directive_closer: Option<(u8, usize)>,

    /// Whether we're at document start (pos == 0)
    pub at_document_start: bool,

    /// Current blockquote depth
    pub blockquote_depth: usize,

    /// Parser configuration
    pub config: &'a ParserOptions,

    /// Sink for embedded-sublanguage syntax errors (malformed YAML). An owned
    /// `Rc`-backed clone, so it threads here without borrowing `self` (which
    /// would clash with the `&mut GreenNodeBuilder` held during emission).
    pub diags: Diagnostics,

    // NOTE: we intentionally do not store `&ContainerStack` here to avoid
    // long-lived borrows of `self` in the main parser loop.
    /// Base indentation from container context (footnotes, definitions)
    pub content_indent: usize,

    /// Indentation stripped from the current line that should be emitted for losslessness
    pub indent_to_emit: Option<&'a str>,

    /// List indentation info if inside a list
    pub list_indent_info: Option<ListIndentInfo>,

    /// Whether we're currently inside any list
    pub in_list: bool,

    /// Whether the immediate enclosing container is a list item that has so
    /// far seen only its marker (no content yet). Equivalent to the
    /// `marker_only` flag on `Container::ListItem`. Used by indented code
    /// detection so that the line *after* an empty list marker can still
    /// open an indented code block when its indent is ≥ content_col + 4,
    /// even though there is no blank line separating the marker line from
    /// the indented line.
    pub in_marker_only_list_item: bool,

    /// If the immediate enclosing `Container::ListItem`'s buffer starts
    /// with a Pandoc matched-pair HTML open tag (e.g. `<div>`,
    /// `<section>`, `<pre>`) whose opens outnumber its closes, this is
    /// the (lowercase) tag name. Used by `HtmlBlockParser::detect_prepared`
    /// to suppress the close-form dispatch (`</div>` etc.) that would
    /// otherwise interrupt the buffer mid-construct — letting the buffer
    /// accumulate the full matched-pair text so the emit-time structural
    /// lift in `ListItemBuffer::emit_as_block` produces a single lifted
    /// HTML block as the list item's content.
    pub list_item_unclosed_html_block_tag: Option<String>,

    /// Whether a `Container::Paragraph` is currently open and buffering
    /// content. When `true`, the *previous* source line was buffered as
    /// paragraph text — even if its shape would have been a heading or HR
    /// in isolation — so paragraph-non-interrupting blocks (notably
    /// indented code under Pandoc) must treat it as paragraph continuation,
    /// not as a "terminal one-liner" that opens a new section.
    pub paragraph_open: bool,

    /// Next line content for lookahead (used by setext headings)
    pub next_line: Option<&'a str>,

    /// Open-alpha-at-indent hint for `ListParser::detect_prepared`.
    /// Precomputed by the parser core from `self.containers` (which is
    /// intentionally not threaded through `BlockContext` — see the note
    /// above). Lets marker detection resolve single-letter Roman
    /// candidates {i,v,x,I,V,X} against an open alpha list in a single
    /// classification pass under Pandoc dialect.
    pub open_alpha_hint: super::blocks::lists::OpenListHint,
}

/// Result of detecting whether a block can be parsed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum BlockDetectionResult {
    /// Can parse this block, requires blank line before
    Yes,

    /// Can parse this block and can interrupt paragraphs (no blank line needed)
    YesCanInterrupt,

    /// Cannot parse this content
    No,
}

/// A prepared (cached) detection result.
///
/// This allows expensive detection logic (e.g., fence parsing) to be performed once,
/// while emission happens only after the caller prepares (flushes buffers/closes paragraphs).
pub(crate) struct PreparedBlockMatch {
    pub parser_index: usize,
    pub detection: BlockDetectionResult,
    pub effect: BlockEffect,
    pub payload: Option<Box<dyn Any>>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum BlockEffect {
    None,
    OpenFencedDiv,
    CloseFencedDiv,
    OpenMystDirective,
    CloseMystDirective,
    OpenAdmonition,
    OpenFootnoteDefinition,
    OpenList,
    OpenDefinitionList,
    OpenBlockQuote,
}

/// Trait for block-level parsers.
///
/// Each block type implements this trait with a two-phase approach:
/// 1. Detection: Can this block type parse this content? (lightweight, no emission)
/// 2. Parsing: Actually parse and emit the block to the builder (called after preparation)
///
/// This separation allows the caller to:
/// - Prepare for block elements (close paragraphs, flush buffers) BEFORE emission
/// - Handle blocks that can interrupt paragraphs vs those that need blank lines
/// - Maintain correct CST node ordering
///
/// Note: This is purely organizational - the trait doesn't introduce
/// backtracking or multiple passes. Each parser operates during the
/// single forward pass through the document.
pub(crate) trait BlockParser {
    fn effect(&self) -> BlockEffect {
        BlockEffect::None
    }

    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)>;

    fn parse_prepared(
        &self,
        ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        payload: Option<&dyn Any>,
    ) -> usize;

    /// Name of this block parser (for debugging/logging)
    fn name(&self) -> &'static str;
}

// ============================================================================
// Concrete Block Parser Implementations
// ============================================================================

/// Horizontal rule parser
pub(crate) struct HorizontalRuleParser;

impl BlockParser for HorizontalRuleParser {
    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        // CommonMark §4.1: thematic breaks can interrupt a paragraph (no
        // blank line required). Pandoc-markdown disagrees and treats a
        // would-be thematic break inside a paragraph as plain text. Branch
        // on dialect.
        let common_mark = ctx.config.dialect == crate::options::Dialect::CommonMark;
        if !common_mark && !ctx.has_blank_before {
            return None;
        }

        // Check if this looks like a horizontal rule
        if try_parse_horizontal_rule(lines.first()).is_some() {
            let detection = if common_mark {
                BlockDetectionResult::YesCanInterrupt
            } else {
                BlockDetectionResult::Yes
            };
            Some((detection, None))
        } else {
            None
        }
    }

    fn parse_prepared(
        &self,
        _ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        _payload: Option<&dyn Any>,
    ) -> usize {
        emit_horizontal_rule(builder, lines.first());
        1 // Consumed 1 line
    }

    fn name(&self) -> &'static str {
        "horizontal_rule"
    }
}

/// ATX heading parser (# Heading)
pub(crate) struct AtxHeadingParser;

impl BlockParser for AtxHeadingParser {
    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        if ctx.config.extensions.blank_before_header && !ctx.has_blank_before {
            return None;
        }

        let level = try_parse_atx_heading(lines.first())?;
        // CommonMark §4.2 allows an ATX heading to interrupt a paragraph, and
        // Pandoc does the same when its `blank_before_header` extension is
        // disabled. `YesCanInterrupt` closes and flushes the open paragraph
        // before the heading is emitted, preserving source order. No dialect
        // check needed: with the extension on, the guard above already
        // requires a blank line before the heading, so no paragraph can be
        // open and `Yes` vs `YesCanInterrupt` is moot (CommonMark defaults
        // the extension off).
        let detection = if ctx.config.extensions.blank_before_header {
            BlockDetectionResult::Yes
        } else {
            BlockDetectionResult::YesCanInterrupt
        };
        Some((detection, Some(Box::new(level))))
    }

    fn parse_prepared(
        &self,
        ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        payload: Option<&dyn Any>,
    ) -> usize {
        let content = lines.first();
        let heading_level = payload
            .and_then(|p| p.downcast_ref::<usize>().copied())
            .or_else(|| try_parse_atx_heading(content))
            .unwrap_or(1);
        emit_atx_heading(builder, content, heading_level, ctx.config);
        1
    }

    fn name(&self) -> &'static str {
        "atx_heading"
    }
}

/// Pandoc title block parser (% Title ...)
pub(crate) struct PandocTitleBlockParser;

impl BlockParser for PandocTitleBlockParser {
    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        let line_pos = lines.pos();
        if !ctx.config.extensions.pandoc_title_block {
            return None;
        }

        // Must be at document start.
        if !ctx.at_document_start || line_pos != 0 {
            return None;
        }

        // Must start with % (allow leading spaces).
        if !lines.first().trim_start().starts_with('%') {
            return None;
        }

        Some((BlockDetectionResult::Yes, None))
    }

    fn parse_prepared(
        &self,
        _ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        _payload: Option<&dyn Any>,
    ) -> usize {
        let line_pos = lines.pos();
        let lines = lines.raw();
        let new_pos =
            try_parse_pandoc_title_block(lines, line_pos, builder).unwrap_or(line_pos + 1);
        new_pos - line_pos
    }

    fn name(&self) -> &'static str {
        "pandoc_title_block"
    }
}

/// MultiMarkdown title block parser (Key: Value ...)
pub(crate) struct MmdTitleBlockParser;

impl BlockParser for MmdTitleBlockParser {
    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        let line_pos = lines.pos();
        if !ctx.config.extensions.mmd_title_block {
            return None;
        }

        // Must be at top-level document start.
        if !ctx.at_document_start || line_pos != 0 || ctx.blockquote_depth > 0 {
            return None;
        }

        // Quick guard to avoid work on obvious non-matches.
        let first = lines.first();
        if first.trim().is_empty() || !first.contains(':') {
            return None;
        }

        Some((BlockDetectionResult::Yes, None))
    }

    fn parse_prepared(
        &self,
        _ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        _payload: Option<&dyn Any>,
    ) -> usize {
        let line_pos = lines.pos();
        let lines = lines.raw();
        let new_pos = try_parse_mmd_title_block(lines, line_pos, builder).unwrap_or(line_pos + 1);
        new_pos - line_pos
    }

    fn name(&self) -> &'static str {
        "mmd_title_block"
    }
}

/// YAML metadata block parser (--- ... ---/...)
pub(crate) struct YamlMetadataParser;
#[derive(Debug, Clone)]
pub(crate) struct YamlMetadataPrepared {
    pub at_document_start: bool,
    pub closing_pos: usize,
    pub outcome: YamlContentOutcome,
}

impl BlockParser for YamlMetadataParser {
    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        let content = lines.first();
        let line_pos = lines.pos();
        let lines = lines.raw();
        if !ctx.config.extensions.yaml_metadata_block {
            return None;
        }

        // Must be at top level (not inside blockquotes)
        if ctx.blockquote_depth > 0 {
            return None;
        }

        // Must start with ---
        if content.trim() != "---" {
            return None;
        }

        // Fast guard: mid-document YAML requires a preceding blank line.
        if !ctx.has_blank_before && !ctx.at_document_start {
            return None;
        }

        // Mid-document YAML metadata is a pandoc-markdown feature. The
        // CommonMark-family readers (gfm, myst, mdsvex) only recognize YAML
        // frontmatter on the document's first line; elsewhere `---` is a
        // thematic break (pandoc's gfm reader parses `---`/`key: value`/`---`
        // in the body as HR plus setext heading).
        if !ctx.at_document_start && ctx.config.dialect == Dialect::CommonMark {
            return None;
        }

        // Look ahead: next line must NOT be blank (to distinguish from horizontal rule)
        let next_line = lines.get(line_pos + 1)?;
        if next_line.trim().is_empty() {
            // This is a horizontal rule, not YAML
            return None;
        }

        let closing_pos = find_yaml_block_closing_pos(lines, line_pos, ctx.at_document_start)?;

        // Metadata gate: well-formed YAML whose top level is not a mapping
        // or null is not metadata under pandoc — fall through so the lines
        // reparse as ordinary blocks. Carries the validation + parse result
        // to emission to avoid re-parsing the content.
        let content = collect_yaml_content(lines, line_pos, closing_pos);
        let outcome = prepare_yaml_content(&content, ctx.config.flavor)?;

        // Cache the `at_document_start` flag for emission (avoids any ambiguity if ctx changes).
        Some((
            BlockDetectionResult::Yes,
            Some(Box::new(YamlMetadataPrepared {
                at_document_start: ctx.at_document_start,
                closing_pos,
                outcome,
            })),
        ))
    }

    fn parse_prepared(
        &self,
        ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        payload: Option<&dyn Any>,
    ) -> usize {
        let line_pos = lines.pos();
        let lines = lines.raw();
        if let Some(prepared) = payload.and_then(|p| p.downcast_ref::<YamlMetadataPrepared>())
            && let Some(new_pos) = emit_yaml_block(
                lines,
                line_pos,
                prepared.closing_pos,
                builder,
                &ctx.diags,
                &prepared.outcome,
            )
        {
            return new_pos - line_pos;
        }

        let at_document_start = payload
            .and_then(|p| p.downcast_ref::<YamlMetadataPrepared>())
            .map(|p| p.at_document_start)
            .unwrap_or(ctx.at_document_start);
        try_parse_yaml_block(
            lines,
            line_pos,
            builder,
            at_document_start,
            &ctx.diags,
            ctx.config.flavor,
        )
        .map(|new_pos| new_pos - line_pos)
        .unwrap_or(1)
    }

    fn name(&self) -> &'static str {
        "yaml_metadata"
    }
}

/// Figure parser (standalone image on its own line)
pub(crate) struct FigureParser;

impl BlockParser for FigureParser {
    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        // Pandoc-only behavior; CommonMark/GFM keep the image inline within
        // the paragraph and do not promote it to a figure block.
        if !ctx.config.extensions.implicit_figures {
            return None;
        }

        // Must have blank line before
        if !ctx.has_blank_before {
            return None;
        }

        let trimmed = lines.first().trim();

        // Must start with ![
        if !trimmed.starts_with("![") {
            return None;
        }

        // Run the expensive inline-image validation once here.
        let (len, _alt, _dest, _attrs) =
            try_parse_inline_image(trimmed, LinkScanContext::from_options(ctx.config))?;
        let after_image = &trimmed[len..];
        if !after_image.trim().is_empty() {
            return None;
        }

        Some((BlockDetectionResult::Yes, Some(Box::new(len))))
    }

    fn parse_prepared(
        &self,
        ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        payload: Option<&dyn Any>,
    ) -> usize {
        // If detection succeeded, we already validated that this is a standalone image.
        // Payload currently only caches the parsed length (future-proofing).
        let _len = payload.and_then(|p| p.downcast_ref::<usize>().copied());

        let line = lines.raw_at(0);
        parse_figure(builder, line, ctx.config);
        1
    }

    fn name(&self) -> &'static str {
        "figure"
    }
}

/// Reference definition parser ([label]: url "title")
pub(crate) struct ReferenceDefinitionParser;
#[derive(Debug, Clone, Copy)]
struct ReferenceDefinitionPrepared {
    consumed_lines: usize,
}

#[derive(Debug, Clone)]
pub(crate) struct FootnoteDefinitionPrepared {
    pub content_start: usize,
}

#[derive(Debug, Clone)]
pub(crate) struct BlockQuotePrepared {
    pub depth: usize,
    pub marker_info: Vec<crate::parser::utils::marker_utils::BlockQuoteMarkerInfo>,
    #[allow(dead_code)]
    pub inner_content: String,
    pub can_start: bool,
    pub can_nest: bool,
}

#[derive(Debug, Clone)]
pub(crate) struct ListPrepared {
    pub marker: ListMarker,
    pub marker_len: usize,
    pub spaces_after: usize,
    pub spaces_after_cols: usize,
    pub indent_cols: usize,
    pub indent_bytes: usize,
    pub nested_marker: Option<char>,
    pub virtual_marker_space: bool,
}

#[derive(Debug, Clone)]
pub(crate) enum DefinitionPrepared {
    Term {
        blank_count: usize,
    },
    Definition {
        marker_char: char,
        indent: usize,
        spaces_after: usize,
        spaces_after_cols: usize,
        has_content: bool,
    },
}

/// List marker parser
pub(crate) struct ListParser;

/// Definition list parser (term lines and definition markers)
pub(crate) struct DefinitionListParser;

/// Blockquote parser (detection only; core handles emission)
pub(crate) struct BlockQuoteParser;

impl BlockParser for ListParser {
    fn effect(&self) -> BlockEffect {
        BlockEffect::OpenList
    }

    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        let content = lines.first();
        let marker_match = try_parse_list_marker(content, ctx.config, ctx.open_alpha_hint)?;
        let after_marker_text = {
            let (_, indent_bytes) = super::utils::container_stack::leading_indent(content);
            let marker_end = indent_bytes + marker_match.marker_len;
            if marker_end <= content.len() {
                &content[marker_end..]
            } else {
                ""
            }
        };
        if marker_match.spaces_after_cols == 0 {
            // The marker parser allows two cases with zero trailing whitespace:
            // a bare marker (no content after on this line) or a
            // task-checkbox immediately following the marker. Only the bare
            // marker is a real list opener; reject the task-checkbox case.
            // (Trailing CR/LF is not "content" for this check.)
            if !trim_end_newlines(after_marker_text).is_empty() {
                return None;
            }
            // CommonMark: an empty list item cannot interrupt a paragraph at
            // document level. Inside an existing list a bare marker still
            // opens a sibling list item.
            if !ctx.at_document_start && !ctx.has_blank_before && !ctx.in_list {
                return None;
            }
        }
        if !ctx.has_blank_before
            && ctx.in_list
            && matches!(
                marker_match.marker,
                ListMarker::Ordered(OrderedMarker::Decimal {
                    style: ListDelimiter::RightParen,
                    ..
                })
            )
            && after_marker_text.trim() == ")"
        {
            return None;
        }
        if (ctx.has_blank_before
            || ctx.at_document_start
            || ctx.config.dialect == crate::options::Dialect::CommonMark)
            && try_parse_horizontal_rule(content).is_some()
        {
            return None;
        }
        let (indent_cols, indent_bytes) = super::utils::container_stack::leading_indent(content);
        if !ctx.has_blank_before
            && ctx.in_list
            && let Some(list_indent) = ctx.list_indent_info
            && list_indent.content_col >= 4
            && indent_cols == list_indent.content_col
            && indent_cols <= 4
        {
            let should_suppress = match &marker_match.marker {
                ListMarker::Ordered(OrderedMarker::Decimal {
                    number,
                    style: ListDelimiter::Parens | ListDelimiter::Period,
                }) => number != "1",
                ListMarker::Ordered(OrderedMarker::LowerAlpha {
                    style: ListDelimiter::Parens,
                    ..
                })
                | ListMarker::Ordered(OrderedMarker::UpperAlpha {
                    style: ListDelimiter::Parens,
                    ..
                })
                | ListMarker::Ordered(OrderedMarker::LowerRoman {
                    style: ListDelimiter::Parens,
                    ..
                })
                | ListMarker::Ordered(OrderedMarker::UpperRoman {
                    style: ListDelimiter::Parens,
                    ..
                }) => true,
                _ => false,
            };

            if should_suppress {
                return None;
            }
        }

        if indent_cols >= 4 && !ctx.in_list {
            return None;
        }
        if ctx.in_list
            && let Some(list_indent) = ctx.list_indent_info
            && indent_cols >= list_indent.content_col + 4
            && marker_match.spaces_after_cols == 0
            && trim_end_newlines(after_marker_text).is_empty()
        {
            // Empty marker indented 4+ past the parent's content column:
            // pandoc + CommonMark treat this as paragraph continuation, not
            // a nested list. Parsing it as a nested empty bullet causes a
            // formatter idempotency loss (the normalized 2-space indent
            // would re-parse as a setext heading underline). Non-empty
            // markers keep the looser "user-friendly" nested-list
            // recognition for now.
            return None;
        }

        // Pandoc parses `table` before `orderedList` (but `bulletList` before
        // `table`) in its `block` choice (Markdown.hs). So an ordered marker
        // whose line is the header of a valid pipe table is NOT a list: the
        // whole construct is a top-level table that absorbs the marker as the
        // first header cell. Mirror that asymmetry for ordered + pipe only —
        // bullets and grid tables already match pandoc and keep their nesting.
        // `in_list` continuations stay list items (pandoc parses item contents
        // recursively, so `table` runs *inside* the already-open list there).
        // Gated to a fresh block boundary, the same precondition the table
        // parser requires, so declining always falls through to a real table.
        if matches!(marker_match.marker, ListMarker::Ordered(_))
            && !ctx.in_list
            && (ctx.has_blank_before || ctx.at_document_start)
        {
            let mut probe = GreenNodeBuilder::new();
            if try_parse_pipe_table(lines, &mut probe, ctx.config).is_some() {
                return None;
            }
        }

        let nested_marker = is_content_nested_bullet_marker(
            content,
            marker_match.marker_len,
            marker_match.spaces_after_bytes,
        );
        let detection = if ctx.has_blank_before || ctx.at_document_start {
            BlockDetectionResult::Yes
        } else {
            BlockDetectionResult::YesCanInterrupt
        };

        Some((
            detection,
            Some(Box::new(ListPrepared {
                marker: marker_match.marker,
                marker_len: marker_match.marker_len,
                spaces_after: marker_match.spaces_after_bytes,
                spaces_after_cols: marker_match.spaces_after_cols,
                indent_cols,
                indent_bytes,
                nested_marker,
                virtual_marker_space: marker_match.virtual_marker_space,
            })),
        ))
    }

    fn parse_prepared(
        &self,
        _ctx: &BlockContext,
        _builder: &mut GreenNodeBuilder<'static>,
        _lines: &StrippedLines<'_, '_>,
        payload: Option<&dyn Any>,
    ) -> usize {
        let prepared = payload.and_then(|p| p.downcast_ref::<ListPrepared>());
        if prepared.is_none() {
            return 1;
        }

        1
    }

    fn name(&self) -> &'static str {
        "list"
    }
}

impl BlockParser for BlockQuoteParser {
    fn effect(&self) -> BlockEffect {
        BlockEffect::OpenBlockQuote
    }

    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        let line_pos = lines.pos();
        let lines = lines.raw();
        if ctx.blockquote_depth > 0 {
            return None;
        }

        let line = lines.get(line_pos)?;
        let (depth, inner_content) = count_blockquote_markers(line);
        if depth == 0 {
            return None;
        }

        let marker_info = parse_blockquote_marker_info(line);
        let at_document_start = ctx.at_document_start;
        let require_blank_before = ctx.config.extensions.blank_before_blockquote;
        let can_start = !require_blank_before
            || can_start_blockquote(line_pos, lines, ctx.config.extensions.fenced_divs);

        let prev_line = lines.get(line_pos.wrapping_sub(1)).unwrap_or(&"");
        let prev_line_blank = prev_line.trim().is_empty();
        let (prev_depth, prev_inner) = count_blockquote_markers(prev_line);
        let prev_line_is_quoted_blank = prev_depth > 0 && prev_inner.trim().is_empty();

        let can_nest = if require_blank_before {
            depth <= 1 || at_document_start || prev_line_blank || prev_line_is_quoted_blank
        } else {
            true
        };

        let has_blank_before = ctx.has_blank_before;
        let detection = if has_blank_before || at_document_start {
            BlockDetectionResult::Yes
        } else {
            BlockDetectionResult::YesCanInterrupt
        };

        Some((
            detection,
            Some(Box::new(BlockQuotePrepared {
                depth,
                marker_info,
                inner_content: inner_content.to_string(),
                can_start,
                can_nest,
            })),
        ))
    }

    fn parse_prepared(
        &self,
        _ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        _lines: &StrippedLines<'_, '_>,
        payload: Option<&dyn Any>,
    ) -> usize {
        use crate::syntax::SyntaxKind;

        let prepared = payload.and_then(|p| p.downcast_ref::<BlockQuotePrepared>());
        let Some(prepared) = prepared else {
            return 0;
        };

        let marker_info = &prepared.marker_info;

        for level in 0..prepared.depth {
            builder.start_node(SyntaxKind::BLOCK_QUOTE.into());
            if let Some(info) = marker_info.get(level) {
                emit_one_blockquote_marker(builder, info.leading_spaces, info.has_trailing_space);
            }
        }

        0
    }

    fn name(&self) -> &'static str {
        "blockquote"
    }
}

impl BlockParser for DefinitionListParser {
    fn effect(&self) -> BlockEffect {
        BlockEffect::OpenDefinitionList
    }

    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        let content = lines.first();
        let line_pos = lines.pos();
        let prefix = lines.prefix();
        let lines = lines.raw();
        if !ctx.config.extensions.definition_lists {
            return None;
        }

        if let Some((marker_char, indent, spaces_after_cols, spaces_after_bytes)) =
            try_parse_definition_marker(content)
        {
            // If this `:` line is actually a table caption marker and a table
            // follows, let TableParser claim it instead of starting a definition
            // list. The marker above was detected on the container-stripped
            // `content`, so run the caption gate on the same stripped window
            // (not raw `lines`) or a `> : caption` inside a blockquote would
            // slip through this gate.
            if marker_char == ':'
                && ctx.config.extensions.table_captions
                && is_caption_followed_by_table(
                    &StrippedLines::with_dispatch(lines, line_pos, line_pos, prefix),
                    line_pos,
                )
            {
                return None;
            }

            let indent_bytes = super::utils::container_stack::byte_index_at_column(content, indent);
            let has_content = content
                .get(indent_bytes + 1 + spaces_after_bytes..)
                .map(|slice| !slice.trim().is_empty())
                .unwrap_or(false);
            return Some((
                BlockDetectionResult::YesCanInterrupt,
                Some(Box::new(DefinitionPrepared::Definition {
                    marker_char,
                    indent,
                    spaces_after: spaces_after_bytes,
                    spaces_after_cols,
                    has_content,
                })),
            ));
        }

        if let Some(blank_count) = next_line_is_definition_marker(lines, line_pos)
            && !content.trim().is_empty()
        {
            return Some((
                BlockDetectionResult::YesCanInterrupt,
                Some(Box::new(DefinitionPrepared::Term { blank_count })),
            ));
        }

        None
    }

    fn parse_prepared(
        &self,
        _ctx: &BlockContext,
        _builder: &mut GreenNodeBuilder<'static>,
        _lines: &StrippedLines<'_, '_>,
        payload: Option<&dyn Any>,
    ) -> usize {
        let prepared = payload.and_then(|p| p.downcast_ref::<DefinitionPrepared>());
        if prepared.is_none() {
            return 1;
        }

        1
    }

    fn name(&self) -> &'static str {
        "definition_list"
    }
}

/// Footnote definition parser ([^id]: content)
pub(crate) struct FootnoteDefinitionParser;

impl BlockParser for FootnoteDefinitionParser {
    fn effect(&self) -> BlockEffect {
        BlockEffect::OpenFootnoteDefinition
    }

    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        if !ctx.config.extensions.footnotes {
            return None;
        }

        let content = lines.first();
        // A footnote def starts with `[^` after no leading indent.
        if !content.starts_with("[^") {
            return None;
        }

        let (_id, content_start) = try_parse_footnote_marker(content)?;
        Some((
            BlockDetectionResult::YesCanInterrupt,
            Some(Box::new(FootnoteDefinitionPrepared { content_start })),
        ))
    }

    fn parse_prepared(
        &self,
        ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        payload: Option<&dyn Any>,
    ) -> usize {
        use crate::syntax::SyntaxKind;

        let content = lines.first();
        let prepared = payload.and_then(|p| p.downcast_ref::<FootnoteDefinitionPrepared>());
        let content_start = prepared
            .map(|p| p.content_start)
            .or_else(|| try_parse_footnote_marker(content).map(|(_, pos)| pos));

        let Some(content_start) = content_start else {
            return 1;
        };

        if let Some(indent_str) = ctx.indent_to_emit {
            builder.token(SyntaxKind::WHITESPACE.into(), indent_str);
        }

        builder.start_node(SyntaxKind::FOOTNOTE_DEFINITION.into());
        let marker_text = &content[..content_start];
        if let Some((id, _)) = try_parse_footnote_marker(marker_text) {
            builder.token(SyntaxKind::FOOTNOTE_LABEL_START.into(), "[^");
            builder.token(SyntaxKind::FOOTNOTE_LABEL_ID.into(), &id);
            builder.token(SyntaxKind::FOOTNOTE_LABEL_END.into(), "]");
            builder.token(SyntaxKind::FOOTNOTE_LABEL_COLON.into(), ":");
            let marker_suffix = marker_text
                .strip_prefix("[^")
                .and_then(|tail| tail.strip_prefix(id.as_str()))
                .and_then(|tail| tail.strip_prefix("]:"))
                .unwrap_or("");
            if !marker_suffix.is_empty() {
                builder.token(SyntaxKind::WHITESPACE.into(), marker_suffix);
            }
        } else {
            builder.token(SyntaxKind::FOOTNOTE_REFERENCE.into(), marker_text);
        }

        1
    }

    fn name(&self) -> &'static str {
        "footnote_definition"
    }
}

impl BlockParser for ReferenceDefinitionParser {
    fn effect(&self) -> BlockEffect {
        BlockEffect::None
    }

    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        let content = lines.first();
        let line_pos = lines.pos();
        let lines = lines.raw();
        if !ctx.config.extensions.reference_links {
            return None;
        }

        // Cheap leading-byte gate: a reference definition starts with `[`
        // after up to 3 leading spaces (CommonMark §4.7). Bail before the
        // multi-line String::new() build below if the gate fails — this
        // is the by-far common case on a typical doc.
        {
            let bytes = content.as_bytes();
            let mut i = 0;
            while i < bytes.len() && i < 3 && bytes[i] == b' ' {
                i += 1;
            }
            if bytes.get(i) != Some(&b'[') {
                return None;
            }
        }

        // Build a multi-line candidate from consecutive non-blank lines so the
        // ref-def parser can recognize destinations and titles that wrap across
        // lines (CommonMark §4.7). Blank lines terminate the definition, so we
        // stop the input there.
        //
        // Inside blockquotes, the raw `lines` carry the `>` markers. The
        // dispatcher already strips them into `lines.first()`, but a
        // multi-line join here would feed those markers back to the parser.
        // Fall back to a single-line attempt in that case — multi-line ref
        // defs inside blockquotes are tracked separately.
        type RefDefParseFn =
            fn(&str, crate::options::Dialect) -> Option<(usize, String, String, Option<String>)>;
        let parse_fn: RefDefParseFn = if ctx.config.extensions.mmd_link_attributes {
            try_parse_reference_definition_lax
        } else {
            try_parse_reference_definition
        };
        let dialect = ctx.config.dialect;

        let consumed = if ctx.blockquote_depth > 0 {
            parse_fn(content, dialect)?;
            1usize
        } else {
            let mut multi = String::new();
            let mut joined_lines = 0usize;
            for line in lines.iter().skip(line_pos) {
                if line.trim().is_empty() {
                    break;
                }
                multi.push_str(line);
                joined_lines += 1;
            }
            if joined_lines == 0 {
                return None;
            }

            let (bytes_consumed, _label, _url, _title) = parse_fn(&multi, dialect)?;

            let mut consumed = 0usize;
            let mut byte_cursor = 0usize;
            for line in lines.iter().skip(line_pos).take(joined_lines) {
                if byte_cursor >= bytes_consumed {
                    break;
                }
                byte_cursor += line.len();
                consumed += 1;
            }
            if consumed == 0 {
                consumed = 1;
            }
            consumed
        };

        let mut consumed = consumed;

        if ctx.config.extensions.mmd_link_attributes {
            let mut i = line_pos + consumed;
            while i < lines.len() {
                let line = lines[i];

                if line.trim().is_empty() {
                    break;
                }
                if line_is_mmd_link_attribute_continuation(line) {
                    consumed += 1;
                    i += 1;
                    continue;
                }
                break;
            }
        }

        Some((
            BlockDetectionResult::Yes,
            Some(Box::new(ReferenceDefinitionPrepared {
                consumed_lines: consumed,
            })),
        ))
    }

    fn parse_prepared(
        &self,
        ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        payload: Option<&dyn Any>,
    ) -> usize {
        use crate::syntax::SyntaxKind;

        let content = lines.first();
        let line_pos = lines.pos();
        let lines = lines.raw();

        builder.start_node(SyntaxKind::REFERENCE_DEFINITION.into());

        let consumed_lines = payload
            .and_then(|p| p.downcast_ref::<ReferenceDefinitionPrepared>())
            .map(|p| p.consumed_lines)
            .unwrap_or(1);

        // The destination/title byte spans come from the same walker detection
        // used, so the structured `REFERENCE_URL` / `REFERENCE_TITLE` nodes wrap
        // exactly the bytes detection recognized (no detect/emit drift).
        let strict_eol = !ctx.config.extensions.mmd_link_attributes;
        let dialect = ctx.config.dialect;

        // Inside a blockquote, BLOCK_QUOTE_MARKER + WHITESPACE were already
        // emitted by the dispatcher; using lines[line_pos] would duplicate the
        // `>` marker (CST losslessness violation). detect_prepared restricts
        // blockquote-context defs to a single line, so we can rely on
        // the bq-stripped first line here.
        if ctx.blockquote_depth > 0 {
            let single = [content];
            let spans = reference_definition_spans(content, strict_eol, dialect);
            emit_reference_definition_lines(builder, &single, spans);
        } else {
            let target_lines: Vec<&str> = lines
                .iter()
                .skip(line_pos)
                .take(consumed_lines)
                .copied()
                .collect();
            let joined: String = target_lines.concat();
            let spans = reference_definition_spans(&joined, strict_eol, dialect);
            emit_reference_definition_lines(builder, &target_lines, spans);
        }

        builder.finish_node();

        consumed_lines
    }

    fn name(&self) -> &'static str {
        "reference_definition"
    }
}

// ============================================================================
// Table Parser (position #10)
// ============================================================================

pub(crate) struct TableParser;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TableKind {
    Grid,
    Multiline,
    Pipe,
    Simple,
}

#[derive(Debug, Clone)]
struct TablePrepared {
    /// The table subtree built during detection. Emission replays this verbatim
    /// (`copy_green_node`) instead of re-parsing — losslessness is guaranteed by
    /// construction since the exact bytes detection validated are what we emit.
    green: rowan::GreenNode,
    /// Lines the table spans, returned to the dispatcher by emission.
    consumed: usize,
}

/// Line index where the table grid begins: past a leading caption (its
/// continuation lines plus one optional blank) when `table_captions` applies,
/// else `line_pos` itself.
///
/// Runs caption detection and the blank-line skip on the container-stripped
/// window (anchored at `line_pos`), not the raw lines. Inside a blockquote/list
/// the raw caption line is `> Table: …` (or `> ` for the blank), which fails the
/// caption-start check and reads as non-blank; the stripped view sees the bare
/// `Table: …`/empty line. Multiline detection only recognizes a caption-led
/// table when dispatched at the border, so getting this right is what keeps a
/// caption-before multiline table in a blockquote from leaking into a paragraph.
fn resolve_table_pos(
    ctx: &BlockContext,
    raw: &[&str],
    line_pos: usize,
    prefix: &ContainerPrefix,
) -> usize {
    if !ctx.config.extensions.table_captions {
        return line_pos;
    }
    let window = StrippedLines::with_dispatch(raw, line_pos, line_pos, prefix);
    if !is_caption_followed_by_table(&window, line_pos) {
        return line_pos;
    }
    let mut pos = line_pos + 1;
    while pos < raw.len() && !window.strip_at(pos).trim().is_empty() {
        pos += 1;
    }
    if pos < raw.len() && window.strip_at(pos).trim().is_empty() {
        pos += 1;
    }
    pos
}

/// Parse a single table `kind` at `pos` (anchored at `dispatch`) into `builder`,
/// gated on the matching extension flag. The single per-kind dispatch shared by
/// detection and emission.
fn try_parse_kind(
    ctx: &BlockContext,
    kind: TableKind,
    raw: &[&str],
    pos: usize,
    dispatch: usize,
    prefix: &ContainerPrefix,
    builder: &mut GreenNodeBuilder<'static>,
) -> Option<usize> {
    let window = StrippedLines::with_dispatch(raw, pos, dispatch, prefix);
    match kind {
        TableKind::Grid if ctx.config.extensions.grid_tables => {
            try_parse_grid_table(&window, builder, ctx.config)
        }
        TableKind::Multiline if ctx.config.extensions.multiline_tables => {
            try_parse_multiline_table(&window, builder, ctx.config)
        }
        TableKind::Pipe if ctx.config.extensions.pipe_tables => {
            try_parse_pipe_table(&window, builder, ctx.config)
        }
        TableKind::Simple if ctx.config.extensions.simple_tables => {
            try_parse_simple_table(&window, builder, ctx.config)
        }
        _ => None,
    }
}

/// Try each table kind (Grid → Multiline → Pipe → Simple) at `pos`, anchored at
/// `dispatch`, parsing the first match into `builder`. Returns the matched kind
/// and the line count consumed. The single home for the kind cascade; callers
/// pick the position-ordering policy.
fn first_kind_at(
    ctx: &BlockContext,
    raw: &[&str],
    pos: usize,
    dispatch: usize,
    prefix: &ContainerPrefix,
    builder: &mut GreenNodeBuilder<'static>,
) -> Option<(TableKind, usize)> {
    for kind in [
        TableKind::Grid,
        TableKind::Multiline,
        TableKind::Pipe,
        TableKind::Simple,
    ] {
        if let Some(consumed) = try_parse_kind(ctx, kind, raw, pos, dispatch, prefix, builder) {
            return Some((kind, consumed));
        }
    }
    None
}

/// Parse a known `kind` into `builder` using emission's position policy: the
/// dispatch line first (so a leading caption is included), then the resolved
/// grid position. Shared by detection's caption-capture path and the (rare)
/// payload-missing fallback's per-kind needs.
fn emit_table_kind(
    ctx: &BlockContext,
    kind: TableKind,
    raw: &[&str],
    line_pos: usize,
    table_pos: usize,
    prefix: &ContainerPrefix,
    builder: &mut GreenNodeBuilder<'static>,
) -> Option<usize> {
    if let Some(n) = try_parse_kind(ctx, kind, raw, line_pos, line_pos, prefix, builder) {
        return Some(n);
    }
    if table_pos != line_pos
        && let Some(n) = try_parse_kind(ctx, kind, raw, table_pos, line_pos, prefix, builder)
    {
        return Some(n);
    }
    None
}

impl BlockParser for TableParser {
    fn effect(&self) -> BlockEffect {
        BlockEffect::None
    }

    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        let line_pos = lines.pos();
        let prefix = lines.prefix();
        let lines = lines.raw();
        if !ctx.has_blank_before && !ctx.at_document_start {
            return None;
        }

        if !(ctx.config.extensions.simple_tables
            || ctx.config.extensions.multiline_tables
            || ctx.config.extensions.grid_tables
            || ctx.config.extensions.pipe_tables)
        {
            return None;
        }

        // Correctness first: only claim a match if a real parse would succeed.
        // (Otherwise we can steal list items/paragraphs and drop content.)
        let detection = if ctx.has_blank_before || ctx.at_document_start {
            BlockDetectionResult::Yes
        } else {
            BlockDetectionResult::YesCanInterrupt
        };

        // Caption-before-table lines match the *table kind* starting after the
        // caption (`table_pos`), but parse from the caption line so the caption
        // is included and consumed. `resolve_table_pos` owns that routing.
        let table_pos = resolve_table_pos(ctx, lines, line_pos, prefix);

        // Selection policy unchanged: cascade at the grid position to pick the
        // kind. We keep the resulting subtree so emission replays it instead of
        // re-parsing (the table was parsed twice before). In the common
        // no-caption case the cascade parses at `line_pos == table_pos`, which
        // *is* emission's first attempt, so the tree is exactly what emission
        // would build — reuse it directly. With a leading caption the cascade
        // parses at the post-caption grid line (omitting the caption), so
        // re-capture via the emission position policy to include it.
        let mut probe = GreenNodeBuilder::new();
        let (kind, probe_consumed) =
            first_kind_at(ctx, lines, table_pos, line_pos, prefix, &mut probe)?;

        let (green, consumed) = if table_pos == line_pos {
            (probe.finish(), probe_consumed)
        } else {
            let mut b = GreenNodeBuilder::new();
            let consumed = emit_table_kind(ctx, kind, lines, line_pos, table_pos, prefix, &mut b)?;
            (b.finish(), consumed)
        };

        Some((detection, Some(Box::new(TablePrepared { green, consumed }))))
    }

    fn parse_prepared(
        &self,
        ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        payload: Option<&dyn Any>,
    ) -> usize {
        // Happy path: replay the subtree detection already built and validated.
        // No re-parse — `copy_green_node` copies its tokens verbatim, so the
        // emitted bytes match detection exactly (lossless by construction).
        if let Some(p) = payload.and_then(|p| p.downcast_ref::<TablePrepared>()) {
            copy_green_node(builder, &p.green);
            return p.consumed;
        }

        let line_pos = lines.pos();
        let prefix = lines.prefix();
        let lines = lines.raw();
        let table_pos = resolve_table_pos(ctx, lines, line_pos, prefix);

        // Fallback (defensive): payload missing. Re-run the cascade at the
        // caption line, then post-caption.
        if let Some((_, n)) = first_kind_at(ctx, lines, line_pos, line_pos, prefix, builder) {
            return n;
        }
        if table_pos != line_pos
            && let Some((_, n)) = first_kind_at(ctx, lines, table_pos, line_pos, prefix, builder)
        {
            return n;
        }

        debug_assert!(false, "TableParser::parse called without a matching table");
        1
    }

    fn name(&self) -> &'static str {
        "table"
    }
}

/// Emit a (possibly multi-line) reference definition's content tokens with
/// full inline structure:
/// `WHITESPACE? LINK<LINK_START "[", LINK_TEXT, "]"> TEXT(":") sep
///  REFERENCE_URL sep REFERENCE_TITLE? trailing`.
///
/// The destination/title byte ranges come from `spans` —
/// [`reference_definition_spans`], the same walker detection uses — so the
/// `REFERENCE_URL` / `REFERENCE_TITLE` nodes wrap exactly the bytes detection
/// recognized and the two phases never drift. The LINK_TEXT may span multiple
/// lines via interleaved TEXT/NEWLINE tokens when the label wraps
/// (e.g. `[Foo\n  bar]: /url`, CommonMark example #541).
///
/// When `spans` is `None` (the dispatcher only calls this after a successful
/// detection, so this is defensive), each input line is emitted verbatim via
/// `emit_line_tokens` to preserve CST losslessness.
fn emit_reference_definition_lines(
    builder: &mut GreenNodeBuilder<'static>,
    lines: &[&str],
    spans: Option<ReferenceSpans>,
) {
    use crate::parser::utils::helpers::emit_line_tokens;
    use crate::syntax::SyntaxKind;

    if lines.is_empty() {
        return;
    }

    let Some(spans) = spans else {
        for line in lines {
            emit_line_tokens(builder, line);
        }
        return;
    };

    // Emit a whitespace/newline-only separator run as standalone WHITESPACE and
    // NEWLINE tokens (the bytes between `:`→url and url→title are guaranteed
    // whitespace + at most one line ending by `skip_ws_one_newline`).
    fn emit_separator(builder: &mut GreenNodeBuilder<'static>, seg: &str) {
        let bytes = seg.as_bytes();
        let mut i = 0;
        while i < bytes.len() {
            match bytes[i] {
                b'\n' => {
                    builder.token(SyntaxKind::NEWLINE.into(), "\n");
                    i += 1;
                }
                b'\r' => {
                    let n = if i + 1 < bytes.len() && bytes[i + 1] == b'\n' {
                        2
                    } else {
                        1
                    };
                    builder.token(SyntaxKind::NEWLINE.into(), &seg[i..i + n]);
                    i += n;
                }
                _ => {
                    let start = i;
                    while i < bytes.len() && bytes[i] != b'\n' && bytes[i] != b'\r' {
                        i += 1;
                    }
                    builder.token(SyntaxKind::WHITESPACE.into(), &seg[start..i]);
                }
            }
        }
    }

    // Emit a text region, splitting line endings into NEWLINE tokens and
    // everything else into TEXT runs (no empty TEXT tokens). Used for a
    // multi-line label and for the trailing remainder (EOL + any MMD
    // attribute-continuation lines).
    fn emit_text_lines(builder: &mut GreenNodeBuilder<'static>, seg: &str) {
        let bytes = seg.as_bytes();
        let mut i = 0;
        let mut start = 0;
        while i < bytes.len() {
            match bytes[i] {
                b'\n' => {
                    if i > start {
                        builder.token(SyntaxKind::TEXT.into(), &seg[start..i]);
                    }
                    builder.token(SyntaxKind::NEWLINE.into(), "\n");
                    i += 1;
                    start = i;
                }
                b'\r' => {
                    if i > start {
                        builder.token(SyntaxKind::TEXT.into(), &seg[start..i]);
                    }
                    let n = if i + 1 < bytes.len() && bytes[i + 1] == b'\n' {
                        2
                    } else {
                        1
                    };
                    builder.token(SyntaxKind::NEWLINE.into(), &seg[i..i + n]);
                    i += n;
                    start = i;
                }
                _ => i += 1,
            }
        }
        if start < bytes.len() {
            builder.token(SyntaxKind::TEXT.into(), &seg[start..]);
        }
    }

    let joined: String = lines.concat();
    let s = &joined[..];

    // Leading indent (0..=3 spaces).
    if spans.indent > 0 {
        builder.token(SyntaxKind::WHITESPACE.into(), &s[..spans.indent]);
    }

    // LINK<LINK_START "[", LINK_TEXT, "]">
    builder.start_node(SyntaxKind::LINK.into());

    builder.start_node(SyntaxKind::LINK_START.into());
    builder.token(SyntaxKind::LINK_START.into(), "[");
    builder.finish_node();

    builder.start_node(SyntaxKind::LINK_TEXT.into());
    emit_text_lines(builder, &s[spans.indent + 1..spans.label_close]);
    builder.finish_node();

    builder.token(SyntaxKind::TEXT.into(), "]");
    builder.finish_node(); // LINK

    // Colon, then separator up to the destination.
    builder.token(SyntaxKind::TEXT.into(), ":");
    emit_separator(builder, &s[spans.colon + 1..spans.url.start]);

    // REFERENCE_URL — angle brackets kept inside as their own delimiter tokens.
    builder.start_node(SyntaxKind::REFERENCE_URL.into());
    if spans.url_is_angle {
        builder.token(SyntaxKind::LINK_DEST_START.into(), "<");
        let inner = &s[spans.url.start + 1..spans.url.end - 1];
        if !inner.is_empty() {
            builder.token(SyntaxKind::TEXT.into(), inner);
        }
        builder.token(SyntaxKind::LINK_DEST_END.into(), ">");
    } else {
        builder.token(SyntaxKind::TEXT.into(), &s[spans.url.clone()]);
    }
    builder.finish_node(); // REFERENCE_URL

    let last_end = if let Some(title) = spans.title.clone() {
        emit_separator(builder, &s[spans.url.end..title.start]);
        builder.start_node(SyntaxKind::REFERENCE_TITLE.into());
        builder.token(SyntaxKind::TEXT.into(), &s[title.clone()]);
        builder.finish_node(); // REFERENCE_TITLE
        title.end
    } else {
        spans.url.end
    };

    // Trailing EOL plus any MMD attribute-continuation lines, verbatim.
    emit_text_lines(builder, &s[last_end..]);
}

/// Fenced code block parser (``` or ~~~)
pub(crate) struct FencedCodeBlockParser;

impl BlockParser for FencedCodeBlockParser {
    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        let content = lines.first();
        let line_pos = lines.pos();
        let lines = lines.raw();
        // Calculate content to check - may need to strip list indentation
        let content_to_check = if let Some(list_info) = ctx.list_indent_info {
            if list_info.content_col > 0 && !content.is_empty() {
                let idx = byte_index_at_column(content, list_info.content_col);
                &content[idx..]
            } else {
                content
            }
        } else {
            content
        };

        let fence = try_parse_fence_open(content_to_check, ctx.config.dialect)?;
        if (fence.fence_char == '`' && !ctx.config.extensions.backtick_code_blocks)
            || (fence.fence_char == '~' && !ctx.config.extensions.fenced_code_blocks)
        {
            return None;
        }

        // Brace-delimited info strings (`{...}`) carry Pandoc attribute
        // semantics — executable chunks, raw blocks, and attribute lists — each
        // gated behind its extension. In the CommonMark dialect braces have no
        // special meaning: the info string is opaque and the fence still opens a
        // plain code block, so none of these rejections apply (matches pandoc's
        // `commonmark`/`gfm` readers, which treat ```` ```{code-cell} ```` as a
        // code block with class `{code-cell}`).
        if ctx.config.dialect == crate::options::Dialect::Pandoc {
            let trimmed_info = fence.info_string.trim();
            if trimmed_info.starts_with('{') && trimmed_info.ends_with('}') {
                if trimmed_info.starts_with("{=") {
                    if !ctx.config.extensions.raw_attribute {
                        return None;
                    }
                } else if !ctx.config.extensions.fenced_code_attributes {
                    return None;
                }
            }

            // Parse info string to determine block type (expensive, but now cached via fence)
            let info = InfoString::parse(&fence.info_string);

            let is_executable = matches!(info.block_type, CodeBlockType::Executable { .. });
            if is_executable && !ctx.config.extensions.executable_code {
                return None;
            }
        }

        // Fenced code blocks can interrupt paragraphs if they have an info string.
        // For bare fences (```), allow interruption only in explicit transcript-like
        // contexts and only when a matching closer exists later.
        let has_info = !fence.info_string.trim().is_empty();
        let has_matching_closer = {
            let mut found = false;
            let container_content_col = ctx.content_indent
                + ctx
                    .list_indent_info
                    .map(|list_info| list_info.content_col)
                    .unwrap_or(0);
            for raw_line in lines.iter().skip(line_pos + 1) {
                let (line_bq_depth, inner) = count_blockquote_markers(raw_line);
                if line_bq_depth < ctx.blockquote_depth {
                    break;
                }
                let candidate = if container_content_col > 0 && !inner.is_empty() {
                    let idx = byte_index_at_column(inner, container_content_col);
                    if idx <= inner.len() {
                        &inner[idx..]
                    } else {
                        inner
                    }
                } else {
                    inner
                };
                if is_closing_fence(candidate, &fence) {
                    found = true;
                    break;
                }
            }
            found
        };

        // CommonMark dialect: fenced code blocks always interrupt paragraphs and
        // run to end-of-document if the closing fence is missing (spec §4.5).
        // Pandoc dialect: bare fences without a closer fall through to a paragraph.
        let common_mark_dialect = ctx.config.dialect == crate::options::Dialect::CommonMark;
        if !has_matching_closer && !common_mark_dialect {
            return None;
        }

        let next_nonblank_is_command = lines
            .iter()
            .skip(line_pos + 1)
            .find(|l| !l.trim().is_empty())
            .is_some_and(|l| l.trim_start().starts_with('%'));
        let bare_fence_before_command_with_closer = has_matching_closer && next_nonblank_is_command;
        let bare_fence_after_colon_with_closer = has_matching_closer
            && next_nonblank_is_command
            && line_pos > 0
            && lines[line_pos - 1].trim_end().ends_with(':');
        let bare_fence_in_list_with_closer = has_matching_closer && ctx.list_indent_info.is_some();
        let bare_fence_after_matching_closer = has_matching_closer
            && next_nonblank_is_command
            && line_pos > 0
            && is_closing_fence(lines[line_pos - 1], &fence);

        // In Pandoc dialect, tilde fences require a blank line before — they
        // never interrupt a paragraph. CommonMark allows tilde fences with
        // info strings to interrupt paragraphs (spec §4.5).
        let tilde_requires_blank_before = fence.fence_char == '~' && !common_mark_dialect;

        let detection = if tilde_requires_blank_before {
            if ctx.has_blank_before {
                BlockDetectionResult::Yes
            } else {
                BlockDetectionResult::No
            }
        } else if has_info
            || bare_fence_before_command_with_closer
            || bare_fence_after_colon_with_closer
            || bare_fence_in_list_with_closer
            || bare_fence_after_matching_closer
            || common_mark_dialect
        {
            BlockDetectionResult::YesCanInterrupt
        } else if ctx.has_blank_before {
            BlockDetectionResult::Yes
        } else {
            BlockDetectionResult::No
        };

        match detection {
            BlockDetectionResult::No => None,
            _ => Some((detection, Some(Box::new(fence)))),
        }
    }

    fn parse_prepared(
        &self,
        ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        payload: Option<&dyn Any>,
    ) -> usize {
        let content = lines.first();
        let line_pos = lines.pos();
        let list_indent_stripped = ctx.list_indent_info.map(|i| i.content_col).unwrap_or(0);

        let fence = if let Some(fence) = payload.and_then(|p| p.downcast_ref::<FenceInfo>()) {
            fence.clone()
        } else {
            let content_to_check = if list_indent_stripped > 0 && !content.is_empty() {
                let idx = byte_index_at_column(content, list_indent_stripped);
                &content[idx..]
            } else {
                content
            };
            try_parse_fence_open(content_to_check, ctx.config.dialect).expect("Fence should exist")
        };

        // All container geometry travels inside the window's prefix; the
        // parse functions derive `bq_depth`/`list_content_col`/`bq_outer`/
        // `content_indent`/`list_marker_consumed_on_line_0` from it.
        let new_pos = if ctx.config.extensions.tex_math_gfm && is_gfm_math_fence(&fence) {
            parse_fenced_math_block(builder, lines, fence, None)
        } else {
            parse_fenced_code_block(builder, lines, fence, None, &ctx.diags, ctx.config.flavor)
        };

        new_pos - line_pos
    }

    fn name(&self) -> &'static str {
        "fenced_code_block"
    }
}

// ============================================================================
// HTML Block Parser (position #9)
// ============================================================================

/// Whether the leading `<script ...>` open tag in `content` has a
/// `type` attribute whose value starts with `math/tex` (case-insensitive).
/// Mirrors pandoc's `isInlineTag` special case for `<script>` opens:
/// only the `math/tex…` flavor is treated as inline mid-paragraph;
/// every other `<script>` open is a `RawBlock` start.
fn is_math_tex_script_open(content: &str) -> bool {
    let trimmed = content.trim_start();
    if !trimmed
        .get(..7)
        .is_some_and(|s| s.eq_ignore_ascii_case("<script"))
    {
        return false;
    }
    let Some(attrs) = parse_html_tag_attributes(trimmed) else {
        return false;
    };
    attrs.key_values.iter().any(|(k, v)| {
        k.eq_ignore_ascii_case("type") && v.to_ascii_lowercase().starts_with("math/tex")
    })
}

/// Whether an HTML block start cannot interrupt a running paragraph under the
/// given dialect (pandoc's `isInlineTag` set, plus the issue-#10643 special
/// cases). `content` is the raw (bq/list-indent-stripped) first line, needed
/// for the `<script type="math/tex…">` attribute probe. Shared between the
/// block dispatcher and the footnote-body marker-line HTML dispatch, which
/// lifts only tags that CAN interrupt (i.e. `!cannot_interrupt`).
pub(crate) fn html_block_cannot_interrupt(
    block_type: &HtmlBlockType,
    content: &str,
    is_pandoc: bool,
) -> bool {
    matches!(block_type, HtmlBlockType::Type7)
        || (matches!(block_type, HtmlBlockType::Comment) && is_pandoc)
        || (matches!(block_type, HtmlBlockType::ProcessingInstruction) && is_pandoc)
        || (is_pandoc
            && matches!(block_type, HtmlBlockType::BlockTag { tag_name, is_closing, .. }
                if is_pandoc_inline_block_tag_name(tag_name)
                    || is_pandoc_void_block_tag_name(tag_name)
                    || tag_name.eq_ignore_ascii_case("style")
                    || (*is_closing && tag_name.eq_ignore_ascii_case("script"))
                    || (!*is_closing
                        && tag_name.eq_ignore_ascii_case("script")
                        && is_math_tex_script_open(content))))
}

pub(crate) struct HtmlBlockParser;

impl BlockParser for HtmlBlockParser {
    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        let content = lines.first();
        let prefix = lines.prefix();
        let line_pos = lines.pos();
        let lines = lines.raw();
        if !ctx.config.extensions.raw_html {
            return None;
        }

        // HTML block must start with `<` after up to 3 leading spaces.
        {
            let bytes = content.as_bytes();
            let mut i = 0;
            while i < bytes.len() && i < 3 && bytes[i] == b' ' {
                i += 1;
            }
            if bytes.get(i) != Some(&b'<') {
                return None;
            }
        }

        let is_commonmark = ctx.config.dialect == crate::options::Dialect::CommonMark;
        let block_type = try_parse_html_block_start(content, is_commonmark)?;

        // Pandoc-only: suppress close-form dispatch when the enclosing
        // LIST_ITEM buffer has an unclosed matched-pair open of the same
        // tag name. Without this, the dispatcher recognizes `</div>` /
        // `</section>` / `</pre>` mid-list-item as a separate block start,
        // which flushes the LIST_ITEM buffer mid-stream and produces
        // `Plain[RawInline <tag>, body, RawInline </tag>]` for the
        // open-side plus a sibling RawBlock for the close. By returning
        // None here, the line falls through to buffer continuation; at
        // emit time `ListItemBuffer::emit_as_block` sees the full matched-
        // pair text and grafts a single lifted HTML block. Same-line and
        // top-level cases are unaffected (no LIST_ITEM container, or the
        // buffer has zero unclosed opens).
        if let HtmlBlockType::BlockTag {
            tag_name,
            is_closing: true,
            ..
        } = &block_type
            && ctx.list_item_unclosed_html_block_tag.as_deref()
                == Some(tag_name.to_ascii_lowercase().as_str())
        {
            return None;
        }

        // Pandoc-only: validate that the open tag is syntactically complete
        // (an unquoted `>` exists somewhere from the `<` onward, possibly
        // spanning later lines). Pandoc-native treats incomplete open tags
        // (`<embed\n`, `<div\n`, `<table\n` with no `>`) as paragraph text;
        // recognizing them as `RawBlock` makes the projector reparse the
        // same bytes and infinite-recurse. CommonMark dialect deliberately
        // accepts incomplete type-6 open tags (`<table\n` is a `RawBlock`),
        // so the validation is gated on Pandoc dialect and BlockTag types.
        if !is_commonmark
            && matches!(block_type, HtmlBlockType::BlockTag { .. })
            && !pandoc_html_open_tag_closes(lines, line_pos, prefix)
        {
            return None;
        }

        // Type 7 cannot interrupt a paragraph (CommonMark §4.6). Other
        // types can. Pandoc-dialect additionally treats HTML comments as
        // non-interrupting: a comment line directly following a paragraph
        // line (no blank above) stays inline as `RawInline (Format "html")`
        // rather than splitting the paragraph into a `RawBlock`. The
        // Pandoc `eitherBlockOrInline` tags (`<iframe>`, `<button>`,
        // `<video>`, …) and their void siblings (`<embed>`, `<area>`,
        // `<source>`, `<track>`) likewise never interrupt a running
        // paragraph — pandoc keeps them inline once a paragraph has
        // started parsing (verified: `Some text\n<button>X</button>\n`
        // and `leading text\n<embed src="x">\nmore text\n` both
        // project as a single Para with the tag as RawInline).
        //
        // The non-interrupt set mirrors pandoc's `isInlineTag` predicate
        // (`pandoc/src/Text/Pandoc/Readers/HTML.hs`): tags where
        // `isInlineTag` returns True are consumable by the inline parser
        // mid-paragraph, so pandoc's `para` keeps them in the running
        // paragraph instead of terminating. The relevant rules:
        //   - `eitherBlockOrInline` tags (notMember of `blockTags`) are
        //     inline — covered by the inline-block / void-block checks
        //     below.
        //   - `<style>` open and close are SPECIAL-CASED to always be
        //     inline (pandoc commit fixing issue #10643), regardless of
        //     `style` being in `blockHtmlTags`.
        //   - `</script>` close is similarly special-cased to always be
        //     inline. `<script>` open is inline only when its `type`
        //     attribute starts with `math/tex` (case-insensitive prefix
        //     match on 8 chars, e.g. `math/tex`, `math/tex; mode=display`).
        //   - PIs (`<? … ?>`) and HTML comments are inline.
        // `<pre>`, `<textarea>`, and `<script>` open without `type="math/tex…"`
        // DO interrupt — they're in `blockTags` and have no `isInlineTag`
        // override.
        let is_pandoc = ctx.config.dialect == crate::options::Dialect::Pandoc;
        let cannot_interrupt = html_block_cannot_interrupt(&block_type, content, is_pandoc);
        // Pandoc-specific: when an `isInlineTag` construct (the
        // `cannot_interrupt` set) appears with leading indent BEYOND
        // the current container's content_col, pandoc-native treats
        // it as inline-in-paragraph instead of an HTML block. We
        // return None so the dispatcher falls through to paragraph
        // parsing, where the inline parser handles the tag as
        // `RawInline`. Blockquote markers are already stripped from
        // the bq-stripped first line; for list-items,
        // `list_indent_info.content_col` is the column we treat as
        // "column 0" within the item. CommonMark keeps the RawBlock
        // shape (block-level recognition).
        if is_pandoc && cannot_interrupt {
            let leading_spaces = content
                .as_bytes()
                .iter()
                .take_while(|&&b| b == b' ')
                .count();
            let container_col = ctx.list_indent_info.map(|i| i.content_col).unwrap_or(0);
            if leading_spaces > container_col {
                return None;
            }
        }
        let detection = if cannot_interrupt {
            if ctx.has_blank_before || ctx.at_document_start {
                BlockDetectionResult::Yes
            } else {
                return None;
            }
        } else if ctx.has_blank_before || ctx.at_document_start {
            BlockDetectionResult::Yes
        } else {
            BlockDetectionResult::YesCanInterrupt
        };

        Some((detection, Some(Box::new(block_type))))
    }

    fn parse_prepared(
        &self,
        ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        payload: Option<&dyn Any>,
    ) -> usize {
        let content = lines.first();
        let prefix = lines.prefix();
        let line_pos = lines.pos();
        let lines = lines.raw();
        let is_commonmark = ctx.config.dialect == crate::options::Dialect::CommonMark;
        let block_type = if let Some(bt) = payload.and_then(|p| p.downcast_ref::<HtmlBlockType>()) {
            bt.clone()
        } else {
            try_parse_html_block_start(content, is_commonmark)
                .expect("HTML block type should exist")
        };

        // Pandoc-dialect div lift: when the block opens with a
        // `<div ...>` tag, retag the wrapper as HTML_BLOCK_DIV so the
        // projector emits Block::Div and the salsa anchor index can read
        // the open tag's id. CST bytes stay identical — only the wrapper
        // kind changes. CommonMark dialect keeps the opaque HTML_BLOCK
        // shape.
        //
        // Retag is gated on `pandoc_html_open_tag_closes`: the structural
        // body lift requires the open tag's `>` to actually appear before
        // EOF. Multi-line opens with trailing on the close-`>` line now
        // also retag — `emit_multiline_open_tag_with_attrs` captures the
        // trailing bytes into `pre_content` (with `lift_trailing=true`)
        // so the open `HTML_BLOCK_TAG` ends cleanly with `TEXT(">")` and
        // `html_block_open_tag_is_clean` accepts. Incomplete opens
        // (`<div\n` no `>` anywhere) keep the opaque `HTML_BLOCK` shape
        // so the projector treats them as paragraph text per pandoc-native.
        //
        // Standalone closing forms (`</div>` with no matched open) keep
        // the opaque `HTML_BLOCK` shape so the projector emits a single
        // `RawBlock "html" "</div>"` (matching pandoc-native) rather than
        // an empty `Div` with a stale close-only structural shape — the
        // close-form `HtmlBlockType::BlockTag` carries `is_closing: true`,
        // and `pandoc_html_open_tag_closes` returns true for `</div>`
        // since the line has a `>`, so without this guard the close would
        // wrongly retag.
        let wrapper_kind = match &block_type {
            HtmlBlockType::BlockTag {
                tag_name,
                is_closing: false,
                ..
            } if tag_name == "div"
                && ctx.config.dialect == crate::options::Dialect::Pandoc
                && ctx.config.extensions.native_divs
                && (probe_open_tag_line_has_close_gt(content, "div")
                    || pandoc_html_open_tag_closes(lines, line_pos, prefix)) =>
            {
                crate::syntax::SyntaxKind::HTML_BLOCK_DIV
            }
            _ => crate::syntax::SyntaxKind::HTML_BLOCK,
        };

        // How far the Pandoc comment/PI trailing-text split may fuse
        // soft-break continuation lines into the trailing paragraph. At the
        // outermost level fusion runs to end of document; inside a plain
        // fenced div it runs up to the div's closing `:::` line; inside a
        // pure blockquote it runs up to the blockquote boundary (the
        // continuation `> ` prefixes are stripped for the reparse and
        // re-injected during graft). A list / content-indent / directive
        // container still disables fusion (the reparse fragment would need
        // more than a simple `> `-prefix strip).
        let fusion =
            if ctx.in_list || ctx.content_indent != 0 || ctx.myst_directive_closer.is_some() {
                SoftbreakFusion::None
            } else if ctx.blockquote_depth > 0 {
                SoftbreakFusion::ToBlockquoteEnd
            } else if !ctx.in_fenced_div {
                SoftbreakFusion::ToDocEnd
            } else if ctx.config.extensions.fenced_divs {
                SoftbreakFusion::ToFencedDivClose
            } else {
                SoftbreakFusion::None
            };

        let new_pos = parse_html_block_with_wrapper(
            builder,
            lines,
            line_pos,
            block_type,
            prefix,
            wrapper_kind,
            fusion,
            ctx.config,
        );
        new_pos - line_pos
    }

    fn name(&self) -> &'static str {
        "html_block"
    }
}

// ============================================================================
// LaTeX Environment Parser (position #12)
// ============================================================================

pub(crate) struct LatexEnvironmentParser;

impl BlockParser for LatexEnvironmentParser {
    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        if !ctx.config.extensions.raw_tex {
            return None;
        }

        let env_name = extract_environment_name(lines.first())?.to_string();
        let env_info = LatexEnvInfo { env_name };

        // Skip inline math environments - they should be parsed inline in paragraphs
        // Import and use the function from raw_blocks module
        use super::blocks::raw_blocks::is_inline_math_environment;
        if is_inline_math_environment(&env_info.env_name) {
            return None;
        }

        // Like HTML blocks, raw TeX blocks should be able to interrupt paragraphs.
        let detection = if ctx.has_blank_before || ctx.at_document_start {
            BlockDetectionResult::Yes
        } else {
            BlockDetectionResult::YesCanInterrupt
        };

        Some((detection, Some(Box::new(env_info))))
    }

    fn parse_prepared(
        &self,
        _ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        payload: Option<&dyn Any>,
    ) -> usize {
        use crate::syntax::SyntaxKind;

        let content = lines.first();
        let line_pos = lines.pos();
        let lines = lines.raw();

        let env_info = if let Some(info) = payload.and_then(|p| p.downcast_ref::<LatexEnvInfo>()) {
            info.clone()
        } else {
            let env_name = extract_environment_name(content)
                .expect("LaTeX env info should exist")
                .to_string();
            LatexEnvInfo { env_name }
        };

        // Use TEX_BLOCK for all non-math environments
        builder.start_node(SyntaxKind::TEX_BLOCK.into());

        let mut current_pos = line_pos;
        let end_marker = format!("\\end{{{}}}", env_info.env_name);
        let mut first_line = true;

        while current_pos < lines.len() {
            let line = lines[current_pos];

            if !first_line {
                builder.token(SyntaxKind::NEWLINE.into(), "\n");
            }
            first_line = false;

            // Emit the line content (strip newline)
            let content = trim_end_newlines(line);
            builder.token(SyntaxKind::TEXT.into(), content);

            current_pos += 1;

            // Check if this line contains the end marker
            if line.trim_start().starts_with(&end_marker) {
                break;
            }
        }

        // Emit final newline
        if current_pos > line_pos {
            builder.token(SyntaxKind::NEWLINE.into(), "\n");
        }

        builder.finish_node(); // TEX_BLOCK

        current_pos - line_pos
    }

    fn name(&self) -> &'static str {
        "latex_environment"
    }
}

// ============================================================================
// Raw TeX Block Parser (position #12)
// ============================================================================

pub(crate) struct RawTexBlockParser;

impl BlockParser for RawTexBlockParser {
    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        if !ctx.config.extensions.raw_tex {
            return None;
        }

        // Raw TeX blocks require blank line before (cannot interrupt paragraphs)
        // This is important to avoid intercepting display math content
        if !ctx.has_blank_before && !ctx.at_document_start {
            return None;
        }

        if !raw_blocks::can_start_raw_block(lines.first(), ctx.config) {
            return None;
        }

        Some((BlockDetectionResult::Yes, None))
    }

    fn parse_prepared(
        &self,
        ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        _payload: Option<&dyn Any>,
    ) -> usize {
        let line_pos = lines.pos();
        let lines = lines.raw();
        raw_blocks::parse_raw_tex_block(builder, lines, line_pos, ctx.blockquote_depth)
    }

    fn name(&self) -> &'static str {
        "raw_tex_block"
    }
}

// ============================================================================
// Line Block Parser (position #13)
// ============================================================================

pub(crate) struct LineBlockParser;

impl BlockParser for LineBlockParser {
    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        let content = lines.first();
        if !ctx.config.extensions.line_blocks {
            return None;
        }

        try_parse_line_block_start(content)?;
        // Note: a previous raw-line guard (re-checking
        // `try_parse_line_block_start` on `lines.raw()[line_pos]`) was removed
        // here — it misfired for nested cases like `- > | First line` where the
        // stripped `content` correctly starts with `| ` but the raw line is
        // prefixed with container markers (`- > `). Stripping is already done
        // by `lines.first()`; the raw probe was redundant and over-strict.

        // Require a blank line (or document start) before a line block.
        // This prevents accidental line-block parsing for wrapped paragraph lines
        // that happen to start with "| ".
        if !ctx.has_blank_before && !ctx.at_document_start {
            return None;
        }

        let detection = BlockDetectionResult::Yes;

        Some((detection, None))
    }

    fn parse_prepared(
        &self,
        ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        _payload: Option<&dyn Any>,
    ) -> usize {
        // The window already carries the container prefix (geometry +
        // `list_marker_consumed_on_line_0`); `parse_line_block` derives the
        // 5-scalar geometry from it directly.
        let line_pos = lines.pos();
        let new_pos = parse_line_block(lines, builder, ctx.config);
        new_pos - line_pos
    }

    fn name(&self) -> &'static str {
        "line_block"
    }
}

// ============================================================================
// Fenced Div Parsers (position #6)
// ============================================================================

pub(crate) struct FencedDivOpenParser;

fn content_for_fenced_div_detection<'a>(ctx: &BlockContext, content: &'a str) -> &'a str {
    if let Some(list_info) = ctx.list_indent_info {
        let (indent_cols, _) = leading_indent(content);
        if indent_cols >= list_info.content_col {
            let idx = byte_index_at_column(content, list_info.content_col);
            return &content[idx..];
        }
    }
    content
}

impl BlockParser for FencedDivOpenParser {
    fn effect(&self) -> BlockEffect {
        BlockEffect::OpenFencedDiv
    }

    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        if !ctx.config.extensions.fenced_divs {
            return None;
        }

        let content = content_for_fenced_div_detection(ctx, lines.first());
        // A fenced-div open fence starts with `:::` (Pandoc dialect)
        // after up to 3 leading spaces. Bail before the full
        // `try_parse_div_fence_open` scan when this byte gate fails.
        {
            let bytes = content.as_bytes();
            let mut i = 0;
            while i < bytes.len() && i < 3 && bytes[i] == b' ' {
                i += 1;
            }
            if bytes.get(i) != Some(&b':') {
                return None;
            }
        }
        let div_fence = try_parse_div_fence_open(content)?;
        Some((BlockDetectionResult::Yes, Some(Box::new(div_fence))))
    }

    fn parse_prepared(
        &self,
        ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        payload: Option<&dyn Any>,
    ) -> usize {
        use crate::syntax::SyntaxKind;

        let first = lines.first();
        let line_pos = lines.pos();
        let lines = lines.raw();

        let div_fence = payload
            .and_then(|p| p.downcast_ref::<DivFenceInfo>())
            .cloned()
            .or_else(|| try_parse_div_fence_open(content_for_fenced_div_detection(ctx, first)))
            .unwrap_or(DivFenceInfo {
                attributes: String::new(),
                fence_count: 3,
            });

        // Start FENCED_DIV node (container push happens in core based on `effect`).
        builder.start_node(SyntaxKind::FENCED_DIV.into());

        // Emit opening fence with attributes as child node to avoid duplication.
        builder.start_node(SyntaxKind::DIV_FENCE_OPEN.into());

        // Use full original line to preserve indentation and newline.
        let full_line = lines[line_pos];
        let line_no_bq = strip_n_blockquote_markers(full_line, ctx.blockquote_depth);
        let trimmed = line_no_bq.trim_start();

        // Leading whitespace
        let leading_ws_len = line_no_bq.len() - trimmed.len();
        if leading_ws_len > 0 {
            builder.token(SyntaxKind::WHITESPACE.into(), &line_no_bq[..leading_ws_len]);
        }

        // Fence colons
        let fence_str: String = ":".repeat(div_fence.fence_count);
        builder.token(SyntaxKind::TEXT.into(), &fence_str);

        // Everything after colons
        let after_colons = &trimmed[div_fence.fence_count..];
        let (content_before_newline, newline_str) = strip_newline(after_colons);

        if !div_fence.attributes.is_empty() {
            // Optional space before attributes
            let has_leading_space = content_before_newline.starts_with(' ');
            if has_leading_space {
                builder.token(SyntaxKind::WHITESPACE.into(), " ");
            }

            let content_after_space = if has_leading_space {
                &content_before_newline[1..]
            } else {
                content_before_newline
            };

            // Attributes — structure the Pandoc `{...}` body into ATTR_*
            // children (bare-word/empty bodies stay one opaque TEXT token).
            emit_div_info_node(builder, &div_fence.attributes);

            // Preserve any suffix after attributes (e.g., trailing spaces, optional symmetric colons).
            let after_attrs = if div_fence.attributes.starts_with('{') {
                if let Some(close_idx) = content_after_space.find('}') {
                    &content_after_space[close_idx + 1..]
                } else {
                    ""
                }
            } else {
                &content_after_space[div_fence.attributes.len()..]
            };

            if !after_attrs.is_empty() {
                let suffix_trimmed = after_attrs.trim_start();
                let ws_len = after_attrs.len() - suffix_trimmed.len();
                if ws_len > 0 {
                    builder.token(SyntaxKind::WHITESPACE.into(), &after_attrs[..ws_len]);
                }
                if !suffix_trimmed.is_empty() {
                    builder.token(SyntaxKind::TEXT.into(), suffix_trimmed);
                }
            }
        }

        if !newline_str.is_empty() {
            builder.token(SyntaxKind::NEWLINE.into(), newline_str);
        }

        builder.finish_node(); // DIV_FENCE_OPEN

        1
    }

    fn name(&self) -> &'static str {
        "fenced_div_open"
    }
}

pub(crate) struct FencedDivCloseParser;

impl BlockParser for FencedDivCloseParser {
    fn effect(&self) -> BlockEffect {
        BlockEffect::CloseFencedDiv
    }

    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        if !ctx.config.extensions.fenced_divs {
            return None;
        }

        if !ctx.in_fenced_div {
            return None;
        }

        if !is_div_closing_fence(content_for_fenced_div_detection(ctx, lines.first())) {
            return None;
        }

        Some((BlockDetectionResult::YesCanInterrupt, None))
    }

    fn parse_prepared(
        &self,
        ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        _payload: Option<&dyn Any>,
    ) -> usize {
        use crate::syntax::SyntaxKind;

        let line_pos = lines.pos();
        let lines = lines.raw();

        builder.start_node(SyntaxKind::DIV_FENCE_CLOSE.into());

        let full_line = lines[line_pos];
        let line_no_bq = strip_n_blockquote_markers(full_line, ctx.blockquote_depth);
        let trimmed = line_no_bq.trim_start();

        let leading_ws_len = line_no_bq.len() - trimmed.len();
        if leading_ws_len > 0 {
            builder.token(SyntaxKind::WHITESPACE.into(), &line_no_bq[..leading_ws_len]);
        }

        let (content_without_newline, line_ending) = strip_newline(trimmed);
        builder.token(SyntaxKind::TEXT.into(), content_without_newline);

        if !line_ending.is_empty() {
            builder.token(SyntaxKind::NEWLINE.into(), line_ending);
        }

        builder.finish_node();
        1
    }

    fn name(&self) -> &'static str {
        "fenced_div_close"
    }
}

// ============================================================================
// MyST Directive Parsers (must precede FencedCodeBlockParser)
// ============================================================================

/// Opener for MyST directives (```` ```{name} ```` / `~~~{name}` / colon
/// `:::{name}`). Opens a `MYST_DIRECTIVE` container whose body is parsed
/// recursively as markdown and closed by a matching fence. Registered before
/// [`FencedCodeBlockParser`] so the brace-tagged opener wins over the generic
/// code-fence path; a non-directive fence falls through to it.
pub(crate) struct MystDirectiveOpenParser;

impl BlockParser for MystDirectiveOpenParser {
    fn effect(&self) -> BlockEffect {
        BlockEffect::OpenMystDirective
    }

    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        let open = try_parse_directive_open(lines.first(), &ctx.config.extensions)?;
        // Directives are fences and interrupt paragraphs like a fenced code
        // block with an info string (CommonMark §4.5).
        Some((BlockDetectionResult::YesCanInterrupt, Some(Box::new(open))))
    }

    fn parse_prepared(
        &self,
        ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        payload: Option<&dyn Any>,
    ) -> usize {
        use crate::syntax::SyntaxKind;

        let line = lines.first();
        let open = payload
            .and_then(|p| p.downcast_ref::<DirectiveOpen>())
            .cloned()
            .or_else(|| try_parse_directive_open(line, &ctx.config.extensions))
            .expect("directive opener should exist");

        // Start the container node (finished on close, via the container stack).
        builder.start_node(SyntaxKind::MYST_DIRECTIVE.into());
        builder.start_node(SyntaxKind::MYST_DIRECTIVE_OPEN.into());

        let (content, newline) = strip_newline(line);

        let mut cursor = 0;
        if open.indent_len > 0 {
            builder.token(SyntaxKind::WHITESPACE.into(), &content[..open.indent_len]);
            cursor = open.indent_len;
        }

        let fence_end = cursor + open.fence_count;
        builder.token(
            SyntaxKind::MYST_DIRECTIVE_FENCE.into(),
            &content[cursor..fence_end],
        );

        let name_end = fence_end + open.name_len;
        builder.token(
            SyntaxKind::MYST_DIRECTIVE_NAME.into(),
            &content[fence_end..name_end],
        );

        // Whatever follows the `{name}` token on the opener line is the
        // directive argument (with surrounding whitespace preserved verbatim).
        let rest = &content[name_end..];
        if !rest.is_empty() {
            let trimmed = rest.trim_start();
            let lead_ws = rest.len() - trimmed.len();
            if lead_ws > 0 {
                builder.token(SyntaxKind::WHITESPACE.into(), &rest[..lead_ws]);
            }
            let arg = trimmed.trim_end();
            if arg.is_empty() {
                if !trimmed.is_empty() {
                    builder.token(SyntaxKind::WHITESPACE.into(), trimmed);
                }
            } else {
                builder.token(SyntaxKind::MYST_DIRECTIVE_ARG.into(), arg);
                let trail = &trimmed[arg.len()..];
                if !trail.is_empty() {
                    builder.token(SyntaxKind::WHITESPACE.into(), trail);
                }
            }
        }

        if !newline.is_empty() {
            builder.token(SyntaxKind::NEWLINE.into(), newline);
        }

        builder.finish_node(); // MYST_DIRECTIVE_OPEN

        // Consume the leading option block (`:key: value` lines). Per MyST
        // semantics the block is the maximal run of option lines directly
        // following the opener, terminated by the first non-option line
        // (including a blank line) -- no blank line is required between the
        // options and the body. The nodes nest under the still-open
        // MYST_DIRECTIVE container.
        let mut consumed = 0;
        loop {
            let idx = 1 + consumed;
            if idx >= lines.remaining() {
                break;
            }
            let opt_line = lines.get(idx);
            // For a colon-fenced directive (`:::{note}`) the closer also starts
            // with `:`; never let the option scan swallow it.
            if is_directive_closing_fence(opt_line, open.fence_char, open.fence_count) {
                break;
            }
            let Some(opt) = try_parse_directive_option(opt_line) else {
                break;
            };
            emit_directive_option(builder, opt_line, &opt);
            consumed += 1;
        }

        if !open.is_verbatim {
            // Non-verbatim directive: leave the container open so the body is
            // parsed recursively as markdown (handled by the container stack).
            return 1 + consumed;
        }

        // Verbatim directive (`{code}`, `{code-block}`, `{code-cell}`,
        // `{math}`): consume the literal body and the closer here, mirroring
        // `parse_fenced_code_block`, and finish the `MYST_DIRECTIVE` node so no
        // markdown-body container is opened. The body is preserved byte-for-byte
        // as a `MYST_DIRECTIVE_BODY` node.
        let total = emit_verbatim_directive_body(builder, lines, &open, 1 + consumed);
        builder.finish_node(); // MYST_DIRECTIVE
        total
    }

    fn name(&self) -> &'static str {
        "myst_directive_open"
    }
}

/// Emit a verbatim directive body (raw `TEXT`/`NEWLINE` tokens under a
/// `MYST_DIRECTIVE_BODY` node) and its closing fence, starting `body_rel` lines
/// past the opener. Returns the total number of lines consumed from the opener
/// onward (opener + options + body + closer), for the dispatcher to commit.
///
/// The forward scan mirrors [`parse_fenced_code_block`]: it stops at the first
/// line that closes the directive's fence, or when an enclosing blockquote ends,
/// or at end of input. Each body line is emitted via
/// [`StrippedLines::emit_prefix_at`] so container prefixes survive when a
/// directive is nested.
fn emit_verbatim_directive_body(
    builder: &mut GreenNodeBuilder<'static>,
    lines: &StrippedLines<'_, '_>,
    open: &DirectiveOpen,
    body_rel: usize,
) -> usize {
    use crate::syntax::SyntaxKind;

    let raw = lines.raw();
    let start = lines.pos();
    let body_start = start + body_rel;

    let prefix = lines.prefix();
    let bq_depth = prefix.bq_depth();
    let list_content_col = prefix.list_content_col();
    let bq_outer = bq_outer_of_list(prefix);

    // Forward-scan for the closing fence.
    let mut scan = body_start;
    let mut found_closer = false;
    while scan < raw.len() {
        // Leaving the enclosing blockquote ends the directive (matches the
        // fenced-code-block forward scan); never triggers at top level.
        let probe = if bq_outer {
            raw[scan]
        } else {
            strip_list_indent(raw[scan], list_content_col)
        };
        let (line_bq_depth, _) = count_blockquote_markers(probe);
        if line_bq_depth < bq_depth {
            break;
        }
        if is_directive_closing_fence(lines.strip_at(scan), open.fence_char, open.fence_count) {
            found_closer = true;
            break;
        }
        scan += 1;
    }

    // Emit the verbatim body (everything between the options and the closer).
    if scan > body_start {
        builder.start_node(SyntaxKind::MYST_DIRECTIVE_BODY.into());
        for i in body_start..scan {
            let tail = lines.emit_prefix_at(builder, i);
            let (text, newline) = strip_newline(tail);
            if !text.is_empty() {
                builder.token(SyntaxKind::TEXT.into(), text);
            }
            if !newline.is_empty() {
                builder.token(SyntaxKind::NEWLINE.into(), newline);
            }
        }
        builder.finish_node(); // MYST_DIRECTIVE_BODY
    }

    // Emit the closing fence as a `MYST_DIRECTIVE_CLOSE` node, if present.
    if found_closer {
        let tail = lines.emit_prefix_at(builder, scan);
        emit_directive_close(builder, tail, open.fence_char);
        scan += 1;
    }

    scan - start
}

/// Emit one MyST directive option line (`:key: value`) as a
/// `MYST_DIRECTIVE_OPTION` node, preserving every byte.
fn emit_directive_option(
    builder: &mut GreenNodeBuilder<'static>,
    line: &str,
    opt: &DirectiveOption,
) {
    use crate::syntax::SyntaxKind;

    let (content, newline) = strip_newline(line);

    builder.start_node(SyntaxKind::MYST_DIRECTIVE_OPTION.into());

    let mut cursor = 0;
    if opt.indent_len > 0 {
        builder.token(SyntaxKind::WHITESPACE.into(), &content[..opt.indent_len]);
        cursor = opt.indent_len;
    }

    // Leading colon, key, closing colon.
    builder.token(
        SyntaxKind::MYST_DIRECTIVE_OPTION_MARKER.into(),
        &content[cursor..cursor + 1],
    );
    cursor += 1;
    let name_end = cursor + opt.name_len;
    builder.token(
        SyntaxKind::MYST_DIRECTIVE_OPTION_NAME.into(),
        &content[cursor..name_end],
    );
    builder.token(
        SyntaxKind::MYST_DIRECTIVE_OPTION_MARKER.into(),
        &content[name_end..name_end + 1],
    );

    // Whatever follows the closing colon is the value, with surrounding
    // whitespace preserved verbatim.
    let rest = &content[name_end + 1..];
    if !rest.is_empty() {
        let trimmed = rest.trim_start();
        let lead_ws = rest.len() - trimmed.len();
        if lead_ws > 0 {
            builder.token(SyntaxKind::WHITESPACE.into(), &rest[..lead_ws]);
        }
        let value = trimmed.trim_end();
        if value.is_empty() {
            if !trimmed.is_empty() {
                builder.token(SyntaxKind::WHITESPACE.into(), trimmed);
            }
        } else {
            builder.token(SyntaxKind::MYST_DIRECTIVE_OPTION_VALUE.into(), value);
            let trail = &trimmed[value.len()..];
            if !trail.is_empty() {
                builder.token(SyntaxKind::WHITESPACE.into(), trail);
            }
        }
    }

    if !newline.is_empty() {
        builder.token(SyntaxKind::NEWLINE.into(), newline);
    }

    builder.finish_node(); // MYST_DIRECTIVE_OPTION
}

/// Closer for MyST directives. Active only when inside a directive (the
/// expected fence is threaded through [`BlockContext::myst_directive_closer`]).
/// Registered before [`FencedCodeBlockParser`] so a bare ```` ``` ```` closes
/// the directive rather than opening an empty code block.
pub(crate) struct MystDirectiveCloseParser;

impl BlockParser for MystDirectiveCloseParser {
    fn effect(&self) -> BlockEffect {
        BlockEffect::CloseMystDirective
    }

    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        let (fence_char, open_count) = ctx.myst_directive_closer?;
        if is_directive_closing_fence(lines.first(), fence_char, open_count) {
            Some((BlockDetectionResult::YesCanInterrupt, None))
        } else {
            None
        }
    }

    fn parse_prepared(
        &self,
        ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        _payload: Option<&dyn Any>,
    ) -> usize {
        let fence_char = ctx.myst_directive_closer.map(|(c, _)| c).unwrap_or(b'`');
        emit_directive_close(builder, lines.first(), fence_char);
        1
    }

    fn name(&self) -> &'static str {
        "myst_directive_close"
    }
}

/// Emit a `MYST_DIRECTIVE_CLOSE` node for an already-prefix-stripped closer
/// `line`: up to 3 leading spaces, the fence run of `fence_char`, then trailing
/// whitespace and the newline. Shared by [`MystDirectiveCloseParser`] (container
/// path) and the verbatim-body path in [`MystDirectiveOpenParser`].
fn emit_directive_close(builder: &mut GreenNodeBuilder<'static>, line: &str, fence_char: u8) {
    use crate::syntax::SyntaxKind;

    let (content, newline) = strip_newline(line);

    builder.start_node(SyntaxKind::MYST_DIRECTIVE_CLOSE.into());

    let lead_ws = content.bytes().take(3).take_while(|&b| b == b' ').count();
    if lead_ws > 0 {
        builder.token(SyntaxKind::WHITESPACE.into(), &content[..lead_ws]);
    }
    let after = &content[lead_ws..];
    let fence_len = after.bytes().take_while(|&b| b == fence_char).count();
    builder.token(SyntaxKind::MYST_DIRECTIVE_FENCE.into(), &after[..fence_len]);
    let trail = &after[fence_len..];
    if !trail.is_empty() {
        builder.token(SyntaxKind::WHITESPACE.into(), trail);
    }
    if !newline.is_empty() {
        builder.token(SyntaxKind::NEWLINE.into(), newline);
    }

    builder.finish_node(); // MYST_DIRECTIVE_CLOSE
}

/// Parser for MyST `(label)=` target lines.
pub(crate) struct MystTargetParser;

impl BlockParser for MystTargetParser {
    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        if !ctx.config.extensions.myst_targets {
            return None;
        }
        let target = try_parse_target(lines.first())?;
        Some((
            BlockDetectionResult::YesCanInterrupt,
            Some(Box::new(target)),
        ))
    }

    fn parse_prepared(
        &self,
        _ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        payload: Option<&dyn Any>,
    ) -> usize {
        use crate::syntax::SyntaxKind;

        let line = lines.first();
        let target = payload
            .and_then(|p| p.downcast_ref::<Target>())
            .copied()
            .or_else(|| try_parse_target(line))
            .expect("target should exist");
        let (content, newline) = strip_newline(line);

        builder.start_node(SyntaxKind::MYST_TARGET.into());
        if target.indent_len > 0 {
            builder.token(SyntaxKind::WHITESPACE.into(), &content[..target.indent_len]);
        }
        builder.token(
            SyntaxKind::TEXT.into(),
            &content[target.indent_len..target.label.0],
        );
        builder.token(
            SyntaxKind::MYST_TARGET_LABEL.into(),
            &content[target.label.0..target.label.1],
        );
        builder.token(
            SyntaxKind::TEXT.into(),
            &content[target.label.1..target.marker_end],
        );
        let trailing = &content[target.marker_end..];
        if !trailing.is_empty() {
            builder.token(SyntaxKind::WHITESPACE.into(), trailing);
        }
        if !newline.is_empty() {
            builder.token(SyntaxKind::NEWLINE.into(), newline);
        }
        builder.finish_node(); // MYST_TARGET
        1
    }

    fn name(&self) -> &'static str {
        "myst_target"
    }
}

/// Parser for MyST `% ...` line comments.
pub(crate) struct MystCommentParser;

impl BlockParser for MystCommentParser {
    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        if !ctx.config.extensions.myst_comments {
            return None;
        }
        if is_comment_line(lines.first()) {
            Some((BlockDetectionResult::YesCanInterrupt, None))
        } else {
            None
        }
    }

    fn parse_prepared(
        &self,
        _ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        _payload: Option<&dyn Any>,
    ) -> usize {
        use crate::syntax::SyntaxKind;

        let line = lines.first();
        let (content, newline) = strip_newline(line);
        let indent_len = content.bytes().take(3).take_while(|&b| b == b' ').count();

        builder.start_node(SyntaxKind::MYST_COMMENT.into());
        if indent_len > 0 {
            builder.token(SyntaxKind::WHITESPACE.into(), &content[..indent_len]);
        }
        builder.token(SyntaxKind::TEXT.into(), &content[indent_len..]);
        if !newline.is_empty() {
            builder.token(SyntaxKind::NEWLINE.into(), newline);
        }
        builder.finish_node(); // MYST_COMMENT
        1
    }

    fn name(&self) -> &'static str {
        "myst_comment"
    }
}

/// A standalone Svelte span line, detected for [`SvelteBlockParser`].
struct SvelteBlockInfo {
    /// Leading-space count (≤3) before the opening `{`.
    indent_len: usize,
    /// Byte length of the balanced `{...}` span.
    span_len: usize,
    /// Span category (block logic / tag / expression).
    kind: SvelteKind,
    /// Verbatim content between the outer braces.
    content: String,
}

/// Parser for standalone Svelte template lines (mdsvex).
///
/// A line whose entire content is a single balanced Svelte span
/// (`{#if}`/`{:else}`/`{/each}`, `{@html}`, or `{expr}`) is emitted as an
/// opaque [`SyntaxKind::SVELTE_BLOCK`] leaf block rather than a paragraph. As a
/// leaf block it is not an open text paragraph, so an immediately following
/// tight list opens as a real `LIST` instead of being absorbed as paragraph
/// continuation and reflowed onto one line. Gated on `svelte_template`, so it is
/// inert for every non-mdsvex flavor. The inner span subtree is built by the
/// shared inline emitter, keeping the CST identical to the inline form.
pub(crate) struct SvelteBlockParser;

impl SvelteBlockParser {
    /// Detect a whole-line Svelte span in `line` (newline already ignored).
    fn detect_line(line: &str) -> Option<SvelteBlockInfo> {
        let (content, _) = strip_newline(line);

        // Up to 3 leading spaces; a 4th would be indented code.
        let indent_len = content.bytes().take_while(|&b| b == b' ').count();
        if indent_len > 3 {
            return None;
        }
        let rest = &content[indent_len..];

        let (span_len, kind, span_content) = try_parse_svelte_template(rest)?;

        // The span must consume the whole line (only trailing whitespace may
        // follow); `{expr} text` is not a standalone block.
        if !rest[span_len..].trim().is_empty() {
            return None;
        }

        Some(SvelteBlockInfo {
            indent_len,
            span_len,
            kind,
            content: span_content,
        })
    }
}

impl BlockParser for SvelteBlockParser {
    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        if !ctx.config.extensions.svelte_template {
            return None;
        }
        let info = Self::detect_line(lines.first())?;
        Some((BlockDetectionResult::YesCanInterrupt, Some(Box::new(info))))
    }

    fn parse_prepared(
        &self,
        _ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        payload: Option<&dyn Any>,
    ) -> usize {
        use crate::syntax::SyntaxKind;

        let line = lines.first();
        let (content, newline) = strip_newline(line);
        let info = payload
            .and_then(|p| p.downcast_ref::<SvelteBlockInfo>())
            .map(|info| SvelteBlockInfo {
                indent_len: info.indent_len,
                span_len: info.span_len,
                kind: info.kind,
                content: info.content.clone(),
            })
            .or_else(|| Self::detect_line(line))
            .expect("svelte block should exist");

        builder.start_node(SyntaxKind::SVELTE_BLOCK.into());
        if info.indent_len > 0 {
            builder.token(SyntaxKind::WHITESPACE.into(), &content[..info.indent_len]);
        }
        emit_svelte_template(builder, info.kind, &info.content);
        let trailing = &content[info.indent_len + info.span_len..];
        if !trailing.is_empty() {
            builder.token(SyntaxKind::WHITESPACE.into(), trailing);
        }
        if !newline.is_empty() {
            builder.token(SyntaxKind::NEWLINE.into(), newline);
        }
        builder.finish_node(); // SVELTE_BLOCK
        1
    }

    fn name(&self) -> &'static str {
        "svelte_block"
    }
}

/// Parser for MyST `+++` block break lines.
pub(crate) struct MystBlockBreakParser;

impl BlockParser for MystBlockBreakParser {
    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        if !ctx.config.extensions.myst_block_breaks {
            return None;
        }
        let block_break = try_parse_block_break(lines.first())?;
        Some((
            BlockDetectionResult::YesCanInterrupt,
            Some(Box::new(block_break)),
        ))
    }

    fn parse_prepared(
        &self,
        _ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        payload: Option<&dyn Any>,
    ) -> usize {
        use crate::syntax::SyntaxKind;

        let line = lines.first();
        let bb = payload
            .and_then(|p| p.downcast_ref::<BlockBreak>())
            .copied()
            .or_else(|| try_parse_block_break(line))
            .expect("block break should exist");
        let (content, newline) = strip_newline(line);

        builder.start_node(SyntaxKind::MYST_BLOCK_BREAK.into());
        if bb.indent_len > 0 {
            builder.token(SyntaxKind::WHITESPACE.into(), &content[..bb.indent_len]);
        }
        builder.token(
            SyntaxKind::MYST_BLOCK_BREAK_MARKER.into(),
            &content[bb.indent_len..bb.marker_end],
        );
        let (meta_start, meta_end) = bb.metadata;
        if meta_end > meta_start {
            // Whitespace between the marker run and the metadata.
            if meta_start > bb.marker_end {
                builder.token(
                    SyntaxKind::WHITESPACE.into(),
                    &content[bb.marker_end..meta_start],
                );
            }
            builder.token(
                SyntaxKind::MYST_BLOCK_BREAK_META.into(),
                &content[meta_start..meta_end],
            );
            // Any trailing whitespace after the metadata.
            if meta_end < content.len() {
                builder.token(SyntaxKind::WHITESPACE.into(), &content[meta_end..]);
            }
        } else if bb.marker_end < content.len() {
            // No metadata: the remainder is trailing whitespace.
            builder.token(SyntaxKind::WHITESPACE.into(), &content[bb.marker_end..]);
        }
        if !newline.is_empty() {
            builder.token(SyntaxKind::NEWLINE.into(), newline);
        }
        builder.finish_node(); // MYST_BLOCK_BREAK
        1
    }

    fn name(&self) -> &'static str {
        "myst_block_break"
    }
}

// ============================================================================
// Admonition Parser (must precede Indented Code Block — position #6b)
// ============================================================================

/// Opener for python-markdown admonitions (`!!! type "title"`) and
/// pymdownx.details (`???`/`???+`). Opens an `ADMONITION` container whose
/// 4-space-indented body is parsed recursively (closed on dedent like a
/// footnote definition). Registered before [`IndentedCodeBlockParser`] so
/// the indented body is not captured as a code block.
pub(crate) struct AdmonitionOpenParser;

impl BlockParser for AdmonitionOpenParser {
    fn effect(&self) -> BlockEffect {
        BlockEffect::OpenAdmonition
    }

    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        let adm = try_parse_admonition_open(lines.first(), &ctx.config.extensions)?;
        // python-markdown / pymdownx split a block at a marker line, so an
        // admonition may interrupt a paragraph.
        Some((BlockDetectionResult::YesCanInterrupt, Some(Box::new(adm))))
    }

    fn parse_prepared(
        &self,
        ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        payload: Option<&dyn Any>,
    ) -> usize {
        use crate::syntax::SyntaxKind;

        let first = lines.first();
        let Some(adm) = payload
            .and_then(|p| p.downcast_ref::<AdmonitionOpen>())
            .cloned()
            .or_else(|| try_parse_admonition_open(first, &ctx.config.extensions))
        else {
            return 1;
        };

        if let Some(indent_str) = ctx.indent_to_emit {
            builder.token(SyntaxKind::WHITESPACE.into(), indent_str);
        }

        // The ADMONITION node is left open; the container machinery closes it
        // on dedent (see `Container::Admonition`).
        builder.start_node(SyntaxKind::ADMONITION.into());
        emit_admonition_marker_line(builder, first, &adm);
        1
    }

    fn name(&self) -> &'static str {
        "admonition"
    }
}

/// Emit the admonition opener line losslessly: every byte of `first` becomes
/// a marker/type/title token or interleaved/trailing `WHITESPACE`, plus the
/// trailing `NEWLINE`.
fn emit_admonition_marker_line(
    builder: &mut GreenNodeBuilder<'static>,
    first: &str,
    adm: &AdmonitionOpen,
) {
    use crate::syntax::SyntaxKind;

    let (line, newline) = strip_newline(first);

    if adm.indent_len > 0 {
        builder.token(SyntaxKind::WHITESPACE.into(), &line[..adm.indent_len]);
    }
    let marker_end = adm.indent_len + adm.marker_len;
    builder.token(
        SyntaxKind::ADMONITION_MARKER.into(),
        &line[adm.indent_len..marker_end],
    );
    let mut cur = marker_end;

    if let Some((start, end)) = adm.type_range {
        if start > cur {
            builder.token(SyntaxKind::WHITESPACE.into(), &line[cur..start]);
        }
        builder.token(SyntaxKind::ADMONITION_TYPE.into(), &line[start..end]);
        cur = end;
    }

    if let Some((start, end)) = adm.title_range {
        if start > cur {
            builder.token(SyntaxKind::WHITESPACE.into(), &line[cur..start]);
        }
        builder.token(SyntaxKind::ADMONITION_TITLE.into(), &line[start..end]);
        cur = end;
    }

    if cur < line.len() {
        builder.token(SyntaxKind::WHITESPACE.into(), &line[cur..]);
    }
    if !newline.is_empty() {
        builder.token(SyntaxKind::NEWLINE.into(), newline);
    }
}

// ============================================================================
// Indented Code Block Parser (position #11)
// ============================================================================

pub(crate) struct IndentedCodeBlockParser;

impl BlockParser for IndentedCodeBlockParser {
    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        let content = lines.first();
        let line_pos = lines.pos();
        let lines = lines.raw();
        // CommonMark §4.4: indented code blocks cannot interrupt a paragraph,
        // but they CAN follow non-paragraph blocks (headings, fenced code,
        // HRs) without an intervening blank line. The relaxed
        // `has_blank_before` captures that "no continuation-eligible block is
        // open" signal — use it under CommonMark so `# Heading\n    foo`
        // correctly emits a code block (spec examples #115, #236, #252).
        //
        // Under Pandoc-markdown the construct diverges: a `>` blockquote with
        // an indented code line followed by an unmarked indented line lazily
        // extends the blockquote (verified with `pandoc -f markdown` for
        // `>     foo\n    bar`). Keep the literal strict gate there to avoid
        // regressing lazy-continuation behavior.
        //
        // Marker-only list items have no buffered content yet, so an indented
        // line on the *next* line cannot interrupt anything; allow the code
        // block to open under either dialect (spec example #278's third item:
        // `-\n      baz` → indented code block inside the list item). Both
        // dialects agree here (verified via `pandoc -f commonmark / -f
        // markdown`). Returned as `YesCanInterrupt` so the parser core flushes
        // the list-item buffer (which holds the marker line's trailing
        // newline) *before* emitting the code block, preserving lossless byte
        // ordering.
        let allow_marker_only = ctx.in_marker_only_list_item;
        let allow = if allow_marker_only {
            true
        } else if ctx.config.dialect == crate::options::Dialect::CommonMark {
            ctx.has_blank_before || ctx.at_document_start
        } else {
            // Pandoc dialect: strict literal blank, OR the previous source line
            // (at the same blockquote depth) was a complete one-liner block
            // (ATX heading or HR). Pandoc allows an indented code block to
            // immediately follow a heading or HR without an intervening blank
            // line; lazy-blockquote-continuation cases are still rejected
            // because their previous line is paragraph-like content, not a
            // self-contained block.
            //
            // The one-liner shortcut is purely textual, so it must additionally
            // require that no `Container::Paragraph` is currently buffering
            // content: if the parser already absorbed the heading-shaped line
            // as paragraph text (e.g. Pandoc's `blank_before_header` is on, or
            // the buffered line was indented past the heading limit), the
            // indented line that follows is paragraph continuation, not a new
            // code block.
            ctx.has_blank_before_strict
                || (!ctx.paragraph_open
                    && prev_line_is_terminal_one_liner(lines, line_pos, ctx.blockquote_depth))
        };
        if !allow {
            return None;
        }

        let list_content_col = ctx
            .list_indent_info
            .map(|list_info| list_info.content_col)
            .unwrap_or(0);
        let required_indent = list_content_col + 4;

        let (indent_cols, _) = leading_indent(content);
        // Don't treat as code if it's a list marker and not indented enough for code.
        if indent_cols < required_indent
            && try_parse_list_marker(content, ctx.config, ctx.open_alpha_hint).is_some()
        {
            return None;
        }

        if indent_cols < required_indent || !is_indented_code_line(content) {
            return None;
        }

        let detection = if allow_marker_only {
            BlockDetectionResult::YesCanInterrupt
        } else {
            BlockDetectionResult::Yes
        };
        Some((detection, None))
    }

    fn parse_prepared(
        &self,
        ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        _payload: Option<&dyn Any>,
    ) -> usize {
        let line_pos = lines.pos();
        let lines = lines.raw();
        let base_indent = ctx.content_indent
            + ctx
                .list_indent_info
                .map(|list_info| list_info.content_col)
                .unwrap_or(0);

        let new_pos =
            parse_indented_code_block(builder, lines, line_pos, ctx.blockquote_depth, base_indent);
        new_pos - line_pos
    }

    fn name(&self) -> &'static str {
        "indented_code_block"
    }
}

// ============================================================================
// Setext Heading Parser (position #3)
// ============================================================================

pub(crate) struct SetextHeadingParser;

impl BlockParser for SetextHeadingParser {
    fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<(BlockDetectionResult, Option<Box<dyn Any>>)> {
        let content = lines.first();
        let line_pos = lines.pos();
        let lines = lines.raw();
        // Setext headings usually require blank line before (unless at document start),
        // but Pandoc also allows consecutive setext headings without an intervening blank line.
        let follows_setext_heading = if line_pos >= 2 {
            let prev_text = count_blockquote_markers(lines[line_pos - 2]).1;
            let prev_underline = count_blockquote_markers(lines[line_pos - 1]).1;
            try_parse_setext_heading(&[prev_text, prev_underline], 0).is_some()
        } else {
            false
        };

        // Pandoc never forms a setext heading mid-paragraph, even with
        // `blank_before_header` disabled (`markdown-blank_before_header` keeps
        // `Text\nTitle\n-----` a single Para) — only ATX headings interrupt.
        // So under the Pandoc dialect the blank-before requirement holds
        // unconditionally; CommonMark instead folds the open paragraph into
        // the heading via the dialect-gated branch in the parser core.
        let requires_blank_before = ctx.config.extensions.blank_before_header
            || ctx.config.dialect == crate::options::Dialect::Pandoc;
        if requires_blank_before
            && !ctx.has_blank_before
            && !ctx.at_document_start
            && !follows_setext_heading
        {
            return None;
        }

        // Need next line for lookahead
        let next_line = ctx.next_line?;

        // Cheap leading-byte gate: a setext underline starts with `=` or
        // `-` after up to 3 spaces (CommonMark §4.3). Avoid the
        // `try_parse_setext_heading` re-scan when this can't fire — the
        // dispatcher runs SetextHeading on every non-blank line.
        {
            let bytes = next_line.as_bytes();
            let mut i = 0;
            while i < bytes.len() && i < 3 && bytes[i] == b' ' {
                i += 1;
            }
            match bytes.get(i) {
                Some(&b'=') | Some(&b'-') => {}
                _ => return None,
            }
        }

        // Create lines array for detection function (avoid allocation)
        let lines = [content, next_line];

        // Try to detect setext heading
        if try_parse_setext_heading(&lines, 0).is_some() {
            // CommonMark §4.3: a setext heading text line cannot itself be a
            // valid thematic break. Pandoc-markdown allows it (e.g. `***\n---`
            // becomes `<h2>***</h2>`), so this branch is dialect-gated.
            if ctx.config.dialect == crate::options::Dialect::CommonMark
                && try_parse_horizontal_rule(content).is_some()
            {
                return None;
            }
            // CommonMark §4.3 / §4.7: a setext heading text line cannot
            // itself be a reference definition — the ref-def takes priority,
            // and the underline becomes a separate paragraph line. Pandoc
            // disagrees: it consumes `[foo]: /url\n===\n` as an H1 with
            // text `[foo]: /url`, so this branch is dialect-gated.
            if ctx.config.dialect == crate::options::Dialect::CommonMark
                && ctx.config.extensions.reference_links
                && try_parse_reference_definition(content, ctx.config.dialect).is_some()
            {
                return None;
            }
            // CommonMark §4.3: the underline must be in the same container as
            // the text. If the text line is inside a blockquote (or nested
            // blockquotes) and the underline line is at a shallower depth,
            // the construct can't be a setext heading — the underline closes
            // the blockquote and (for `---` after a non-empty paragraph)
            // becomes a thematic break instead. Pandoc disagrees: it treats
            // `> foo\n---\n` as a top-level setext H2 with text `> foo`, so
            // gate on dialect.
            if ctx.config.dialect == crate::options::Dialect::CommonMark
                && count_blockquote_markers(next_line).0 != ctx.blockquote_depth
            {
                return None;
            }
            // Same-container rule for list items: if the text line is inside a
            // list item (content_col > 0) and the underline line's indent is
            // less than that content_col, the underline breaks out of the
            // list item — it's a sibling list marker (or HR / paragraph
            // continuation), not a setext underline. Both dialects agree on
            // this for the single-`-` case (`-\n  foo\n-\n` → two sibling
            // list items, not a setext heading), verified via
            // `pandoc -f commonmark` and `pandoc -f markdown`.
            if let Some(list_info) = ctx.list_indent_info {
                let (next_indent_cols, _) = leading_indent(next_line);
                if next_indent_cols < list_info.content_col {
                    return None;
                }
            }
            Some((BlockDetectionResult::Yes, None))
        } else {
            None
        }
    }

    fn parse_prepared(
        &self,
        ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
        _payload: Option<&dyn Any>,
    ) -> usize {
        // Get text line and underline line
        let text_line = lines.raw_at(0);
        let underline_line = lines.raw_at(1);

        // Determine level from underline character (no need to call try_parse again)
        let underline_char = underline_line.trim().chars().next().unwrap_or('=');
        let level = if underline_char == '=' { 1 } else { 2 };

        // Emit the setext heading
        emit_setext_heading(builder, text_line, underline_line, level, ctx.config);

        // Return lines consumed: text line + underline line
        2
    }

    fn name(&self) -> &'static str {
        "setext_heading"
    }
}

// ============================================================================
// Helpers
// ============================================================================

/// Whether the immediately-previous source line (after stripping `expected_bq_depth`
/// blockquote markers) is itself a complete one-liner block — currently an ATX
/// heading or a horizontal rule. Used by the indented-code-block dispatcher
/// under Pandoc dialect to allow `# Heading\n    foo` (and the analogous HR
/// case) to emit a CodeBlock without requiring an intervening blank line,
/// matching pandoc's behavior. Returns false on lazy-blockquote-continuation
/// lines (where the prev line is paragraph-like content rather than a
/// self-contained block).
fn prev_line_is_terminal_one_liner(
    lines: &[&str],
    line_pos: usize,
    expected_bq_depth: usize,
) -> bool {
    if line_pos == 0 {
        return false;
    }
    let prev_line = lines[line_pos - 1];
    let (prev_bq_depth, prev_inner) = count_blockquote_markers(prev_line);
    if prev_bq_depth != expected_bq_depth {
        return false;
    }
    let (prev_inner_no_nl, _) = strip_newline(prev_inner);
    // Don't trim_start: the ATX/HR detectors enforce the ≤3-leading-space rule
    // themselves, and indented paragraph continuation lines that *look* like
    // headings (e.g. `                ## comment` inside buffered paragraph
    // text) must not be reported as terminal one-liners — otherwise an
    // indented code line that follows is wrongly allowed to interrupt the
    // open paragraph.
    try_parse_atx_heading(prev_inner_no_nl).is_some()
        || try_parse_horizontal_rule(prev_inner_no_nl).is_some()
}

// ============================================================================
// Block Parser Registry
// ============================================================================

/// Registry of block parsers, ordered by priority.
///
/// This dispatcher tries each parser in order until one succeeds.
/// The ordering follows Pandoc's approach - explicit list order rather
/// than numeric priorities.
pub(crate) struct BlockParserRegistry {
    parsers: Vec<Box<dyn BlockParser>>,
}

impl BlockParserRegistry {
    /// Create a new registry with all block parsers.
    ///
    /// Order matters! Parsers are tried in the order listed here.
    /// This follows Pandoc's design where ordering is explicit and documented.
    ///
    /// **Pandoc reference order** (from pandoc/src/Text/Pandoc/Readers/Markdown.hs:487-515):
    /// 1. blanklines (handled separately in our parser)
    /// 2. codeBlockFenced
    /// 3. yamlMetaBlock' ← YAML metadata comes early!
    /// 4. bulletList
    /// 5. divHtml
    /// 6. divFenced
    /// 7. header ← ATX and Setext headers
    /// 8. lhsCodeBlock
    /// 9. htmlBlock
    /// 10. table
    /// 11. codeBlockIndented
    /// 12. rawTeXBlock (LaTeX)
    /// 13. lineBlock
    /// 14. blockQuote
    /// 15. hrule ← Horizontal rules come AFTER headers!
    /// 16. orderedList
    /// 17. definitionList
    /// 18. noteBlock (footnotes)
    /// 19. referenceKey ← Reference definitions
    /// 20. abbrevKey
    /// 21. para
    /// 22. plain
    pub fn new() -> Self {
        let parsers: Vec<Box<dyn BlockParser>> = vec![
            // Match Pandoc's ordering to ensure correct precedence:
            // (0) Pandoc title block (must be at document start).
            Box::new(PandocTitleBlockParser),
            // (0b) MultiMarkdown title block (must be at document start).
            // Pandoc title block remains first for precedence.
            Box::new(MmdTitleBlockParser),
            // (1b) MyST directives — MUST precede fenced code so a brace-tagged
            // opener (```` ```{name} ````) and a directive closer win over the
            // generic code-fence path. Close before open, like fenced divs.
            Box::new(MystDirectiveCloseParser),
            Box::new(MystDirectiveOpenParser),
            // (2) Fenced code blocks - can interrupt paragraphs!
            Box::new(FencedCodeBlockParser),
            // (3) YAML metadata - before headers and hrules!
            Box::new(YamlMetadataParser),
            // (3b) MyST `+++` block break — MUST precede lists so the spaced
            // marker form (`+ + +`) is a block break, not a bullet list, matching
            // markdown-it's `myst_block_break` (registered before `hr`/`list`).
            Box::new(MystBlockBreakParser),
            // (4) Lists
            Box::new(ListParser),
            // (6) Fenced divs ::: (open/close)
            Box::new(FencedDivCloseParser),
            Box::new(FencedDivOpenParser),
            // (6b) MyST target lines `(label)=` and `%` comments (leaf blocks).
            Box::new(MystTargetParser),
            Box::new(MystCommentParser),
            // (7) Setext headings (part of Pandoc's "header" parser)
            // Must come before ATX to properly handle `---` disambiguation
            Box::new(SetextHeadingParser),
            // (7) ATX headings (part of Pandoc's "header" parser)
            Box::new(AtxHeadingParser),
            // (9) HTML blocks
            Box::new(HtmlBlockParser),
            // (9b) Standalone Svelte spans (mdsvex) - opaque line-level blocks,
            // gated on `svelte_template` so inert for every other flavor.
            Box::new(SvelteBlockParser),
            // (10) Tables
            Box::new(TableParser),
            // (10b) Admonitions (`!!!`/`???`) — MUST precede indented code so
            // the 4-space-indented body isn't captured as a code block.
            Box::new(AdmonitionOpenParser),
            // (11) Indented code blocks (AFTER fenced!)
            Box::new(IndentedCodeBlockParser),
            // (12) LaTeX environment blocks
            Box::new(LatexEnvironmentParser),
            // (12) Raw TeX blocks (macro definitions, etc.)
            Box::new(RawTexBlockParser),
            // (13) Line blocks
            Box::new(LineBlockParser),
            // (14) Block quotes (detection-only for now)
            Box::new(BlockQuoteParser),
            // (15) Horizontal rules - AFTER headings per Pandoc
            Box::new(HorizontalRuleParser),
            // Figures (standalone images) - Pandoc doesn't have these
            Box::new(FigureParser),
            // (17) Definition lists
            Box::new(DefinitionListParser),
            // (18) Footnote definitions (noteBlock)
            Box::new(FootnoteDefinitionParser),
            // (19) Reference definitions
            Box::new(ReferenceDefinitionParser),
        ];

        Self { parsers }
    }

    /// Like `detect()`, but allows parsers to return cached payload for emission.
    pub fn detect_prepared(
        &self,
        ctx: &BlockContext,
        lines: &StrippedLines<'_, '_>,
    ) -> Option<PreparedBlockMatch> {
        for (i, parser) in self.parsers.iter().enumerate() {
            if let Some((detection, payload)) = parser.detect_prepared(ctx, lines) {
                log::trace!("Block detected by: {}", parser.name());
                return Some(PreparedBlockMatch {
                    parser_index: i,
                    detection,
                    effect: parser.effect(),
                    payload,
                });
            }
        }
        None
    }

    pub fn parser_name(&self, block_match: &PreparedBlockMatch) -> &'static str {
        self.parsers[block_match.parser_index].name()
    }

    pub fn parse_prepared(
        &self,
        block_match: &PreparedBlockMatch,
        ctx: &BlockContext,
        builder: &mut GreenNodeBuilder<'static>,
        lines: &StrippedLines<'_, '_>,
    ) -> usize {
        let parser = &self.parsers[block_match.parser_index];
        log::trace!("Block parsed by: {}", parser.name());
        parser.parse_prepared(ctx, builder, lines, block_match.payload.as_deref())
    }
}

#[cfg(test)]
mod svelte_block_tests {
    use super::{SvelteBlockParser, SvelteKind};

    #[test]
    fn detects_block_logic_line() {
        let info = SvelteBlockParser::detect_line("{#each items as item}\n").unwrap();
        assert_eq!(info.kind, SvelteKind::BlockLogic);
        assert_eq!(info.indent_len, 0);
        assert_eq!(info.content, "#each items as item");
    }

    #[test]
    fn detects_tag_and_expression_lines() {
        assert_eq!(
            SvelteBlockParser::detect_line("{@html body}\n")
                .unwrap()
                .kind,
            SvelteKind::Tag
        );
        assert_eq!(
            SvelteBlockParser::detect_line("{count}\n").unwrap().kind,
            SvelteKind::Expression
        );
    }

    #[test]
    fn accepts_up_to_three_leading_spaces() {
        let info = SvelteBlockParser::detect_line("   {/if}\n").unwrap();
        assert_eq!(info.indent_len, 3);
    }

    #[test]
    fn rejects_four_leading_spaces() {
        // Four leading spaces is indented code, not a standalone span.
        assert!(SvelteBlockParser::detect_line("    {/if}\n").is_none());
    }

    #[test]
    fn accepts_trailing_whitespace_after_span() {
        assert!(SvelteBlockParser::detect_line("{/if}   \n").is_some());
    }

    #[test]
    fn rejects_trailing_text_after_span() {
        // A span followed by prose is inline, not a standalone block.
        assert!(SvelteBlockParser::detect_line("{count} today\n").is_none());
    }

    #[test]
    fn rejects_unbalanced_span() {
        assert!(SvelteBlockParser::detect_line("{#if x\n").is_none());
    }

    #[test]
    fn rejects_shortcode_opener() {
        // `{{< ... >}}` is left to the Quarto shortcode probe.
        assert!(SvelteBlockParser::detect_line("{{< meta x >}}\n").is_none());
    }
}