ferromark 0.1.2

Ultra-high-performance Markdown to HTML compiler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
//! Block parser implementation.

use crate::Range;
use crate::cursor::Cursor;
use crate::limits;
use smallvec::SmallVec;

use super::event::{Alignment, BlockEvent, CalloutType, ListKind, TaskState};
use crate::Options;
use crate::footnote::{FootnoteStore, normalize_footnote_label};
use crate::link_ref::{LinkRefDef, LinkRefStore, normalize_label_into};

#[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
use std::arch::aarch64::*;

/// State for an open fenced code block.
#[derive(Debug, Clone)]
struct FenceState {
    /// The fence character (` or ~).
    fence_char: u8,
    /// Length of the opening fence.
    fence_len: usize,
    /// Indentation of the opening fence.
    indent: usize,
}

/// HTML block kinds (CommonMark types 1-7).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HtmlBlockKind {
    Type1,
    Type2,
    Type3,
    Type4,
    Type5,
    Type6,
    Type7,
}

/// Type of container block.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ContainerType {
    /// Block quote (`>`)
    BlockQuote,
    /// List item
    ListItem {
        /// List type
        kind: ListKind,
        /// Marker character for unordered, or 0 for ordered
        marker: u8,
        /// Column where content starts (after marker + space)
        content_indent: usize,
    },
    /// Footnote definition (`[^label]: content`)
    FootnoteDefinition {
        /// Column where content starts (after `[^label]: `)
        content_indent: usize,
    },
}

/// An open container on the stack.
#[derive(Debug, Clone)]
struct Container {
    /// Type of container.
    typ: ContainerType,
    /// Whether this container has had any content yet.
    /// For list items, this is used to implement the two-blank-line rule.
    has_content: bool,
}

/// Tracks an open list that may have its items closed/reopened.
#[derive(Debug, Clone)]
struct OpenList {
    kind: ListKind,
    /// Marker character for unordered (-, *, +) or delimiter for ordered (., )).
    marker: u8,
    /// Whether the list is still tight (no blank lines in items).
    tight: bool,
    /// Whether we've seen a blank line since the last item started.
    /// Used to detect loose lists (blank line between items or inside items).
    blank_in_item: bool,
    /// Number of items so far.
    item_count: u32,
}

/// Block parser state.
pub struct BlockParser<'a> {
    /// Input bytes.
    input: &'a [u8],
    /// Current cursor position.
    cursor: Cursor<'a>,
    /// Whether we're currently in a paragraph.
    in_paragraph: bool,
    /// Accumulated paragraph text ranges.
    paragraph_lines: Vec<Range>,
    /// Current fenced code block state, if inside one.
    fence_state: Option<FenceState>,
    /// Whether we're in an indented code block.
    in_indented_code: bool,
    /// Extra spaces to prepend to each line of indented code (from tab expansion).
    indented_code_extra_spaces: usize,
    /// Pending blank lines in indented code (only emit if code continues).
    /// Stores (extra_spaces_beyond_4, newline_range) for each blank line.
    pending_code_blanks: Vec<(u8, Range)>,
    /// Current HTML block kind, if inside an HTML block.
    html_block: Option<HtmlBlockKind>,
    /// Number of bytes skipped by the last leading-indent scan for this line.
    line_indent_bytes: usize,
    /// Optional indent start override for the first line of an HTML block.
    pending_html_indent_start: Option<usize>,
    /// Collected link reference definitions.
    link_refs: LinkRefStore,
    /// Reused scratch buffer for paragraph-backed link reference parsing.
    link_ref_parse_buf: Vec<u8>,
    /// Reused normalized-label buffer for paragraph-backed link reference parsing.
    link_ref_label_buf: String,
    /// Parser options.
    options: Options,
    /// Stack of open containers (blockquotes, list items).
    container_stack: SmallVec<[Container; 8]>,
    /// Whether we're in a tight list context.
    #[allow(dead_code)]
    tight_list: bool,
    /// Currently open lists (for tracking across item closes).
    open_lists: SmallVec<[OpenList; 4]>,
    /// Remaining columns from a partially-consumed tab.
    /// When a tab expands beyond what's needed for container indent, the excess
    /// columns are stored here and added to the next indent measurement.
    partial_tab_cols: usize,
    /// Current absolute column position within the line (for tab expansion).
    current_col: usize,
    /// Whether we're currently inside a table.
    in_table: bool,
    /// Column alignments for the current table.
    table_alignments: SmallVec<[Alignment; 8]>,
    /// Whether the current table has a body (at least one data row).
    table_has_body: bool,
    /// Collected footnote definitions.
    footnote_store: FootnoteStore,
    /// Index in the event buffer where the current footnote definition's content starts.
    footnote_event_start: Option<usize>,
    /// Pending label for the current footnote definition (normalized, original).
    pending_footnote_label: Option<(String, String)>,
}

impl<'a> BlockParser<'a> {
    /// Create a new block parser.
    pub fn new(input: &'a [u8]) -> Self {
        Self::new_with_options(input, Options::default())
    }

    /// Create a new block parser with options.
    pub fn new_with_options(input: &'a [u8], options: Options) -> Self {
        Self {
            input,
            cursor: Cursor::new(input),
            in_paragraph: false,
            paragraph_lines: Vec::new(),
            fence_state: None,
            in_indented_code: false,
            indented_code_extra_spaces: 0,
            pending_code_blanks: Vec::new(),
            html_block: None,
            line_indent_bytes: 0,
            pending_html_indent_start: None,
            link_refs: LinkRefStore::new(),
            link_ref_parse_buf: Vec::new(),
            link_ref_label_buf: String::with_capacity(64),
            options,
            container_stack: SmallVec::new(),
            tight_list: false,
            open_lists: SmallVec::new(),
            partial_tab_cols: 0,
            current_col: 0,
            in_table: false,
            table_alignments: SmallVec::new(),
            table_has_body: false,
            footnote_store: FootnoteStore::new(),
            footnote_event_start: None,
            pending_footnote_label: None,
        }
    }

    /// Parse all blocks and collect events.
    pub fn parse(&mut self, events: &mut Vec<BlockEvent>) {
        while !self.cursor.is_eof() {
            self.parse_line(events);
        }

        // Close any open table at end of input
        self.close_table(events);

        // Close any open paragraph at end of input
        self.close_paragraph(events);

        // Close any unclosed fenced code block
        if self.fence_state.is_some() {
            self.fence_state = None;
            events.push(BlockEvent::CodeBlockEnd);
        }

        // Close any unclosed indented code block (discard trailing blanks)
        if self.in_indented_code {
            self.pending_code_blanks.clear();
            self.in_indented_code = false;
            events.push(BlockEvent::CodeBlockEnd);
        }

        // Close any unclosed HTML block
        if self.html_block.is_some() {
            self.html_block = None;
            events.push(BlockEvent::HtmlBlockEnd);
        }

        // Close all open containers
        self.close_all_containers(events);
    }

    /// Take the collected link reference definitions.
    pub fn take_link_refs(&mut self) -> LinkRefStore {
        std::mem::take(&mut self.link_refs)
    }

    /// Take the collected footnote definitions.
    pub fn take_footnote_store(&mut self) -> FootnoteStore {
        std::mem::take(&mut self.footnote_store)
    }

    /// Parse a single line.
    fn parse_line(&mut self, events: &mut Vec<BlockEvent>) {
        if self.parse_simple_paragraph_run(events) {
            return;
        }

        let line_start = self.cursor.offset();

        // Reset column tracking at the start of each line
        self.partial_tab_cols = 0;
        self.current_col = 0;

        // Check for blank line first (before any space skipping), unless we're in an HTML block
        if self.html_block.is_none() && self.is_blank_line() {
            // If we're inside a fenced code block, ensure containers still match.
            if self.fence_state.is_some() {
                self.cursor = Cursor::new_at(self.input, line_start);
                self.partial_tab_cols = 0;
                self.current_col = 0;
                let matched_containers = self.match_containers(events);
                if matched_containers < self.container_stack.len() {
                    self.fence_state = None;
                    events.push(BlockEvent::CodeBlockEnd);
                    let (indent, _) = self.skip_indent();
                    self.close_containers_from(matched_containers, indent, events);
                    self.close_paragraph(events);
                    self.handle_blank_line_containers(events, true);
                    return;
                }
                self.parse_fence_line_in_container(events);
                return;
            }
            // Track columns while skipping whitespace (for code block blank lines)
            let mut cols = 0usize;
            while let Some(b) = self.cursor.peek() {
                if b == b' ' {
                    cols += 1;
                    self.cursor.bump();
                } else if b == b'\t' {
                    cols = (cols + 4) & !3;
                    self.cursor.bump();
                } else {
                    break;
                }
            }
            let newline_start = self.cursor.offset();
            if !self.cursor.is_eof() && self.cursor.at(b'\n') {
                self.cursor.bump();
            }
            let ws_end = self.cursor.offset();

            // Blank lines inside indented code are preserved (but buffered)
            // Check this BEFORE closing blockquotes, as closing will end the code block
            if self.in_indented_code {
                // Check if we're inside a blockquote - if so, the blank line closes it
                // which also closes the indented code block
                let has_blockquote = self
                    .container_stack
                    .iter()
                    .any(|c| c.typ == ContainerType::BlockQuote);
                if !has_blockquote {
                    // Buffer the blank line with any extra whitespace beyond 4 columns
                    let extra_spaces = cols.saturating_sub(4) as u8;
                    self.pending_code_blanks.push((
                        extra_spaces,
                        Range::new(newline_start as u32, ws_end as u32),
                    ));
                    return;
                }
                // Fall through to close blockquotes (which will close the code block too)
            }

            self.close_table(events);
            self.close_paragraph(events);
            // This is a truly blank line (no container markers) - close blockquotes
            self.handle_blank_line_containers(events, true);
            return;
        }

        // Reset to line start for container matching
        self.cursor = Cursor::new_at(self.input, line_start);

        // Try to match and continue existing containers
        // This handles the indent requirements per container type
        let matched_containers = self.match_containers(events);

        // If we're inside an HTML block, handle it after container matching.
        if self.options.allow_html && self.html_block.is_some() {
            if matched_containers < self.container_stack.len() {
                // Containers didn't match, close the HTML block
                self.html_block = None;
                events.push(BlockEvent::HtmlBlockEnd);
                let (indent, _) = self.skip_indent();
                self.close_containers_from(matched_containers, indent, events);
                // Fall through to continue parsing the line normally
            } else {
                self.parse_html_block_line(events);
                return;
            }
        }

        // If we're inside a fenced code block, handle it after container matching
        // but BEFORE skip_spaces (since spaces may be part of code content)
        if self.fence_state.is_some() {
            // If containers didn't match, close the fenced code block
            if matched_containers < self.container_stack.len() {
                self.fence_state = None;
                events.push(BlockEvent::CodeBlockEnd);
                // Close unmatched containers and continue with normal parsing
                let (indent, _) = self.skip_indent();
                self.close_containers_from(matched_containers, indent, events);
                // Fall through to continue parsing the line normally
            } else {
                // Containers matched, handle as fenced code line
                self.parse_fence_line_in_container(events);
                return;
            }
        }

        // Get current indent (in columns) after container matching
        let (indent, indent_bytes) = self.skip_indent();
        self.line_indent_bytes = indent_bytes;

        // Check for blank line AFTER container matching (e.g., ">>" followed by newline)
        if self.cursor.is_eof() || self.cursor.at(b'\n') {
            if !self.cursor.is_eof() {
                self.cursor.bump();
            }
            self.close_table(events);
            self.close_paragraph(events);
            // Container markers were present, so don't close blockquotes
            self.handle_blank_line_containers(events, false);
            return;
        }

        // If we have unmatched containers, check for lazy continuation or close them
        if matched_containers < self.container_stack.len() {
            // If we're in an indented code block and containers don't match, close it
            if self.in_indented_code {
                self.in_indented_code = false;
                events.push(BlockEvent::CodeBlockEnd);
            }

            // Check if this is a thematic break - it should close all containers first
            if indent < 4 && self.peek_thematic_break() {
                self.close_all_containers(events);
                self.try_thematic_break(events);
                return;
            }

            // Check for lazy continuation (paragraph continues without > marker)
            // Note: setext underlines do NOT work via lazy continuation - they must be at
            // the same container level as the paragraph content. So we don't check for them here.
            if self.can_lazy_continue(matched_containers, indent) {
                // Normal lazy continuation - add this line to the paragraph
                let line_start = self.cursor.offset();
                self.parse_paragraph_line(line_start, events);
                return;
            }

            // close_containers_from is smart about keeping lists open when starting new items
            // Pass indent so it knows if a new item is actually possible (only at indent < 4)
            self.close_containers_from(matched_containers, indent, events);
        }

        // If we're in an indented code block and containers matched, handle continuation
        if self.in_indented_code {
            if indent >= 4 {
                // Continue the code block - first emit any pending blank lines
                for (extra_spaces, blank_range) in self.pending_code_blanks.drain(..) {
                    if extra_spaces > 0 {
                        events.push(BlockEvent::VirtualSpaces(extra_spaces));
                    }
                    events.push(BlockEvent::Code(blank_range));
                }

                // Calculate extra spaces for this line (columns beyond 4)
                let extra_spaces = indent.saturating_sub(4);

                // Cursor is past all whitespace. Content starts at current position.
                let text_start = self.cursor.offset();
                let line_end = self.find_line_end();
                let content_end = if !self.cursor.is_eof() && self.cursor.at(b'\n') {
                    self.cursor.bump();
                    line_end + 1
                } else {
                    line_end
                };

                // Emit virtual spaces if there are extra columns
                if extra_spaces > 0 {
                    events.push(BlockEvent::VirtualSpaces(extra_spaces as u8));
                }
                events.push(BlockEvent::Code(Range::new(
                    text_start as u32,
                    content_end as u32,
                )));
                return;
            } else {
                // Close the code block - discard pending blank lines (trailing blanks)
                self.pending_code_blanks.clear();
                self.in_indented_code = false;
                self.indented_code_extra_spaces = 0;
                events.push(BlockEvent::CodeBlockEnd);
            }
        }

        // If we're in a table, check for continuation or termination
        if self.in_table {
            let first = self.cursor.peek_or_zero();
            if first == 0 || first == b'\n' {
                if first == b'\n' {
                    self.cursor.bump();
                }
                self.close_table(events);
                self.close_paragraph(events);
                self.handle_blank_line_containers(events, false);
                return;
            }
            if indent < 4 && self.would_start_block_for_table(first, indent) {
                self.close_table(events);
                // Fall through to normal block parsing
            } else {
                self.mark_container_has_content();
                self.emit_table_row(events);
                return;
            }
        }

        // Check for setext heading underline (when in a paragraph)
        // Must check BEFORE thematic break since `---` can be either
        // Note: indent must be < 4 for a valid setext underline
        if indent < 4 && self.in_paragraph {
            if let Some(level) = self.is_setext_underline_after_indent() {
                // Strip link reference definitions before deciding on setext conversion.
                let consumed = self.extract_link_ref_defs();
                if consumed > 0 {
                    let drain_count = consumed.min(self.paragraph_lines.len());
                    self.paragraph_lines.drain(0..drain_count);
                }
                if self.paragraph_lines.is_empty() {
                    // No paragraph content left after stripping definitions; not a setext heading.
                    // Treat this line as normal paragraph content.
                    let line_start = self.cursor.offset();
                    self.parse_paragraph_line(line_start, events);
                    return;
                } else {
                    // Skip to end of line
                    while !self.cursor.is_eof() && !self.cursor.at(b'\n') {
                        self.cursor.bump();
                    }
                    if !self.cursor.is_eof() {
                        self.cursor.bump();
                    }
                    // Convert paragraph to heading
                    self.close_paragraph_as_setext_heading(level, events);
                    return;
                }
            }
        }

        // Check for GFM table delimiter row at top level (when in a paragraph)
        // Quick guard: delimiter rows start with |, -, or :
        if self.options.tables
            && indent < 4
            && self.in_paragraph
            && matches!(self.cursor.peek_or_zero(), b'|' | b'-' | b':')
        {
            let save_pos = self.cursor.offset();
            let save_partial = self.partial_tab_cols;
            let save_col = self.current_col;

            let line_end = {
                let mut p = save_pos;
                while p < self.input.len() && self.input[p] != b'\n' {
                    p += 1;
                }
                p
            };
            let line = &self.input[save_pos..line_end];

            if let Some(alignments) = Self::is_delimiter_row(line) {
                if !self.paragraph_lines.is_empty() {
                    let last_para_line = self.paragraph_lines.last().unwrap();
                    let header_line = last_para_line.slice(self.input);
                    let header_cells = Self::split_table_cells(header_line);

                    if header_cells.len() == alignments.len() {
                        self.cursor = Cursor::new_at(self.input, line_end);
                        if !self.cursor.is_eof() && self.cursor.at(b'\n') {
                            self.cursor.bump();
                        }
                        self.start_table(header_cells, alignments, events);
                        return;
                    }
                }
            }

            self.cursor = Cursor::new_at(self.input, save_pos);
            self.partial_tab_cols = save_partial;
            self.current_col = save_col;
        }

        // Check for thematic break (also when all containers matched, e.g. inside blockquote)
        if indent < 4 && self.try_thematic_break(events) {
            return;
        }

        // Check for new container starts (blockquote, list)
        if indent < 4 && self.container_stack.len() < limits::MAX_BLOCK_NESTING {
            // Check for blockquote
            if self.try_blockquote(events) {
                // Recursively parse the rest of the line
                self.parse_line_content(events);
                return;
            }

            // Check for list item - either continuing an existing list or starting new
            // Pass the pre-marker indent so content_indent can be calculated correctly
            if self.try_list_item(indent, events) {
                self.parse_line_content(events);
                return;
            }
        }

        // Check for indented code block (4+ spaces, not in paragraph)
        if indent >= 4 && !self.in_paragraph {
            self.start_indented_code(indent, events);
            return;
        }

        // Parse regular block content (pass known indent to avoid re-measuring)
        self.parse_line_content_with_indent(indent, events);
    }

    /// Fast path: parse consecutive simple paragraph lines at top level.
    /// Returns true if it consumed at least one line.
    fn parse_simple_paragraph_run(&mut self, events: &mut Vec<BlockEvent>) -> bool {
        if self.html_block.is_some()
            || self.fence_state.is_some()
            || self.in_indented_code
            || self.in_table
            || !self.container_stack.is_empty()
        {
            return false;
        }

        let mut consumed_any = false;
        loop {
            let line_start = self.cursor.offset();

            // Reset column tracking at the start of each line
            self.partial_tab_cols = 0;
            self.current_col = 0;

            let (indent, indent_bytes) = self.skip_indent();
            self.line_indent_bytes = indent_bytes;

            let first = self.cursor.peek_or_zero();
            if first == 0 || first == b'\n' {
                if !self.cursor.is_eof() && self.cursor.at(b'\n') {
                    self.cursor.bump();
                }
                self.close_paragraph(events);
                return true;
            }

            if indent >= 4 || !is_simple_line_start(first) {
                self.cursor = Cursor::new_at(self.input, line_start);
                return consumed_any;
            }

            // When tables are enabled and we're in a paragraph, bail on lines
            // that could be delimiter rows (starting with ':' or '-')
            // '-' is already caught by is_simple_line_start above.
            if self.options.tables && self.in_paragraph && first == b':' {
                self.cursor = Cursor::new_at(self.input, line_start);
                return consumed_any;
            }

            // When footnotes are enabled, bail on lines starting with `[`
            // since they could be footnote definitions `[^label]:`
            if self.options.footnotes && first == b'[' {
                self.cursor = Cursor::new_at(self.input, line_start);
                return consumed_any;
            }

            self.parse_paragraph_line(self.cursor.offset(), events);
            consumed_any = true;

            if self.cursor.is_eof() {
                return true;
            }
        }
    }

    /// Check if line is blank after consuming whitespace.
    fn is_blank_line(&self) -> bool {
        let slice = self.cursor.remaining_slice();
        #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
        {
            if let Some(result) = unsafe { Self::is_blank_line_simd(slice) } {
                return result;
            }
        }
        Self::is_blank_line_scalar(slice)
    }

    #[inline]
    fn is_blank_line_scalar(slice: &[u8]) -> bool {
        for &b in slice {
            if b == b' ' || b == b'\t' {
                continue;
            }
            return b == b'\n';
        }
        true // EOF is treated as blank
    }

    #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
    #[target_feature(enable = "neon")]
    #[allow(unsafe_op_in_unsafe_fn)]
    unsafe fn is_blank_line_simd(slice: &[u8]) -> Option<bool> {
        if slice.len() < 16 {
            return None;
        }

        let ptr = slice.as_ptr();
        let mut pos = 0usize;
        let len = slice.len();
        while pos + 16 <= len {
            let v = vld1q_u8(ptr.add(pos));
            let nl_mask = vceqq_u8(v, vdupq_n_u8(b'\n'));
            if vmaxvq_u8(nl_mask) != 0 {
                break;
            }
            let space_mask = vceqq_u8(v, vdupq_n_u8(b' '));
            let tab_mask = vceqq_u8(v, vdupq_n_u8(b'\t'));
            let ws_mask = vorrq_u8(space_mask, tab_mask);
            if vminvq_u8(ws_mask) != 0xFF {
                return Some(false);
            }
            pos += 16;
        }

        for &b in &slice[pos..] {
            if b == b' ' || b == b'\t' {
                continue;
            }
            return Some(b == b'\n');
        }
        Some(true)
    }

    /// Calculate the column that a tab at the given column would expand to.
    #[inline]
    fn tab_column(col: usize) -> usize {
        (col + 4) & !3
    }

    /// Skip whitespace (spaces and tabs) returning (columns, bytes).
    /// Includes any remaining columns from a partially-consumed tab.
    /// Uses self.current_col for correct tab expansion and updates it.
    fn skip_indent(&mut self) -> (usize, usize) {
        // Add any remaining columns from a partially-consumed tab
        let partial = self.partial_tab_cols;
        self.partial_tab_cols = 0;

        let start_col = self.current_col;
        let mut bytes = 0;
        while let Some(b) = self.cursor.peek() {
            if b == b' ' {
                self.current_col += 1;
                bytes += 1;
                self.cursor.bump();
            } else if b == b'\t' {
                self.current_col = Self::tab_column(self.current_col);
                bytes += 1;
                self.cursor.bump();
            } else {
                break;
            }
        }
        // Return the number of columns measured PLUS any partial tab carryover
        (self.current_col - start_col + partial, bytes)
    }

    /// Skip up to `max_cols` columns of whitespace, returning (columns_skipped, bytes_skipped).
    /// If a tab would exceed max_cols, consumes the tab and stores excess in partial_tab_cols.
    /// Uses self.current_col for correct tab expansion and updates it.
    fn skip_indent_max(&mut self, max_cols: usize) -> (usize, usize) {
        // Include any carryover from previous partial tab
        let partial = self.partial_tab_cols;
        self.partial_tab_cols = 0;

        // If we already have enough from partial tab, just return
        if partial >= max_cols {
            self.partial_tab_cols = partial - max_cols;
            return (max_cols, 0);
        }

        let mut bytes = 0;
        let mut cols_counted = partial;

        while cols_counted < max_cols {
            match self.cursor.peek() {
                Some(b' ') => {
                    cols_counted += 1;
                    self.current_col += 1;
                    bytes += 1;
                    self.cursor.bump();
                }
                Some(b'\t') => {
                    let next_col = Self::tab_column(self.current_col);
                    let tab_width = next_col - self.current_col;
                    let cols_needed = max_cols - cols_counted;
                    if tab_width <= cols_needed {
                        cols_counted += tab_width;
                        self.current_col = next_col;
                        bytes += 1;
                        self.cursor.bump();
                    } else {
                        // Tab would exceed max_cols - consume it but save excess
                        self.partial_tab_cols = tab_width - cols_needed;
                        self.current_col = next_col;
                        bytes += 1;
                        self.cursor.bump();
                        return (max_cols, bytes);
                    }
                }
                _ => break,
            }
        }
        (cols_counted, bytes)
    }

    /// Parse line content after container markers have been handled.
    /// Measures indent from current position.
    fn parse_line_content(&mut self, events: &mut Vec<BlockEvent>) {
        let (indent, indent_bytes) = self.skip_indent();
        self.line_indent_bytes = indent_bytes;
        self.parse_line_content_with_indent(indent, events);
    }

    /// Parse line content with a known indent value.
    /// Cursor should already be past the leading whitespace.
    fn parse_line_content_with_indent(&mut self, indent: usize, events: &mut Vec<BlockEvent>) {
        let first = self.cursor.peek_or_zero();

        // Check for blank line (can happen after container markers)
        if first == 0 || first == b'\n' {
            if first == b'\n' {
                self.cursor.bump();
            }
            self.close_table(events);
            self.close_paragraph(events);
            return;
        }

        // If we're in a table, check for continuation or termination
        if self.in_table {
            // Check if the line starts a block construct that would terminate the table
            if indent < 4 && self.would_start_block_for_table(first, indent) {
                self.close_table(events);
                // Fall through to normal block parsing
            } else {
                // Parse as table data row
                self.mark_container_has_content();
                self.emit_table_row(events);
                return;
            }
        }

        // Try to parse block-level constructs (only if indent < 4)
        if indent < 4 {
            if is_simple_line_start(first)
                && !(self.options.tables && (first == b'|' || (first == b':' && self.in_paragraph)))
                && !(self.options.footnotes && first == b'[')
            {
                let line_start = self.cursor.offset();
                self.parse_paragraph_line(line_start, events);
                return;
            }

            // Check for setext heading underline (when in a paragraph)
            // Must check BEFORE thematic break since `---` can be either
            if self.in_paragraph && matches!(first, b'=' | b'-') {
                if let Some(level) = self.is_setext_underline_after_indent() {
                    // Skip to end of line
                    while !self.cursor.is_eof() && !self.cursor.at(b'\n') {
                        self.cursor.bump();
                    }
                    if !self.cursor.is_eof() {
                        self.cursor.bump();
                    }
                    // Convert paragraph to heading
                    self.close_paragraph_as_setext_heading(level, events);
                    return;
                }
            }

            // Check for GFM table delimiter row (when in a paragraph)
            // Must check BEFORE thematic break since `---` lines can be delimiter rows
            // Quick guard: delimiter rows start with |, -, or :
            if self.options.tables && self.in_paragraph && matches!(first, b'|' | b'-' | b':') {
                let save_pos = self.cursor.offset();
                let save_partial = self.partial_tab_cols;
                let save_col = self.current_col;

                // Read the current line to check if it's a delimiter row
                let line_end = {
                    let mut p = save_pos;
                    while p < self.input.len() && self.input[p] != b'\n' {
                        p += 1;
                    }
                    p
                };
                let line = &self.input[save_pos..line_end];

                if let Some(alignments) = Self::is_delimiter_row(line) {
                    // Check cell count of the last paragraph line matches
                    if !self.paragraph_lines.is_empty() {
                        let last_para_line = self.paragraph_lines.last().unwrap();
                        let header_line = last_para_line.slice(self.input);
                        let header_cells = Self::split_table_cells(header_line);

                        if header_cells.len() == alignments.len() {
                            // We have a table! Convert the paragraph.
                            // Skip the delimiter row
                            self.cursor = Cursor::new_at(self.input, line_end);
                            if !self.cursor.is_eof() && self.cursor.at(b'\n') {
                                self.cursor.bump();
                            }

                            self.start_table(header_cells, alignments, events);
                            return;
                        }
                    }
                }

                // Not a delimiter row, restore cursor
                self.cursor = Cursor::new_at(self.input, save_pos);
                self.partial_tab_cols = save_partial;
                self.current_col = save_col;
            }

            // Check for thematic break FIRST - `* * *` is a thematic break, not a list
            if matches!(first, b'-' | b'*' | b'_') && self.try_thematic_break(events) {
                return;
            }

            // Check for footnote definition (`[^label]:`)
            if self.options.footnotes
                && first == b'['
                && !self.in_paragraph
                && self.try_footnote_definition(indent, events)
            {
                // Parse the rest of the first line as content inside the footnote
                self.parse_line_content(events);
                return;
            }

            // Check for nested containers (blockquote, list)
            if self.container_stack.len() < limits::MAX_BLOCK_NESTING {
                // Check for blockquote
                if first == b'>' && self.try_blockquote(events) {
                    // Recursively parse the rest of the line
                    self.parse_line_content(events);
                    return;
                }

                // Check for list item (pass indent for absolute content_indent calculation)
                if is_list_marker_start(first) && self.try_list_item(indent, events) {
                    self.parse_line_content(events);
                    return;
                }
            }

            // Check for HTML block
            if self.options.allow_html && first == b'<' && self.try_html_block_start(indent, events)
            {
                return;
            }

            // Check for fenced code block
            if matches!(first, b'`' | b'~') && self.try_code_fence(indent, events) {
                return;
            }

            // Check for ATX heading
            if first == b'#' && self.try_atx_heading(events) {
                return;
            }
        }

        // Check for indented code block (4+ spaces, not in paragraph)
        if indent >= 4 && !self.in_paragraph {
            self.start_indented_code(indent, events);
            return;
        }

        // Otherwise, it's paragraph content
        let line_start = self.cursor.offset();
        self.parse_paragraph_line(line_start, events);
    }

    /// Try to match existing containers at line start.
    /// Returns number of matched containers.
    fn match_containers(&mut self, _events: &mut Vec<BlockEvent>) -> usize {
        if self.container_stack.is_empty() {
            return 0;
        }

        let mut matched = 0;
        // Track the deepest list that matched with non-blank content
        // (this is the level where a blank line would make the list loose)
        let mut deepest_list_match: Option<usize> = None;

        for i in 0..self.container_stack.len() {
            let container = &self.container_stack[i];
            match container.typ {
                ContainerType::BlockQuote => {
                    // Try to match `>` marker with up to 3 leading spaces/tabs
                    let save_pos = self.cursor.offset();
                    let save_partial = self.partial_tab_cols;
                    let save_col = self.current_col;
                    let (cols, _bytes) = self.skip_indent();
                    if cols <= 3 && self.cursor.at(b'>') {
                        self.cursor.bump();
                        self.current_col += 1;
                        // Optional space after > - use skip_indent_max(1) for proper tab handling
                        self.skip_indent_max(1);
                        matched += 1;
                    } else {
                        // Can't continue blockquote, reset cursor and break
                        self.cursor = Cursor::new_at(self.input, save_pos);
                        self.partial_tab_cols = save_partial;
                        self.current_col = save_col;
                        break;
                    }
                }
                ContainerType::ListItem {
                    content_indent,
                    kind,
                    marker,
                } => {
                    // Check if line is blank (after any spaces we've consumed so far)
                    let remaining = self.cursor.remaining_slice();
                    let is_blank = remaining.is_empty()
                        || remaining[0] == b'\n'
                        || remaining
                            .iter()
                            .take_while(|&&b| b == b' ' || b == b'\t')
                            .count()
                            == remaining.len().min(
                                remaining
                                    .iter()
                                    .position(|&b| b == b'\n')
                                    .unwrap_or(remaining.len()),
                            );

                    if is_blank {
                        // Blank lines always match list items
                        matched += 1;
                    } else {
                        // Save position, partial tab state, and column
                        let save_pos = self.cursor.offset();
                        let save_partial = self.partial_tab_cols;
                        let save_col = self.current_col;
                        let (cols, _bytes) = self.skip_indent();

                        if cols >= content_indent {
                            // Enough indent to continue the list item
                            // We need to position the cursor so that only content_indent
                            // columns have been consumed. This is tricky with tabs.
                            // Rewind and skip exactly content_indent columns.
                            self.cursor = Cursor::new_at(self.input, save_pos);
                            self.partial_tab_cols = save_partial;
                            self.current_col = save_col;
                            let (_skipped_cols, _skipped_bytes) =
                                self.skip_indent_max(content_indent);
                            // Now cursor is past content_indent columns worth of whitespace
                            // Any excess from partial tab consumption is in partial_tab_cols

                            // Track this list as a potential loose candidate
                            let list_index = self.container_stack[..=i]
                                .iter()
                                .filter(|c| matches!(c.typ, ContainerType::ListItem { .. }))
                                .count();
                            if list_index > 0 {
                                deepest_list_match = Some(list_index - 1);
                            }
                            matched += 1;
                        } else {
                            // Not enough indent - check if it's a new list item of same type
                            // (cursor is already past the whitespace)
                            let is_same_list = self.peek_list_marker(kind, marker);

                            // Reset cursor, partial tab state, and column
                            self.cursor = Cursor::new_at(self.input, save_pos);
                            self.partial_tab_cols = save_partial;
                            self.current_col = save_col;

                            if is_same_list {
                                // This will start a new item in the same list
                                // Don't match this container
                                break;
                            } else {
                                // Different content, don't match
                                break;
                            }
                        }
                    }
                }
                ContainerType::FootnoteDefinition { content_indent } => {
                    // Similar to list items: blank lines match, content needs enough indent
                    let remaining = self.cursor.remaining_slice();
                    let is_blank = remaining.is_empty()
                        || remaining[0] == b'\n'
                        || remaining
                            .iter()
                            .take_while(|&&b| b == b' ' || b == b'\t')
                            .count()
                            == remaining.len().min(
                                remaining
                                    .iter()
                                    .position(|&b| b == b'\n')
                                    .unwrap_or(remaining.len()),
                            );

                    if is_blank {
                        matched += 1;
                    } else {
                        let save_pos = self.cursor.offset();
                        let save_partial = self.partial_tab_cols;
                        let save_col = self.current_col;
                        let (cols, _bytes) = self.skip_indent();

                        if cols >= content_indent {
                            self.cursor = Cursor::new_at(self.input, save_pos);
                            self.partial_tab_cols = save_partial;
                            self.current_col = save_col;
                            let (_skipped_cols, _skipped_bytes) =
                                self.skip_indent_max(content_indent);
                            matched += 1;
                        } else {
                            self.cursor = Cursor::new_at(self.input, save_pos);
                            self.partial_tab_cols = save_partial;
                            self.current_col = save_col;
                            break;
                        }
                    }
                }
            }
        }

        // After matching, mark the deepest matched list as loose if it had a blank line.
        // This ensures the blank only affects the innermost level that actually continues.
        if let Some(list_idx) = deepest_list_match {
            if let Some(open_list) = self.open_lists.get_mut(list_idx) {
                if open_list.blank_in_item {
                    open_list.tight = false;
                }
            }
            // Clear blank_in_item for all outer lists - the blank was "consumed" by the deeper level
            for outer_list in self.open_lists[..list_idx].iter_mut() {
                outer_list.blank_in_item = false;
            }
        }

        // Don't close containers here - let parse_line handle it
        matched
    }

    /// Peek ahead to see if there's a list marker of the same type.
    fn peek_list_marker(&self, kind: ListKind, marker: u8) -> bool {
        let b = match self.cursor.peek() {
            Some(b) => b,
            None => return false,
        };

        match kind {
            ListKind::Unordered => {
                // Must be the SAME marker character (-, *, or +)
                // Followed by space, tab, or newline (blank list item)
                if b != marker {
                    return false;
                }
                let after = self.cursor.peek_ahead(1);
                after == Some(b' ')
                    || after == Some(b'\t')
                    || after == Some(b'\n')
                    || after.is_none()
            }
            ListKind::Ordered { delimiter, .. } => {
                // Must be digit(s) followed by the SAME delimiter (. or ))
                if !b.is_ascii_digit() {
                    return false;
                }
                // Find the delimiter after the digits
                let mut offset = 1;
                while self
                    .cursor
                    .peek_ahead(offset)
                    .is_some_and(|b| b.is_ascii_digit())
                {
                    offset += 1;
                }
                // Check if delimiter matches
                if self.cursor.peek_ahead(offset) != Some(delimiter) {
                    return false;
                }
                // Must be followed by space, tab, or newline
                let after = self.cursor.peek_ahead(offset + 1);
                after == Some(b' ')
                    || after == Some(b'\t')
                    || after == Some(b'\n')
                    || after.is_none()
            }
        }
    }

    /// Check if we can do lazy continuation for a container (blockquote or list item).
    /// Returns true if:
    /// 1. We're in a paragraph
    /// 2. The first unmatched container is a blockquote or list item
    /// 3. The current line doesn't start a new block
    fn can_lazy_continue(&self, matched: usize, indent: usize) -> bool {
        // Must be in a paragraph to do lazy continuation
        if !self.in_paragraph {
            return false;
        }

        // Must have unmatched containers
        if matched >= self.container_stack.len() {
            return false;
        }

        // The first unmatched container must be a blockquote or list item
        // (CommonMark allows lazy continuation for paragraphs in both)
        let container = &self.container_stack[matched];
        let is_lazy_container = matches!(
            container.typ,
            ContainerType::BlockQuote | ContainerType::ListItem { .. }
        );
        if !is_lazy_container {
            return false;
        }

        // Note: we don't check indent >= 4 for indented code here because
        // we're in a paragraph. Indented code blocks can only start when
        // NOT in a paragraph.

        // Check if the current line would start a new block
        // Pass indent to would_start_block so it can ignore block starts
        // at 4+ indent (which become continuation or indented code)
        !self.would_start_block(indent)
    }

    /// Check if the current position would start a new block.
    /// Used for lazy continuation checks.
    /// `indent` is the number of spaces at the start of the line (before current position).
    fn would_start_block(&self, indent: usize) -> bool {
        let b = self.cursor.peek_or_zero();
        if b == 0 {
            return false;
        }

        match b {
            // ATX heading - only at indent < 4
            b'#' => indent < 4,
            // Fenced code block - only at indent < 4
            b'`' | b'~' => {
                indent < 4
                    && self
                        .cursor
                        .remaining_slice()
                        .iter()
                        .take_while(|&&c| c == b)
                        .count()
                        >= 3
            }
            // Blockquote - only at indent < 4
            b'>' => indent < 4,
            // Unordered list marker or thematic break - only at indent < 4
            b'-' | b'*' | b'+' => {
                if indent >= 4 {
                    // At 4+ indent, thematic breaks are still possible
                    return self.peek_thematic_break();
                }
                // Check if followed by space/tab/newline (list item) or if it's a thematic break
                let after = self.cursor.peek_ahead(1);
                after == Some(b' ')
                    || after == Some(b'\t')
                    || after == Some(b'\n')
                    || after.is_none()
                    || self.peek_thematic_break()
            }
            // Ordered list marker - only at indent < 4
            b'0'..=b'9' => {
                if indent >= 4 {
                    return false;
                }
                // Check if digit(s) followed by . or ) then space/tab/newline
                let mut offset = 1;
                while self
                    .cursor
                    .peek_ahead(offset)
                    .is_some_and(|c| c.is_ascii_digit())
                {
                    offset += 1;
                }
                let delim = self.cursor.peek_ahead(offset);
                if delim != Some(b'.') && delim != Some(b')') {
                    return false;
                }
                let after = self.cursor.peek_ahead(offset + 1);
                after == Some(b' ')
                    || after == Some(b'\t')
                    || after == Some(b'\n')
                    || after.is_none()
            }
            // HTML block (only types that can interrupt paragraphs) - only at indent < 4
            b'<' => indent < 4 && self.peek_html_block_start(true).is_some(),
            // Note: We don't check for setext underlines (= or plain line of -) here because
            // setext underlines can't interrupt lazy continuation. They only work when the
            // paragraph is at the same container level as the underline.
            // Blank or other content - not a block start
            _ => false,
        }
    }

    /// Close containers starting from index, being smart about lists.
    /// `indent` is the current line's indent - used to determine if a new list item is possible.
    fn close_containers_from(&mut self, from: usize, indent: usize, events: &mut Vec<BlockEvent>) {
        self.close_table(events);

        // Check if we're about to close a list item but might start a new one
        while self.container_stack.len() > from {
            let top = self.container_stack.last().unwrap();

            // Only consider "same list" continuation if:
            // 1. This is the LAST container we need to close
            // 2. The indent is < 4 (otherwise we can't start a new item)
            let is_last_to_close = self.container_stack.len() == from + 1;
            let can_start_new_item = indent < 4;

            if is_last_to_close && can_start_new_item {
                if let ContainerType::ListItem { kind, marker, .. } = top.typ {
                    // Check if the current position has a same-type list marker
                    let save_pos = self.cursor.offset();
                    let save_partial = self.partial_tab_cols;
                    let save_col = self.current_col;
                    self.skip_indent();
                    let is_same_list = self.peek_list_marker(kind, marker);
                    self.cursor = Cursor::new_at(self.input, save_pos);
                    self.partial_tab_cols = save_partial;
                    self.current_col = save_col;

                    if is_same_list {
                        // Just close the item, not the list
                        self.container_stack.pop();
                        self.close_paragraph(events);
                        events.push(BlockEvent::ListItemEnd);
                        // Don't pop from open_lists
                        continue;
                    }
                }
            }

            self.close_top_container(events);
        }
    }

    /// Handle blank line for container continuation.
    /// `close_blockquotes`: true if this is a truly blank line (no `>` markers),
    /// false if the line had container markers but blank content.
    fn handle_blank_line_containers(
        &mut self,
        events: &mut Vec<BlockEvent>,
        close_blockquotes: bool,
    ) {
        // A blank line (without > marker) closes blockquotes
        if close_blockquotes {
            // Close all blockquote containers from the top
            while let Some(container) = self.container_stack.last() {
                if container.typ == ContainerType::BlockQuote {
                    self.close_top_container(events);
                } else {
                    break;
                }
            }
        }

        // Two-blank-line rule: a list item can begin with at most one blank line.
        // If the innermost list item has no content and we see a blank line, close it.
        // But keep the list open - only close the item.
        if let Some(container) = self.container_stack.last() {
            if let ContainerType::ListItem { .. } = container.typ {
                if !container.has_content {
                    // This is the second blank line (first was the blank item itself)
                    // Close just the list item, not the list
                    self.container_stack.pop();
                    self.close_paragraph(events);
                    events.push(BlockEvent::ListItemEnd);
                    // Mark blank_in_item for the list - the blank line is between items,
                    // which will make the list loose when the next item starts.
                    if let Some(open_list) = self.open_lists.last_mut() {
                        open_list.blank_in_item = true;
                    }
                    return; // Already handled blank marking for this case
                }
            }
        }

        // Mark all lists with an active item as having seen a blank line.
        // We don't know yet which level the blank is at - that's determined
        // when we see the continuation line.
        //
        // BUT: If close_blockquotes is false, the line had container markers (like `>`).
        // If there's a blockquote on the stack, the blank is inside the blockquote,
        // not directly in the list item, so don't mark the list.
        if !close_blockquotes {
            if let Some(container) = self.container_stack.last() {
                if container.typ == ContainerType::BlockQuote {
                    // The blank is inside a blockquote, not between list item blocks
                    return;
                }
            }
        }

        let active_list_count = self
            .container_stack
            .iter()
            .filter(|c| matches!(c.typ, ContainerType::ListItem { .. }))
            .count();
        let start_idx = self.open_lists.len().saturating_sub(active_list_count);
        for open_list in self.open_lists[start_idx..].iter_mut() {
            open_list.blank_in_item = true;
        }
    }

    /// Try to start a blockquote.
    fn try_blockquote(&mut self, events: &mut Vec<BlockEvent>) -> bool {
        if !self.cursor.at(b'>') {
            return false;
        }

        self.cursor.bump(); // consume >
        self.current_col += 1;

        // Optional space after > (consumes 1 column of whitespace)
        // Use skip_indent_max(1) to properly handle partial tab consumption.
        // If it's a tab, the excess columns are stored in partial_tab_cols.
        self.skip_indent_max(1);

        // Try to detect callout marker [!TYPE] on first line
        let callout = if self.options.callouts {
            self.try_callout_type()
        } else {
            None
        };

        // Close paragraph if any
        self.close_paragraph(events);

        // Mark the current container as having content (before pushing new container)
        self.mark_container_has_content();

        // Push blockquote container
        self.container_stack.push(Container {
            typ: ContainerType::BlockQuote,
            has_content: false,
        });

        events.push(BlockEvent::BlockQuoteStart { callout });
        true
    }

    /// Try to detect a callout type marker `[!TYPE]` at the current cursor position.
    /// If found, consumes the marker and trailing whitespace/newline. Returns the type.
    /// If not found, cursor is unchanged.
    fn try_callout_type(&mut self) -> Option<CalloutType> {
        let saved_offset = self.cursor.offset();

        // Check for `[!`
        if !self.cursor.at(b'[') {
            return None;
        }
        self.cursor.bump();
        if !self.cursor.at(b'!') {
            self.cursor = Cursor::new_at(self.input, saved_offset);
            return None;
        }
        self.cursor.bump();

        // Read ASCII alpha type name
        let type_start = self.cursor.offset();
        while self.cursor.peek().is_some_and(|b| b.is_ascii_alphabetic()) {
            self.cursor.bump();
        }
        let type_end = self.cursor.offset();

        if type_end == type_start {
            // Empty type name
            self.cursor = Cursor::new_at(self.input, saved_offset);
            return None;
        }

        // Must close with `]`
        if !self.cursor.at(b']') {
            self.cursor = Cursor::new_at(self.input, saved_offset);
            return None;
        }
        self.cursor.bump();

        // After `]`, only optional whitespace allowed before newline/EOF
        while self.cursor.peek().is_some_and(|b| b == b' ' || b == b'\t') {
            self.cursor.bump();
        }
        if !self.cursor.is_eof() && !self.cursor.at(b'\n') && !self.cursor.at(b'\r') {
            // Non-whitespace after `]` — not a callout
            self.cursor = Cursor::new_at(self.input, saved_offset);
            return None;
        }

        // Match type name case-insensitively
        let type_bytes = &self.input[type_start..type_end];
        let callout_type = match type_bytes.len() {
            3 if type_bytes.eq_ignore_ascii_case(b"TIP") => CalloutType::Tip,
            4 if type_bytes.eq_ignore_ascii_case(b"NOTE") => CalloutType::Note,
            7 if type_bytes.eq_ignore_ascii_case(b"WARNING") => CalloutType::Warning,
            7 if type_bytes.eq_ignore_ascii_case(b"CAUTION") => CalloutType::Caution,
            9 if type_bytes.eq_ignore_ascii_case(b"IMPORTANT") => CalloutType::Important,
            _ => {
                // Unknown type — revert to regular blockquote
                self.cursor = Cursor::new_at(self.input, saved_offset);
                return None;
            }
        };

        // Don't consume the trailing newline — let parse_line_content handle
        // it as a blank line so the next line is processed through match_containers.

        Some(callout_type)
    }

    /// Try to start a list item.
    /// `pre_marker_indent` is the number of spaces before the list marker (absolute column position).
    fn try_list_item(&mut self, pre_marker_indent: usize, events: &mut Vec<BlockEvent>) -> bool {
        let start_offset = self.cursor.offset();

        // Check for unordered list marker (-, *, +)
        if let Some((marker, relative_content_indent)) = self.try_unordered_marker() {
            // CommonMark: a blank list item cannot interrupt a paragraph
            // A blank item has relative_content_indent == 2 (marker + 1 implicit space)
            let is_blank_item = relative_content_indent == 2 && self.cursor.at(b'\n');
            if self.in_paragraph && is_blank_item {
                // Reset cursor and don't start list
                self.cursor = Cursor::new_at(self.input, start_offset);
                return false;
            }

            // Absolute content_indent = spaces before marker + marker width + spaces after marker
            let absolute_content_indent = pre_marker_indent + relative_content_indent;
            self.start_list_item(ListKind::Unordered, marker, absolute_content_indent, events);
            return true;
        }

        // Check for ordered list marker (1. 2. etc)
        if let Some((start_num, relative_content_indent, delimiter)) = self.try_ordered_marker() {
            // CommonMark: an ordered list can only interrupt a paragraph if it starts with 1
            // Also, a blank list item cannot interrupt a paragraph
            let is_blank_item = self.cursor.at(b'\n');
            if self.in_paragraph && (start_num != 1 || is_blank_item) {
                // Reset cursor and don't start list
                self.cursor = Cursor::new_at(self.input, start_offset);
                return false;
            }
            // Absolute content_indent = spaces before marker + marker width + spaces after marker
            let absolute_content_indent = pre_marker_indent + relative_content_indent;
            self.start_list_item(
                ListKind::Ordered {
                    start: start_num,
                    delimiter,
                },
                delimiter,
                absolute_content_indent,
                events,
            );
            return true;
        }

        false
    }

    /// Try to parse an unordered list marker (-, *, +).
    /// Returns (marker_char, relative_content_indent) where relative_content_indent is
    /// the column offset from marker to where content starts.
    fn try_unordered_marker(&mut self) -> Option<(u8, usize)> {
        let marker = self.cursor.peek()?;
        if marker != b'-' && marker != b'*' && marker != b'+' {
            return None;
        }

        // Must be followed by space or tab or newline
        let after_marker = self.cursor.peek_ahead(1);
        if after_marker != Some(b' ') && after_marker != Some(b'\t') && after_marker != Some(b'\n')
        {
            // Could be thematic break for - and *
            return None;
        }

        self.cursor.bump(); // consume marker (1 column)
        self.current_col += 1;

        // Handle blank list item (marker followed by newline)
        if self.cursor.at(b'\n') {
            return Some((marker, 2)); // marker + 1 implicit space
        }

        // Count columns of whitespace between marker and content
        let pos_after_marker = self.cursor.offset();
        let col_after_marker = self.current_col;
        let partial_after_marker = self.partial_tab_cols;
        let (cols_after_marker, _bytes_after_marker) = self.skip_indent();

        // Check if this is a blank list item (only whitespace after marker)
        if self.cursor.at(b'\n') || self.cursor.is_eof() {
            // Blank list item: content_indent = marker(1) + 1 implicit space
            // Reset cursor to after just 1 space/tab column
            self.cursor = Cursor::new_at(self.input, pos_after_marker);
            self.current_col = col_after_marker;
            self.partial_tab_cols = partial_after_marker;
            self.skip_indent_max(1);
            return Some((marker, 2));
        }

        // CommonMark rule: 1-4 columns after marker is normal
        // 5+ columns means blank item with indented content (only 1 counts)
        if cols_after_marker >= 5 {
            // Put cursor back to just after 1 column of whitespace
            self.cursor = Cursor::new_at(self.input, pos_after_marker);
            self.current_col = col_after_marker;
            self.partial_tab_cols = partial_after_marker;
            self.skip_indent_max(1);
            // content_indent = marker(1) + 1 column
            return Some((marker, 2));
        }

        // content_indent = marker(1) + cols_after_marker
        Some((marker, 1 + cols_after_marker))
    }

    /// Try to parse an ordered list marker (1. 2. etc).
    /// Returns (number, relative_content_indent, delimiter) where delimiter is '.' or ')'.
    /// relative_content_indent is in columns.
    fn try_ordered_marker(&mut self) -> Option<(u32, usize, u8)> {
        let start = self.cursor.offset();
        let start_col = self.current_col;
        let mut num: u32 = 0;
        let mut digits = 0;

        // Parse digits
        while let Some(b) = self.cursor.peek() {
            if b.is_ascii_digit() {
                if digits >= limits::MAX_LIST_MARKER_DIGITS {
                    // Too many digits, reset and return
                    self.cursor = Cursor::new_at(self.input, start);
                    self.current_col = start_col;
                    return None;
                }
                num = num * 10 + (b - b'0') as u32;
                digits += 1;
                self.cursor.bump();
                self.current_col += 1;
            } else {
                break;
            }
        }

        if digits == 0 {
            return None;
        }

        // Must be followed by . or )
        let delimiter = match self.cursor.peek() {
            Some(b'.') => b'.',
            Some(b')') => b')',
            _ => {
                self.cursor = Cursor::new_at(self.input, start);
                self.current_col = start_col;
                return None;
            }
        };
        self.cursor.bump(); // consume . or )
        self.current_col += 1;

        // Must be followed by space, tab, or newline
        if !self.cursor.at(b' ') && !self.cursor.at(b'\t') && !self.cursor.at(b'\n') {
            self.cursor = Cursor::new_at(self.input, start);
            self.current_col = start_col;
            return None;
        }

        // Handle blank list item (marker followed by newline)
        if self.cursor.at(b'\n') {
            // relative_content_indent = digits + delimiter + 1 implicit space
            let relative_content_indent = digits + 2;
            return Some((num, relative_content_indent, delimiter));
        }

        // Count columns of whitespace between marker and content
        let pos_after_delim = self.cursor.offset();
        let col_after_delim = self.current_col;
        let partial_after_delim = self.partial_tab_cols;
        let (cols_after_marker, _bytes) = self.skip_indent();

        // Check if this is a blank list item (only whitespace after marker)
        if self.cursor.at(b'\n') || self.cursor.is_eof() {
            // Blank list item: relative_content_indent = digits + delimiter + 1 column
            // Reset cursor to after just 1 column of whitespace
            self.cursor = Cursor::new_at(self.input, pos_after_delim);
            self.current_col = col_after_delim;
            self.partial_tab_cols = partial_after_delim;
            self.skip_indent_max(1);
            let relative_content_indent = digits + 2;
            return Some((num, relative_content_indent, delimiter));
        }

        // CommonMark rule: 1-4 columns after marker is normal
        // 5+ columns means blank item with indented content (only 1 counts)
        if cols_after_marker >= 5 {
            // Put cursor back to just after 1 column of whitespace
            self.cursor = Cursor::new_at(self.input, pos_after_delim);
            self.current_col = col_after_delim;
            self.partial_tab_cols = partial_after_delim;
            self.skip_indent_max(1);
            // relative_content_indent = digits + delimiter(1) + 1 column
            let relative_content_indent = digits + 2;
            return Some((num, relative_content_indent, delimiter));
        }

        // relative_content_indent = digits + delimiter(1) + cols_after_marker
        let relative_content_indent = digits + 1 + cols_after_marker;
        Some((num, relative_content_indent, delimiter))
    }

    /// Start a new list item.
    fn start_list_item(
        &mut self,
        kind: ListKind,
        marker: u8,
        content_indent: usize,
        events: &mut Vec<BlockEvent>,
    ) {
        // Close paragraph if any
        self.close_paragraph(events);

        // Check if we have an open list waiting for more items.
        // We're continuing a list if:
        // 1. There's a compatible open list, AND
        // 2. Either we're not inside a list item, OR there are more open lists
        //    than list items in container_stack (meaning there's a nested list waiting)
        let list_item_count = self
            .container_stack
            .iter()
            .filter(|c| matches!(c.typ, ContainerType::ListItem { .. }))
            .count();
        // If open_lists.len() > list_item_count, there's a "free" open list
        // that was started but whose item was closed - we should continue it
        let has_waiting_list = self.open_lists.len() > list_item_count;
        let continuing_list = has_waiting_list && self.is_compatible_list(kind, marker);

        // Check if we're inside a list item (for the nesting case)
        let inside_list_item = list_item_count > 0;

        if !continuing_list {
            // Close any existing list items from incompatible lists
            // (but not if we're nesting inside a matched item)
            if !inside_list_item {
                while let Some(container) = self.container_stack.last() {
                    if matches!(container.typ, ContainerType::ListItem { .. }) {
                        self.close_top_container(events);
                    } else {
                        break;
                    }
                }
            }

            // Start new list (tight will be determined later)
            events.push(BlockEvent::ListStart { kind, tight: true });
            self.open_lists.push(OpenList {
                kind,
                marker,
                tight: true,
                blank_in_item: false,
                item_count: 0,
            });
        }
        // Note: if continuing_list is true, the previous item was already
        // closed by close_containers_from, so we just add the new item

        // Mark the current container as having content (before pushing new container)
        self.mark_container_has_content();

        // Push list item container
        self.container_stack.push(Container {
            typ: ContainerType::ListItem {
                kind,
                marker,
                content_indent,
            },
            has_content: false,
        });

        // Track item count and blank line status for tight/loose detection
        if let Some(open_list) = self.open_lists.last_mut() {
            // If we've seen a blank line since the previous item, list becomes loose
            if open_list.item_count > 0 && open_list.blank_in_item {
                open_list.tight = false;
            }
            open_list.item_count += 1;
            open_list.blank_in_item = false;
        }

        // Check for task list checkbox (only if enabled)
        let task = if self.options.task_lists {
            self.try_task_checkbox()
        } else {
            TaskState::None
        };

        events.push(BlockEvent::ListItemStart { task });
    }

    /// Check if we're continuing a compatible list.
    fn is_compatible_list(&self, kind: ListKind, marker: u8) -> bool {
        // Check open_lists for a compatible list
        if let Some(open_list) = self.open_lists.last() {
            return match (kind, open_list.kind) {
                // For ordered lists, delimiter (. vs )) must match
                (
                    ListKind::Ordered { delimiter: d1, .. },
                    ListKind::Ordered { delimiter: d2, .. },
                ) => d1 == d2,
                // For unordered lists, marker (-, *, +) must match
                (ListKind::Unordered, ListKind::Unordered) => open_list.marker == marker,
                _ => false,
            };
        }
        false
    }

    /// Try to parse a task list checkbox.
    fn try_task_checkbox(&mut self) -> TaskState {
        if !self.cursor.at(b'[') {
            return TaskState::None;
        }

        let checkbox_char = self.cursor.peek_ahead(1);
        if self.cursor.peek_ahead(2) != Some(b']') {
            return TaskState::None;
        }

        // Must be followed by space
        if self.cursor.peek_ahead(3) != Some(b' ') {
            return TaskState::None;
        }

        let state = match checkbox_char {
            Some(b' ') => TaskState::Unchecked,
            Some(b'x') | Some(b'X') => TaskState::Checked,
            _ => return TaskState::None,
        };

        // Consume checkbox
        self.cursor.advance(4);
        state
    }

    /// Close the topmost container.
    fn close_top_container(&mut self, events: &mut Vec<BlockEvent>) {
        if let Some(container) = self.container_stack.pop() {
            // Close table first
            self.close_table(events);

            // Close paragraph first
            self.close_paragraph(events);

            // Close any open indented code block inside this container
            if self.in_indented_code {
                self.pending_code_blanks.clear();
                self.in_indented_code = false;
                events.push(BlockEvent::CodeBlockEnd);
            }

            match container.typ {
                ContainerType::BlockQuote => {
                    events.push(BlockEvent::BlockQuoteEnd);
                }
                ContainerType::ListItem { kind, .. } => {
                    events.push(BlockEvent::ListItemEnd);

                    // Count remaining ListItem containers
                    let remaining_items = self
                        .container_stack
                        .iter()
                        .filter(|c| matches!(c.typ, ContainerType::ListItem { .. }))
                        .count();

                    // Close lists until open_lists count matches remaining items
                    // This properly handles nested lists: each nesting level has one
                    // ListItem container and one open list
                    while self.open_lists.len() > remaining_items {
                        let tight = self.open_lists.last().is_none_or(|l| l.tight);
                        events.push(BlockEvent::ListEnd { kind, tight });
                        self.open_lists.pop();
                    }
                }
                ContainerType::FootnoteDefinition { .. } => {
                    self.close_footnote_definition(events);
                }
            }
        }
    }

    /// Close all containers.
    fn close_all_containers(&mut self, events: &mut Vec<BlockEvent>) {
        while !self.container_stack.is_empty() {
            self.close_top_container(events);
        }
    }

    /// Check if the current line is a thematic break without consuming input.
    fn peek_thematic_break(&self) -> bool {
        // Must start with -, *, or _
        let marker = match self.cursor.peek() {
            Some(b'-') | Some(b'*') | Some(b'_') => self.cursor.peek().unwrap(),
            _ => return false,
        };

        // Count markers and spaces
        let mut count = 0;
        let mut temp_cursor = self.cursor;

        while let Some(b) = temp_cursor.peek() {
            if b == marker {
                count += 1;
                temp_cursor.bump();
            } else if b == b' ' || b == b'\t' {
                temp_cursor.bump();
            } else if b == b'\n' {
                break;
            } else {
                // Invalid character
                return false;
            }
        }

        // Need at least 3 markers
        count >= 3
    }

    /// Try to parse a thematic break.
    /// Returns true if successful.
    fn try_thematic_break(&mut self, events: &mut Vec<BlockEvent>) -> bool {
        let _start_pos = self.cursor.offset();

        // Must start with -, *, or _
        let marker = match self.cursor.peek() {
            Some(b'-') | Some(b'*') | Some(b'_') => self.cursor.peek().unwrap(),
            _ => return false,
        };

        // Count markers and spaces
        let mut count = 0;
        let mut temp_cursor = self.cursor;

        while let Some(b) = temp_cursor.peek() {
            if b == marker {
                count += 1;
                temp_cursor.bump();
            } else if b == b' ' || b == b'\t' {
                temp_cursor.bump();
            } else if b == b'\n' {
                break;
            } else {
                // Invalid character
                return false;
            }
        }

        // Need at least 3 markers
        if count < 3 {
            return false;
        }

        // Consume the line
        self.cursor = temp_cursor;
        if !self.cursor.is_eof() && self.cursor.at(b'\n') {
            self.cursor.bump();
        }

        // Close any open paragraph
        self.close_paragraph(events);

        // Mark the current container as having content
        self.mark_container_has_content();

        events.push(BlockEvent::ThematicBreak);
        true
    }

    /// Try to parse an ATX heading.
    /// Returns true if successful.
    fn try_atx_heading(&mut self, events: &mut Vec<BlockEvent>) -> bool {
        // Must start with #
        if !self.cursor.at(b'#') {
            return false;
        }

        let _start_pos = self.cursor.offset();

        // Count # characters (1-6)
        let mut level = 0u8;
        let mut temp_cursor = self.cursor;

        while temp_cursor.at(b'#') && level < 7 {
            level += 1;
            temp_cursor.bump();
        }

        // Level must be 1-6
        if level == 0 || level > 6 {
            return false;
        }

        // Must be followed by space, tab, or end of line
        if !temp_cursor.is_eof()
            && !temp_cursor.at(b' ')
            && !temp_cursor.at(b'\t')
            && !temp_cursor.at(b'\n')
        {
            return false;
        }

        // Skip spaces after #
        temp_cursor.skip_whitespace();

        // Find content start and end
        let content_start = temp_cursor.offset();

        // Find end of line
        let line_end = match temp_cursor.find_newline() {
            Some(pos) => content_start + pos,
            None => content_start + temp_cursor.remaining(),
        };

        // Trim trailing # and spaces from content
        let content_end = self.trim_heading_end(content_start, line_end);

        // Update cursor to end of line
        self.cursor = Cursor::new_at(self.input, line_end);
        if !self.cursor.is_eof() && self.cursor.at(b'\n') {
            self.cursor.bump();
        }

        // Close any open paragraph
        self.close_paragraph(events);

        // Mark the current container as having content
        self.mark_container_has_content();

        // Emit heading events
        events.push(BlockEvent::HeadingStart { level });

        if content_end > content_start {
            events.push(BlockEvent::Text(Range::from_usize(
                content_start,
                content_end,
            )));
        }

        events.push(BlockEvent::HeadingEnd { level });

        true
    }

    /// Trim trailing # characters and spaces from heading content.
    fn trim_heading_end(&self, start: usize, end: usize) -> usize {
        if start >= end {
            return start;
        }

        let mut pos = end;

        // Trim trailing spaces
        while pos > start && (self.input[pos - 1] == b' ' || self.input[pos - 1] == b'\t') {
            pos -= 1;
        }

        // Check for closing # sequence
        let after_hashes = pos;
        while pos > start && self.input[pos - 1] == b'#' {
            pos -= 1;
        }

        // Closing hashes must be preceded by space (or be at start)
        if pos < after_hashes {
            if pos == start || self.input[pos - 1] == b' ' || self.input[pos - 1] == b'\t' {
                // Valid closing hashes, trim them and any preceding space
                while pos > start && (self.input[pos - 1] == b' ' || self.input[pos - 1] == b'\t') {
                    pos -= 1;
                }
            } else {
                // Hashes not preceded by space, keep them
                pos = after_hashes;
            }
        }

        pos
    }
    /// Check if the current position (after indent has been skipped) is a setext underline.
    /// Returns Some(level) where level is 1 for '=' and 2 for '-', or None.
    /// Unlike peek_setext_underline, this assumes indent has already been consumed.
    fn is_setext_underline_after_indent(&self) -> Option<u8> {
        let slice = self.cursor.remaining_slice();
        if slice.is_empty() {
            return None;
        }

        // Must start with = or -
        let underline_char = slice[0];
        if underline_char != b'=' && underline_char != b'-' {
            return None;
        }

        // Count the underline characters (at least 1)
        let mut pos = 0;
        while pos < slice.len() && slice[pos] == underline_char {
            pos += 1;
        }

        // Skip trailing spaces/tabs
        while pos < slice.len() && (slice[pos] == b' ' || slice[pos] == b'\t') {
            pos += 1;
        }

        // Must end at newline or EOF
        if pos < slice.len() && slice[pos] != b'\n' {
            return None;
        }

        Some(if underline_char == b'=' { 1 } else { 2 })
    }

    /// Close the paragraph as a setext heading with the given level.
    fn close_paragraph_as_setext_heading(&mut self, level: u8, events: &mut Vec<BlockEvent>) {
        if !self.in_paragraph || self.paragraph_lines.is_empty() {
            return;
        }

        self.in_paragraph = false;

        // Mark the current container as having content
        self.mark_container_has_content();

        events.push(BlockEvent::HeadingStart { level });

        // Emit text ranges for each line with soft breaks between
        // Trim trailing spaces/tabs from the last line
        let line_count = self.paragraph_lines.len();
        for (i, mut range) in self.paragraph_lines.drain(..).enumerate() {
            if i > 0 {
                events.push(BlockEvent::SoftBreak);
            }
            // Trim trailing whitespace from the last line
            if i == line_count - 1 {
                while range.end > range.start {
                    let b = self.input[(range.end - 1) as usize];
                    if b == b' ' || b == b'\t' {
                        range.end -= 1;
                    } else {
                        break;
                    }
                }
            }
            events.push(BlockEvent::Text(range));
        }

        events.push(BlockEvent::HeadingEnd { level });
    }

    /// Try to parse a fenced code block opening.
    /// Returns true if successful.
    fn try_code_fence(&mut self, indent: usize, events: &mut Vec<BlockEvent>) -> bool {
        // Must start with ` or ~
        let fence_char = match self.cursor.peek() {
            Some(b'`') | Some(b'~') => self.cursor.peek().unwrap(),
            _ => return false,
        };

        // Count fence characters (need at least 3)
        let mut fence_len = 0;
        let mut temp_cursor = self.cursor;

        while temp_cursor.at(fence_char) {
            fence_len += 1;
            temp_cursor.bump();
        }

        if fence_len < 3 {
            return false;
        }

        // For backtick fences, info string cannot contain backticks
        let _info_start = temp_cursor.offset();

        // Skip optional spaces before info string
        temp_cursor.skip_whitespace();
        let info_content_start = temp_cursor.offset();

        // Find end of line
        let line_end = match temp_cursor.find_newline() {
            Some(pos) => info_content_start + pos,
            None => info_content_start + temp_cursor.remaining(),
        };

        // Check for backticks in info string (invalid for backtick fences)
        if fence_char == b'`' {
            let info_slice = &self.input[info_content_start..line_end];
            if info_slice.contains(&b'`') {
                return false;
            }
        }

        // Trim trailing whitespace from info string
        let mut info_end = line_end;
        while info_end > info_content_start
            && (self.input[info_end - 1] == b' ' || self.input[info_end - 1] == b'\t')
        {
            info_end -= 1;
        }

        // Move cursor past the line
        self.cursor = Cursor::new_at(self.input, line_end);
        if !self.cursor.is_eof() && self.cursor.at(b'\n') {
            self.cursor.bump();
        }

        // Close any open paragraph
        self.close_paragraph(events);

        // Store fence state
        self.fence_state = Some(FenceState {
            fence_char,
            fence_len,
            indent,
        });

        // Mark the current container as having content
        self.mark_container_has_content();

        // Emit code block start with info string
        let info = if info_end > info_content_start {
            Some(Range::from_usize(info_content_start, info_end))
        } else {
            None
        };
        events.push(BlockEvent::CodeBlockStart { info });

        true
    }

    /// Start an indented code block.
    /// `indent_cols` is the number of columns of indentation measured.
    fn start_indented_code(&mut self, indent_cols: usize, events: &mut Vec<BlockEvent>) {
        // Close any open paragraph first
        self.close_paragraph(events);

        // Mark the current container as having content
        self.mark_container_has_content();

        // Start the code block
        self.in_indented_code = true;
        // Store the excess columns (indent_cols - 4) to prepend as spaces
        self.indented_code_extra_spaces = indent_cols.saturating_sub(4);
        events.push(BlockEvent::CodeBlockStart { info: None });

        // The cursor is past the whitespace bytes.
        // The cursor is past the whitespace bytes.
        let text_start = self.cursor.offset();

        // Find end of line (including newline for code blocks)
        let line_end = self.find_line_end();
        let content_end = if !self.cursor.is_eof() && self.cursor.at(b'\n') {
            self.cursor.bump();
            line_end + 1 // Include the newline
        } else {
            line_end
        };

        // Emit virtual spaces if there are extra columns beyond 4
        if self.indented_code_extra_spaces > 0 {
            events.push(BlockEvent::VirtualSpaces(
                self.indented_code_extra_spaces as u8,
            ));
        }
        // Emit the content (including newline) - use Code event to skip inline parsing
        events.push(BlockEvent::Code(Range::new(
            text_start as u32,
            content_end as u32,
        )));
    }

    /// Try to start an HTML block.
    /// Returns true if an HTML block was started and the line was consumed.
    fn try_html_block_start(&mut self, indent: usize, events: &mut Vec<BlockEvent>) -> bool {
        let kind = match self.peek_html_block_start(self.in_paragraph) {
            Some(kind) => kind,
            None => return false,
        };

        if indent >= 4 {
            return false;
        }

        // Close any open paragraph first
        self.close_paragraph(events);
        // Close any orphaned lists before starting a block
        self.close_orphaned_lists(events);
        // Mark the current container as having content
        self.mark_container_has_content();

        self.html_block = Some(kind);
        self.pending_html_indent_start =
            Some(self.cursor.offset().saturating_sub(self.line_indent_bytes));
        events.push(BlockEvent::HtmlBlockStart);

        // Consume the current line as HTML block content
        self.parse_html_block_line(events);
        true
    }

    /// Parse a single HTML block line after container matching.
    /// Called when we're inside an HTML block and containers matched.
    fn parse_html_block_line(&mut self, events: &mut Vec<BlockEvent>) {
        let kind = self.html_block.unwrap();

        let indent_start = self
            .pending_html_indent_start
            .take()
            .unwrap_or_else(|| self.cursor.offset());
        let (_indent, _) = self.skip_indent();
        let content_start = self.cursor.offset();

        // Blank line handling for types 6/7 (end on blank line)
        if (self.cursor.is_eof() || self.cursor.at(b'\n'))
            && matches!(kind, HtmlBlockKind::Type6 | HtmlBlockKind::Type7)
        {
            self.html_block = None;
            events.push(BlockEvent::HtmlBlockEnd);

            if !self.cursor.is_eof() {
                self.cursor.bump();
            }

            self.close_paragraph(events);
            let close_blockquotes = self.container_stack.is_empty();
            self.handle_blank_line_containers(events, close_blockquotes);
            return;
        }

        // Find end of line (including newline)
        let line_end = self.find_line_end();
        let content_end = if !self.cursor.is_eof() && self.cursor.at(b'\n') {
            self.cursor.bump();
            line_end + 1
        } else {
            line_end
        };

        // Emit the raw HTML line (including any indentation after container markers)
        events.push(BlockEvent::HtmlBlockText(Range::from_usize(
            indent_start,
            content_end,
        )));

        // Check for HTML block end markers (types 1-5)
        let line = &self.input[content_start..line_end];
        if self.html_block_ends(kind, line) {
            self.html_block = None;
            events.push(BlockEvent::HtmlBlockEnd);
        }
    }

    /// Check if the current line starts an HTML block.
    /// `in_paragraph` controls whether type 7 is allowed to start (it can't interrupt).
    fn peek_html_block_start(&self, in_paragraph: bool) -> Option<HtmlBlockKind> {
        let line = self.current_line_slice();
        if line.is_empty() {
            return None;
        }

        // Type 1: <script|pre|style|textarea
        if self.starts_with_tag(line, b"script")
            || self.starts_with_tag(line, b"pre")
            || self.starts_with_tag(line, b"style")
            || self.starts_with_tag(line, b"textarea")
        {
            return Some(HtmlBlockKind::Type1);
        }

        // Type 2: <!--
        if line.starts_with(b"<!--") {
            return Some(HtmlBlockKind::Type2);
        }

        // Type 3: <?
        if line.starts_with(b"<?") {
            return Some(HtmlBlockKind::Type3);
        }

        // Type 4: <![CDATA[
        if line.starts_with(b"<![CDATA[") {
            return Some(HtmlBlockKind::Type4);
        }

        // Type 5: <! + letter
        if line.starts_with(b"<!") && line.len() > 2 && line[2].is_ascii_alphabetic() {
            return Some(HtmlBlockKind::Type5);
        }

        // Type 6: block tags
        if let Some((name, tag_end)) = self.parse_html_tag_name(line) {
            if self.is_block_tag(name) && self.tag_boundary(line, tag_end) {
                return Some(HtmlBlockKind::Type6);
            }
        }

        // Type 7: any other HTML tag (cannot interrupt a paragraph)
        if in_paragraph {
            return None;
        }
        if let Some((_name, tag_end)) = self.parse_html_tag(line) {
            if line[tag_end..].iter().all(|&b| Self::is_html_whitespace(b)) {
                return Some(HtmlBlockKind::Type7);
            }
        }

        None
    }

    /// Check if an HTML block ends on this line (types 1-5).
    fn html_block_ends(&self, kind: HtmlBlockKind, line: &[u8]) -> bool {
        match kind {
            HtmlBlockKind::Type1 => {
                self.contains_ci(line, b"</script")
                    || self.contains_ci(line, b"</pre")
                    || self.contains_ci(line, b"</style")
                    || self.contains_ci(line, b"</textarea")
            }
            HtmlBlockKind::Type2 => self.contains_bytes(line, b"-->"),
            HtmlBlockKind::Type3 => self.contains_bytes(line, b"?>"),
            HtmlBlockKind::Type4 => self.contains_bytes(line, b"]]>"),
            HtmlBlockKind::Type5 => self.contains_bytes(line, b">"),
            HtmlBlockKind::Type6 | HtmlBlockKind::Type7 => false,
        }
    }

    /// Get the current line slice (from cursor to before newline).
    fn current_line_slice(&self) -> &[u8] {
        let offset = self.cursor.offset();
        let slice = &self.input[offset..];
        let end = slice
            .iter()
            .position(|&b| b == b'\n')
            .unwrap_or(slice.len());
        &slice[..end]
    }

    /// Check if line starts with "<tag" (case-insensitive) and valid boundary.
    fn starts_with_tag(&self, line: &[u8], tag: &[u8]) -> bool {
        if line.len() < tag.len() + 1 || line[0] != b'<' {
            return false;
        }
        let name_start = 1;
        let name_end = name_start + tag.len();
        if name_end > line.len() {
            return false;
        }
        if !self.eq_ignore_ascii_case(&line[name_start..name_end], tag) {
            return false;
        }
        self.tag_boundary(line, name_end)
    }

    /// Parse a valid HTML tag on a single line and return (tag_name, end_index_after_tag).
    fn parse_html_tag<'b>(&self, line: &'b [u8]) -> Option<(&'b [u8], usize)> {
        if line.first() != Some(&b'<') {
            return None;
        }
        let mut i = 1;
        let mut is_closing = false;
        if i < line.len() && line[i] == b'/' {
            is_closing = true;
            i += 1;
        }
        if i >= line.len() || !line[i].is_ascii_alphabetic() {
            return None;
        }
        let start = i;
        i += 1;
        while i < line.len() && (line[i].is_ascii_alphanumeric() || line[i] == b'-') {
            i += 1;
        }
        let name = &line[start..i];

        if is_closing {
            while i < line.len() && Self::is_html_whitespace(line[i]) {
                i += 1;
            }
            if i < line.len() && line[i] == b'>' {
                return Some((name, i + 1));
            }
            return None;
        }

        loop {
            if i >= line.len() {
                return None;
            }
            if line[i] == b'>' {
                return Some((name, i + 1));
            }
            if line[i] == b'/' {
                i += 1;
                return if i < line.len() && line[i] == b'>' {
                    Some((name, i + 1))
                } else {
                    None
                };
            }
            if !Self::is_html_whitespace(line[i]) {
                return None;
            }
            while i < line.len() && Self::is_html_whitespace(line[i]) {
                i += 1;
            }
            if i >= line.len() {
                return None;
            }
            if line[i] == b'>' {
                return Some((name, i + 1));
            }
            if line[i] == b'/' {
                i += 1;
                return if i < line.len() && line[i] == b'>' {
                    Some((name, i + 1))
                } else {
                    None
                };
            }
            if !Self::is_attr_name_start(line[i]) {
                return None;
            }
            i += 1;
            while i < line.len() && Self::is_attr_name_char(line[i]) {
                i += 1;
            }
            let ws_start = i;
            while i < line.len() && Self::is_html_whitespace(line[i]) {
                i += 1;
            }
            if i < line.len() && line[i] == b'=' {
                i += 1;
                while i < line.len() && Self::is_html_whitespace(line[i]) {
                    i += 1;
                }
                if i >= line.len() {
                    return None;
                }
                let quote = line[i];
                if quote == b'"' || quote == b'\'' {
                    i += 1;
                    let value_start = i;
                    while i < line.len() && line[i] != quote {
                        i += 1;
                    }
                    if i >= line.len() {
                        return None;
                    }
                    if i > value_start && line[i - 1] == b'\\' {
                        return None;
                    }
                    i += 1;
                } else {
                    let mut had = false;
                    while i < line.len() && !Self::is_html_whitespace(line[i]) {
                        let b = line[i];
                        if b == b'"'
                            || b == b'\''
                            || b == b'='
                            || b == b'<'
                            || b == b'>'
                            || b == b'`'
                        {
                            break;
                        }
                        had = true;
                        i += 1;
                    }
                    if !had {
                        return None;
                    }
                }
            } else {
                i = ws_start;
            }
        }
    }

    /// Parse tag name from a line starting with "<" or "</".
    /// Returns (tag_name, end_index_after_name).
    fn parse_html_tag_name<'b>(&self, line: &'b [u8]) -> Option<(&'b [u8], usize)> {
        if line.first() != Some(&b'<') {
            return None;
        }
        let mut i = 1;
        if i < line.len() && line[i] == b'/' {
            i += 1;
        }
        if i >= line.len() || !line[i].is_ascii_alphabetic() {
            return None;
        }
        let start = i;
        i += 1;
        while i < line.len() && (line[i].is_ascii_alphanumeric() || line[i] == b'-') {
            i += 1;
        }
        Some((&line[start..i], i))
    }

    /// Check if the character after tag name is a valid boundary.
    fn tag_boundary(&self, line: &[u8], idx: usize) -> bool {
        if idx >= line.len() {
            return true;
        }
        matches!(line[idx], b' ' | b'\t' | b'\n' | b'>' | b'/')
    }

    #[inline]
    fn is_html_whitespace(b: u8) -> bool {
        matches!(b, b' ' | b'\t' | b'\n' | b'\r' | b'\x0c')
    }

    #[inline]
    fn is_attr_name_start(b: u8) -> bool {
        b.is_ascii_alphabetic() || b == b'_' || b == b':'
    }

    #[inline]
    fn is_attr_name_char(b: u8) -> bool {
        Self::is_attr_name_start(b) || b.is_ascii_digit() || b == b'.' || b == b'-'
    }

    /// Check if the tag name is in the CommonMark block tag list.
    fn is_block_tag(&self, name: &[u8]) -> bool {
        if name.len() == 2 && (name[0] | 0x20) == b'h' && (b'1'..=b'6').contains(&name[1]) {
            return true;
        }

        const BLOCK_TAGS: [&[u8]; 56] = [
            b"address",
            b"article",
            b"aside",
            b"base",
            b"basefont",
            b"blockquote",
            b"body",
            b"caption",
            b"center",
            b"col",
            b"colgroup",
            b"dd",
            b"details",
            b"dialog",
            b"dir",
            b"div",
            b"dl",
            b"dt",
            b"fieldset",
            b"figcaption",
            b"figure",
            b"footer",
            b"form",
            b"frame",
            b"frameset",
            b"head",
            b"header",
            b"hr",
            b"html",
            b"iframe",
            b"legend",
            b"li",
            b"link",
            b"main",
            b"menu",
            b"menuitem",
            b"nav",
            b"noframes",
            b"ol",
            b"optgroup",
            b"option",
            b"p",
            b"param",
            b"section",
            b"source",
            b"summary",
            b"table",
            b"tbody",
            b"td",
            b"tfoot",
            b"th",
            b"thead",
            b"title",
            b"tr",
            b"track",
            b"ul",
        ];

        BLOCK_TAGS
            .iter()
            .any(|&t| self.eq_ignore_ascii_case(name, t))
    }

    #[inline]
    fn eq_ignore_ascii_case(&self, a: &[u8], b: &[u8]) -> bool {
        if a.len() != b.len() {
            return false;
        }
        a.iter()
            .zip(b.iter())
            .all(|(&x, &y)| x.eq_ignore_ascii_case(&y))
    }

    #[inline]
    fn contains_bytes(&self, haystack: &[u8], needle: &[u8]) -> bool {
        if needle.is_empty() || haystack.len() < needle.len() {
            return false;
        }
        haystack.windows(needle.len()).any(|w| w == needle)
    }

    #[inline]
    fn contains_ci(&self, haystack: &[u8], needle: &[u8]) -> bool {
        if needle.is_empty() || haystack.len() < needle.len() {
            return false;
        }
        haystack
            .windows(needle.len())
            .any(|w| self.eq_ignore_ascii_case(w, needle))
    }
    /// Find end of current line (position of \n or EOF).
    fn find_line_end(&mut self) -> usize {
        while !self.cursor.is_eof() && !self.cursor.at(b'\n') {
            self.cursor.bump();
        }
        self.cursor.offset()
    }

    /// Parse a fenced code line after container matching.
    /// Called when we're inside a fenced code block and containers matched.
    /// The cursor is at the content position (past container indent).
    fn parse_fence_line_in_container(&mut self, events: &mut Vec<BlockEvent>) {
        let fence = self.fence_state.as_ref().unwrap();
        let fence_char = fence.fence_char;
        let fence_len = fence.fence_len;
        let fence_indent = fence.indent;

        let content_pos = self.cursor.offset();

        // Check for closing fence (allow up to 3 spaces of indent)
        let mut temp_cursor = self.cursor;
        let mut cols = 0usize;
        while cols < 3 {
            match temp_cursor.peek() {
                Some(b' ') => {
                    cols += 1;
                    temp_cursor.bump();
                }
                Some(b'\t') => {
                    let next_col = Self::tab_column(cols);
                    cols = next_col;
                    temp_cursor.bump();
                }
                _ => break,
            }
        }
        if temp_cursor.at(fence_char) {
            let mut closing_len = 0;

            while temp_cursor.at(fence_char) {
                closing_len += 1;
                temp_cursor.bump();
            }

            // Closing fence must be at least as long as opening
            if closing_len >= fence_len {
                // Check that rest of line is only spaces/tabs
                temp_cursor.skip_whitespace();
                if temp_cursor.is_eof() || temp_cursor.at(b'\n') {
                    // Valid closing fence
                    self.cursor = temp_cursor;
                    if !self.cursor.is_eof() && self.cursor.at(b'\n') {
                        self.cursor.bump();
                    }

                    self.fence_state = None;
                    events.push(BlockEvent::CodeBlockEnd);
                    return;
                }
            }
        }

        // Not a closing fence, emit as code content
        // Reset to content_pos and skip up to fence_indent columns of whitespace
        self.cursor = Cursor::new_at(self.input, content_pos);
        let (_skipped_cols, _skipped_bytes) = self.skip_indent_max(fence_indent);

        let code_start = self.cursor.offset();

        // Find end of line
        let line_end = match self.cursor.find_newline() {
            Some(pos) => code_start + pos,
            None => code_start + self.cursor.remaining(),
        };

        // Include the newline in the code content range
        let content_end = if line_end < self.input.len() && self.input[line_end] == b'\n' {
            line_end + 1
        } else {
            line_end
        };

        // Move cursor past the newline
        self.cursor = Cursor::new_at(self.input, content_end);

        // Emit the code line (including newline)
        events.push(BlockEvent::Code(Range::from_usize(code_start, content_end)));
    }

    /// Parse a paragraph line.
    fn parse_paragraph_line(&mut self, _line_start: usize, events: &mut Vec<BlockEvent>) {
        // Find end of line
        let content_start = self.cursor.offset();
        let line_end = match self.cursor.find_newline() {
            Some(pos) => {
                // Advance directly instead of rebuilding the cursor at line end.
                self.cursor.advance(pos);
                let end = content_start + pos;
                self.cursor.bump(); // consume newline
                end
            }
            None => {
                let remaining = self.cursor.remaining();
                self.cursor.advance(remaining);
                content_start + remaining
            }
        };

        // If we weren't in a paragraph, we are now
        if !self.in_paragraph {
            // Before starting a paragraph, close any orphaned lists (lists with no active item)
            self.close_orphaned_lists(events);
            self.in_paragraph = true;
        }

        // Add this line to paragraph content
        // We include from original line_start to capture any leading spaces we skipped
        // Actually, use content_start which is after indent
        if line_end > content_start {
            self.paragraph_lines
                .push(Range::from_usize(content_start, line_end));
        }
    }

    // --- Table parsing ---

    /// Split a table line by unescaped `|` outside backtick code spans.
    /// Returns byte offset pairs (start, end) for each cell, trimmed of whitespace.
    /// Leading and trailing pipe are stripped.
    fn split_table_cells(line: &[u8]) -> SmallVec<[(usize, usize); 8]> {
        let mut cells = SmallVec::new();
        let len = line.len();
        if len == 0 {
            return cells;
        }

        // Strip trailing whitespace from the line
        let mut line_end = len;
        while line_end > 0 && matches!(line[line_end - 1], b' ' | b'\t') {
            line_end -= 1;
        }

        // Determine start/end after stripping leading/trailing pipes
        let mut pos = 0;
        // Skip leading whitespace before leading pipe
        while pos < line_end && matches!(line[pos], b' ' | b'\t') {
            pos += 1;
        }
        let has_leading_pipe = pos < line_end && line[pos] == b'|';
        if has_leading_pipe {
            pos += 1;
        }
        let has_trailing_pipe = line_end > pos
            && line[line_end - 1] == b'|'
            && !(line_end >= 2 && line[line_end - 2] == b'\\');
        let scan_end = if has_trailing_pipe {
            line_end - 1
        } else {
            line_end
        };

        // A line that is just a bare pipe (e.g., "|") has no content between leading/trailing
        // pipes and should not produce any cells.
        if pos >= scan_end {
            return cells;
        }

        let mut cell_start = pos;
        while pos <= scan_end {
            if pos == scan_end {
                // End of line - emit last cell
                let (s, e) = Self::trim_cell(&line[cell_start..pos], cell_start);
                cells.push((s, e));
                break;
            }

            let b = line[pos];
            if b == b'\\' && pos + 1 < scan_end {
                // Escaped character - skip next
                pos += 2;
            } else if b == b'`' {
                // Code span - skip until matching backticks
                let bt_len = {
                    let mut n = 0;
                    while pos + n < scan_end && line[pos + n] == b'`' {
                        n += 1;
                    }
                    n
                };
                pos += bt_len;
                // Find closing backtick sequence of same length
                let mut found = false;
                while pos < scan_end {
                    if line[pos] == b'`' {
                        let close_len = {
                            let mut n = 0;
                            while pos + n < scan_end && line[pos + n] == b'`' {
                                n += 1;
                            }
                            n
                        };
                        pos += close_len;
                        if close_len == bt_len {
                            found = true;
                            break;
                        }
                    } else {
                        pos += 1;
                    }
                }
                if !found {
                    // Unclosed code span - just continue
                }
            } else if b == b'|' {
                // Cell boundary
                let (s, e) = Self::trim_cell(&line[cell_start..pos], cell_start);
                cells.push((s, e));
                pos += 1;
                cell_start = pos;
                if cells.len() >= limits::MAX_TABLE_COLUMNS {
                    break;
                }
            } else {
                pos += 1;
            }
        }

        cells
    }

    /// Trim whitespace from a cell slice, returning absolute byte offsets.
    #[inline]
    fn trim_cell(cell: &[u8], base: usize) -> (usize, usize) {
        let mut s = 0;
        while s < cell.len() && matches!(cell[s], b' ' | b'\t') {
            s += 1;
        }
        let mut e = cell.len();
        while e > s && matches!(cell[e - 1], b' ' | b'\t') {
            e -= 1;
        }
        (base + s, base + e)
    }

    /// Quick pre-filter: a valid delimiter row contains only `-`, `:`, `|`, spaces, and tabs,
    /// and must have at least one `-`.
    #[inline]
    fn could_be_delimiter_row(line: &[u8]) -> bool {
        let mut has_dash = false;
        for &b in line {
            match b {
                b'-' => has_dash = true,
                b':' | b'|' | b' ' | b'\t' => {}
                _ => return false,
            }
        }
        has_dash
    }

    /// Check if a line is a valid GFM table delimiter row.
    /// Returns column alignments if valid.
    fn is_delimiter_row(line: &[u8]) -> Option<SmallVec<[Alignment; 8]>> {
        if !Self::could_be_delimiter_row(line) {
            return None;
        }
        let cells = Self::split_table_cells(line);
        if cells.is_empty() {
            return None;
        }

        let mut alignments = SmallVec::new();
        for &(start, end) in &cells {
            let cell = &line[start..end];
            if cell.is_empty() {
                return None;
            }

            let mut i = 0;
            let left_colon = cell[i] == b':';
            if left_colon {
                i += 1;
            }

            // Must have at least one dash
            let dash_start = i;
            while i < cell.len() && cell[i] == b'-' {
                i += 1;
            }
            if i == dash_start {
                return None; // No dashes
            }

            let right_colon = i < cell.len() && cell[i] == b':';
            if right_colon {
                i += 1;
            }

            // Must consume entire cell (after trimming)
            if i != cell.len() {
                return None;
            }

            let alignment = match (left_colon, right_colon) {
                (true, true) => Alignment::Center,
                (true, false) => Alignment::Left,
                (false, true) => Alignment::Right,
                (false, false) => Alignment::None,
            };
            alignments.push(alignment);

            if alignments.len() >= limits::MAX_TABLE_COLUMNS {
                break;
            }
        }

        Some(alignments)
    }

    /// Check if the current line would start a block construct that terminates a table.
    fn would_start_block_for_table(&self, first: u8, indent: usize) -> bool {
        if indent >= 4 {
            return false;
        }
        match first {
            b'#' => true, // ATX heading
            b'>' => true, // Blockquote
            b'`' | b'~' => {
                // Fenced code block (need at least 3)
                self.cursor
                    .remaining_slice()
                    .iter()
                    .take_while(|&&c| c == first)
                    .count()
                    >= 3
            }
            b'-' | b'*' | b'_' => {
                // Thematic break check
                self.peek_thematic_break()
            }
            b'<' => {
                // HTML block
                self.options.allow_html && self.peek_html_block_start(false).is_some()
            }
            _ => false,
        }
    }

    /// Start a table from the last paragraph line (header) and delimiter row.
    fn start_table(
        &mut self,
        header_cells: SmallVec<[(usize, usize); 8]>,
        alignments: SmallVec<[Alignment; 8]>,
        events: &mut Vec<BlockEvent>,
    ) {
        // Extract the last paragraph line for use as header
        let header_range = self.paragraph_lines.pop().unwrap();

        // Close any remaining paragraph content (lines before the header line)
        // These stay as a normal paragraph
        if !self.paragraph_lines.is_empty() {
            // Emit those lines as a paragraph
            self.mark_container_has_content();
            events.push(BlockEvent::ParagraphStart);
            for (i, range) in self.paragraph_lines.drain(..).enumerate() {
                if i > 0 {
                    events.push(BlockEvent::SoftBreak);
                }
                events.push(BlockEvent::Text(range));
            }
            events.push(BlockEvent::ParagraphEnd);
        }
        self.in_paragraph = false;

        // Now emit the table structure
        self.mark_container_has_content();

        events.push(BlockEvent::TableStart);
        events.push(BlockEvent::TableHeadStart);
        events.push(BlockEvent::TableRowStart);

        let header_base = header_range.start as usize;

        for (i, &alignment) in alignments.iter().enumerate() {
            events.push(BlockEvent::TableCellStart { alignment });
            if i < header_cells.len() {
                let (s, e) = header_cells[i];
                if e > s {
                    events.push(BlockEvent::Text(Range::from_usize(
                        header_base + s,
                        header_base + e,
                    )));
                }
            }
            events.push(BlockEvent::TableCellEnd);
        }

        events.push(BlockEvent::TableRowEnd);
        events.push(BlockEvent::TableHeadEnd);

        // Set table state
        self.in_table = true;
        self.table_alignments = alignments;
        self.table_has_body = false;
    }

    /// Close an open table, emitting appropriate end events.
    fn close_table(&mut self, events: &mut Vec<BlockEvent>) {
        if !self.in_table {
            return;
        }
        if self.table_has_body {
            events.push(BlockEvent::TableBodyEnd);
        }
        events.push(BlockEvent::TableEnd);
        self.in_table = false;
        self.table_alignments.clear();
        self.table_has_body = false;
    }

    /// Emit a table data row from a line.
    fn emit_table_row(&mut self, events: &mut Vec<BlockEvent>) {
        let line_start = self.cursor.offset();
        let line_end = match self.cursor.find_newline() {
            Some(pos) => {
                self.cursor.advance(pos);
                let end = line_start + pos;
                self.cursor.bump();
                end
            }
            None => {
                let remaining = self.cursor.remaining();
                self.cursor.advance(remaining);
                line_start + remaining
            }
        };

        let line = &self.input[line_start..line_end];
        let cells = Self::split_table_cells(line);
        let col_count = self.table_alignments.len();

        if !self.table_has_body {
            self.table_has_body = true;
            events.push(BlockEvent::TableBodyStart);
        }

        events.push(BlockEvent::TableRowStart);

        for i in 0..col_count {
            let alignment = self.table_alignments[i];
            events.push(BlockEvent::TableCellStart { alignment });
            if i < cells.len() {
                let (s, e) = cells[i];
                if e > s {
                    events.push(BlockEvent::Text(Range::from_usize(
                        line_start + s,
                        line_start + e,
                    )));
                }
            }
            // If i >= cells.len(), emit an empty cell (no Text event)
            events.push(BlockEvent::TableCellEnd);
        }

        events.push(BlockEvent::TableRowEnd);
    }

    /// Close an open paragraph.
    fn close_paragraph(&mut self, events: &mut Vec<BlockEvent>) {
        if !self.in_paragraph {
            return;
        }

        self.in_paragraph = false;

        if self.paragraph_lines.is_empty() {
            return;
        }

        // Extract link reference definitions from the start of this paragraph.
        let consumed_lines = self.extract_link_ref_defs();
        if consumed_lines > 0 {
            let drain_count = consumed_lines.min(self.paragraph_lines.len());
            self.paragraph_lines.drain(0..drain_count);
        }

        if self.paragraph_lines.is_empty() {
            return;
        }

        // Mark the current container as having content
        self.mark_container_has_content();

        events.push(BlockEvent::ParagraphStart);

        // Emit text ranges for each line with soft breaks between
        for (i, range) in self.paragraph_lines.drain(..).enumerate() {
            if i > 0 {
                // Add soft break between lines
                events.push(BlockEvent::SoftBreak);
            }
            events.push(BlockEvent::Text(range));
        }

        events.push(BlockEvent::ParagraphEnd);
    }

    /// Close the current footnote definition, draining captured events into the store.
    fn close_footnote_definition(&mut self, events: &mut Vec<BlockEvent>) {
        if let Some(start) = self.footnote_event_start.take() {
            // Find the footnote container to get the label
            // We need to find the label from the footnote container that was just popped.
            // We stored it when we opened the definition — extract from the drained events.
            let footnote_events: Vec<BlockEvent> = events.drain(start..).collect();

            // The label was stored as a Text event right at the start marker position.
            // Actually, we need to store the label separately. Let's use a field.
            if let Some((normalized, label)) = self.pending_footnote_label.take() {
                self.footnote_store
                    .insert(normalized, label, footnote_events);
            }
        }
    }

    /// Try to parse a footnote definition start: `[^label]: content`
    /// Returns true if a footnote definition was started.
    fn try_footnote_definition(&mut self, indent: usize, events: &mut Vec<BlockEvent>) -> bool {
        // Must start with `[^`
        let save_pos = self.cursor.offset();
        let save_partial = self.partial_tab_cols;
        let save_col = self.current_col;

        if !self.cursor.at(b'[') {
            return false;
        }
        self.cursor.bump();
        if self.cursor.is_eof() || !self.cursor.at(b'^') {
            self.cursor = Cursor::new_at(self.input, save_pos);
            self.partial_tab_cols = save_partial;
            self.current_col = save_col;
            return false;
        }
        self.cursor.bump();

        // Read label: alphanumeric, dash, underscore
        let label_start = self.cursor.offset();
        while !self.cursor.is_eof() {
            let b = self.cursor.peek_or_zero();
            if b.is_ascii_alphanumeric() || b == b'-' || b == b'_' {
                self.cursor.bump();
            } else {
                break;
            }
        }
        let label_end = self.cursor.offset();

        if label_end == label_start {
            // Empty label
            self.cursor = Cursor::new_at(self.input, save_pos);
            self.partial_tab_cols = save_partial;
            self.current_col = save_col;
            return false;
        }

        // Must be followed by `]:`
        if self.cursor.is_eof() || !self.cursor.at(b']') {
            self.cursor = Cursor::new_at(self.input, save_pos);
            self.partial_tab_cols = save_partial;
            self.current_col = save_col;
            return false;
        }
        self.cursor.bump();
        if self.cursor.is_eof() || !self.cursor.at(b':') {
            self.cursor = Cursor::new_at(self.input, save_pos);
            self.partial_tab_cols = save_partial;
            self.current_col = save_col;
            return false;
        }
        self.cursor.bump();

        let label_bytes = &self.input[label_start..label_end];
        let normalized = match normalize_footnote_label(label_bytes) {
            Some(n) => n,
            None => {
                self.cursor = Cursor::new_at(self.input, save_pos);
                self.partial_tab_cols = save_partial;
                self.current_col = save_col;
                return false;
            }
        };
        let label = String::from_utf8_lossy(label_bytes).into_owned();

        // Skip optional space/tab after colon
        if !self.cursor.is_eof() && (self.cursor.at(b' ') || self.cursor.at(b'\t')) {
            self.cursor.bump();
        }

        // Calculate content indent: columns from line start to current position
        // content_indent = indent (leading spaces) + bytes consumed for [^label]: + optional space
        let content_indent = indent + (self.cursor.offset() - save_pos);

        // Close current paragraph and containers that don't match
        self.close_table(events);
        self.close_paragraph(events);

        // Store the label for when we close the definition
        self.pending_footnote_label = Some((normalized, label));

        // Mark event start position
        self.footnote_event_start = Some(events.len());

        // Push footnote container
        self.container_stack.push(Container {
            typ: ContainerType::FootnoteDefinition { content_indent },
            has_content: false,
        });

        true
    }

    /// Extract link reference definitions from the start of the current paragraph.
    /// Returns the number of paragraph lines consumed by definitions.
    fn extract_link_ref_defs(&mut self) -> usize {
        if !self.options.allow_link_refs {
            return 0;
        }
        if self.paragraph_lines.is_empty() {
            return 0;
        }

        // Fast path: reference definitions can only start at paragraph start.
        // If the first line cannot start a definition, no extraction is possible.
        let first_line = self.paragraph_lines[0].slice(self.input);
        let mut i = 0usize;
        let mut spaces = 0u8;
        let mut has_candidate = false;
        while i < first_line.len() {
            match first_line[i] {
                b' ' => {
                    spaces += 1;
                    if spaces > 3 {
                        break;
                    }
                    i += 1;
                }
                b'\t' => {
                    // A leading tab exceeds the allowed 3-space indent for link ref defs.
                    break;
                }
                b'[' => {
                    has_candidate = true;
                    break;
                }
                _ => break,
            }
        }
        if !has_candidate {
            return 0;
        }

        let input = self.input;
        if let Some((start, end)) = self.try_contiguous_paragraph_ref_span() {
            return self.extract_link_ref_defs_from_bytes(&input[start..end]);
        }

        let mut total_len = self.paragraph_lines.len().saturating_sub(1); // newlines
        for range in &self.paragraph_lines {
            total_len += range.len() as usize;
        }
        self.link_ref_parse_buf.clear();
        self.link_ref_parse_buf.reserve(total_len);
        for (i, range) in self.paragraph_lines.iter().enumerate() {
            if i > 0 {
                self.link_ref_parse_buf.push(b'\n');
            }
            self.link_ref_parse_buf
                .extend_from_slice(range.slice(self.input));
        }
        let para_buf = std::mem::take(&mut self.link_ref_parse_buf);
        let consumed_lines = self.extract_link_ref_defs_from_bytes(para_buf.as_slice());
        self.link_ref_parse_buf = para_buf;
        consumed_lines
    }

    fn extract_link_ref_defs_from_bytes(&mut self, para: &[u8]) -> usize {
        let mut pos = 0usize;
        let mut consumed_lines = 0usize;
        self.link_ref_label_buf.clear();

        loop {
            // Only parse at start of a line
            if pos > 0 && para[pos - 1] != b'\n' {
                break;
            }
            let Some((def, end_pos)) = parse_link_ref_def(para, pos) else {
                break;
            };

            normalize_label_into(def.label.slice(para), &mut self.link_ref_label_buf);
            if self.link_ref_label_buf.is_empty() {
                break;
            }
            if self.link_refs.get_index(&self.link_ref_label_buf).is_none() {
                let link_def = LinkRefDef {
                    url: def.url.slice(para).to_vec(),
                    title: def.title.map(|r| r.slice(para).to_vec()),
                };
                self.link_refs
                    .insert(std::mem::take(&mut self.link_ref_label_buf), link_def);
            } else {
                self.link_ref_label_buf.clear();
            }

            let newline_count = para[pos..end_pos].iter().filter(|&&b| b == b'\n').count();
            let ends_with_newline = end_pos > 0 && para.get(end_pos - 1) == Some(&b'\n');
            consumed_lines += if ends_with_newline {
                newline_count
            } else {
                newline_count + 1
            };
            pos = end_pos;

            if pos >= para.len() {
                break;
            }
        }

        consumed_lines
    }

    /// Returns a contiguous paragraph byte span if lines are directly adjacent in input
    /// with plain `\n` separators and no stripped container prefix.
    fn try_contiguous_paragraph_ref_span(&self) -> Option<(usize, usize)> {
        let first = self.paragraph_lines.first()?;
        let last = self.paragraph_lines.last()?;
        let mut prev_end = first.end_usize();

        for range in self.paragraph_lines.iter().skip(1) {
            let start = range.start_usize();
            if start <= prev_end || start > self.input.len() {
                return None;
            }
            let gap = &self.input[prev_end..start];
            if gap != b"\n" {
                return None;
            }
            prev_end = range.end_usize();
        }

        Some((first.start_usize(), last.end_usize()))
    }

    /// Mark the innermost container as having content.
    /// Used for the two-blank-line rule: list items that have had content
    /// are not closed by a blank line.
    fn mark_container_has_content(&mut self) {
        if let Some(container) = self.container_stack.last_mut() {
            container.has_content = true;
        }
    }

    /// Close any open lists that have no active list item.
    /// This can happen after the two-blank-line rule closes an item.
    fn close_orphaned_lists(&mut self, events: &mut Vec<BlockEvent>) {
        // Count active list items in container stack
        let active_items = self
            .container_stack
            .iter()
            .filter(|c| matches!(c.typ, ContainerType::ListItem { .. }))
            .count();

        // Close lists that have no corresponding item
        while self.open_lists.len() > active_items {
            if let Some(open_list) = self.open_lists.pop() {
                events.push(BlockEvent::ListEnd {
                    kind: open_list.kind,
                    tight: open_list.tight,
                });
            }
        }
    }
}

struct ParsedLinkRefDef {
    label: Range,
    url: Range,
    title: Option<Range>,
}

fn parse_link_ref_def(input: &[u8], start: usize) -> Option<(ParsedLinkRefDef, usize)> {
    let len = input.len();
    let mut i = start;

    // Up to 3 leading spaces
    let mut spaces = 0usize;
    while i < len && input[i] == b' ' && spaces < 3 {
        i += 1;
        spaces += 1;
    }

    if i >= len || input[i] != b'[' {
        return None;
    }
    i += 1;

    // Parse label
    let label_start = i;
    while i < len {
        match input[i] {
            b'\\' => {
                if i + 1 < len {
                    i += 2;
                } else {
                    return None;
                }
            }
            b'[' => return None,
            b']' => break,
            _ => i += 1,
        }
    }
    if i >= len || input[i] != b']' {
        return None;
    }
    let label_end = i;
    i += 1;

    if i >= len || input[i] != b':' {
        return None;
    }
    i += 1;

    // Skip whitespace (allow a single line break)
    let mut saw_newline = false;
    while i < len {
        match input[i] {
            b' ' | b'\t' => i += 1,
            b'\n' => {
                if saw_newline {
                    return None;
                }
                saw_newline = true;
                i += 1;
            }
            _ => break,
        }
    }
    if i >= len {
        return None;
    }

    // Parse destination
    let (url, mut i) = if input[i] == b'<' {
        i += 1;
        let url_start = i;
        while i < len && input[i] != b'>' && input[i] != b'\n' {
            i += 1;
        }
        if i >= len || input[i] != b'>' {
            return None;
        }
        let url_end = i;
        i += 1;
        // After angle destination, must be whitespace or end of line
        if i < len && !matches!(input[i], b' ' | b'\t' | b'\n') {
            return None;
        }
        (Range::from_usize(url_start, url_end), i)
    } else {
        let url_start = i;
        let mut parens = 0i32;
        while i < len {
            let b = input[i];
            if b == b'\\' && i + 1 < len {
                i += 2;
                continue;
            }
            if b == b'(' {
                parens += 1;
                i += 1;
                continue;
            }
            if b == b')' {
                if parens == 0 {
                    break;
                }
                parens -= 1;
                i += 1;
                continue;
            }
            if is_whitespace(b) {
                break;
            }
            i += 1;
        }
        if url_start == i {
            return None;
        }
        (Range::from_usize(url_start, i), i)
    };

    let mut line_end = i;
    while line_end < len && input[line_end] != b'\n' {
        line_end += 1;
    }

    // Skip whitespace before title
    let mut j = i;
    let mut had_title_sep = false;
    let mut title_on_newline = false;
    while j < len && (input[j] == b' ' || input[j] == b'\t') {
        j += 1;
        had_title_sep = true;
    }
    if j < len && input[j] == b'\n' {
        j += 1;
        had_title_sep = true;
        title_on_newline = true;
        while j < len && (input[j] == b' ' || input[j] == b'\t') {
            j += 1;
        }
    }

    let mut title = None;
    if had_title_sep && j < len {
        let opener = input[j];
        let closer = match opener {
            b'"' => b'"',
            b'\'' => b'\'',
            b'(' => b')',
            _ => 0,
        };

        if closer != 0 {
            j += 1;
            let title_start = j;
            while j < len {
                let b = input[j];
                if b == b'\\' && j + 1 < len {
                    j += 2;
                    continue;
                }
                if b == b'\n' && j + 1 < len && input[j + 1] == b'\n' {
                    // Blank line not allowed in title
                    if title_on_newline {
                        return Some((
                            ParsedLinkRefDef {
                                label: Range::from_usize(label_start, label_end),
                                url,
                                title: None,
                            },
                            if line_end < len {
                                line_end + 1
                            } else {
                                line_end
                            },
                        ));
                    }
                    return None;
                }
                if b == closer {
                    break;
                }
                j += 1;
            }
            if j >= len || input[j] != closer {
                // Not a valid title.
                if title_on_newline {
                    return Some((
                        ParsedLinkRefDef {
                            label: Range::from_usize(label_start, label_end),
                            url,
                            title: None,
                        },
                        if line_end < len {
                            line_end + 1
                        } else {
                            line_end
                        },
                    ));
                }
                return None;
            }
            let title_end = j;
            j += 1;
            title = Some(Range::from_usize(title_start, title_end));

            while j < len && (input[j] == b' ' || input[j] == b'\t') {
                j += 1;
            }
            if j < len && input[j] != b'\n' {
                // Invalid title (extra text).
                if title_on_newline {
                    return Some((
                        ParsedLinkRefDef {
                            label: Range::from_usize(label_start, label_end),
                            url,
                            title: None,
                        },
                        if line_end < len {
                            line_end + 1
                        } else {
                            line_end
                        },
                    ));
                }
                return None;
            }
            i = j;
        }
    }

    // If no title, ensure remaining is only whitespace
    if title.is_none() {
        // Definition ends at end of destination line.
        i = line_end;
    }

    // Consume end of line
    if i < len && input[i] == b'\n' {
        i += 1;
    }

    Some((
        ParsedLinkRefDef {
            label: Range::from_usize(label_start, label_end),
            url,
            title,
        },
        i,
    ))
}

#[inline]
fn is_simple_line_start(b: u8) -> bool {
    !matches!(
        b,
        b'#' | b'>'
            | b'-'
            | b'*'
            | b'_'
            | b'+'
            | b'`'
            | b'~'
            | b'<'
            | b'='
            | b'|'
            | b'\n'
            | b'\r'
            | b'0'..=b'9'
    )
}

#[inline]
fn is_list_marker_start(b: u8) -> bool {
    matches!(b, b'-' | b'*' | b'+' | b'0'..=b'9')
}

#[inline]
fn is_whitespace(b: u8) -> bool {
    matches!(b, b' ' | b'\t' | b'\n')
}

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

    fn parse(input: &str) -> Vec<BlockEvent> {
        let mut parser = BlockParser::new(input.as_bytes());
        let mut events = Vec::new();
        parser.parse(&mut events);
        events
    }

    fn get_text<'a>(input: &'a str, event: &BlockEvent) -> &'a str {
        match event {
            BlockEvent::Text(range) => std::str::from_utf8(range.slice(input.as_bytes())).unwrap(),
            _ => panic!("Expected Text event"),
        }
    }

    #[test]
    fn test_empty_input() {
        let events = parse("");
        assert!(events.is_empty());
    }

    #[test]
    fn test_blank_lines() {
        let events = parse("\n\n\n");
        assert!(events.is_empty());
    }

    #[test]
    fn test_simple_paragraph() {
        let input = "Hello, world!";
        let events = parse(input);

        assert_eq!(events.len(), 3);
        assert_eq!(events[0], BlockEvent::ParagraphStart);
        assert_eq!(get_text(input, &events[1]), "Hello, world!");
        assert_eq!(events[2], BlockEvent::ParagraphEnd);
    }

    #[test]
    fn test_multiline_paragraph() {
        let input = "Line 1\nLine 2\nLine 3";
        let events = parse(input);

        // ParagraphStart, Text, SoftBreak, Text, SoftBreak, Text, ParagraphEnd
        assert_eq!(events.len(), 7);
        assert_eq!(events[0], BlockEvent::ParagraphStart);
        assert_eq!(get_text(input, &events[1]), "Line 1");
        assert_eq!(events[2], BlockEvent::SoftBreak);
        assert_eq!(get_text(input, &events[3]), "Line 2");
        assert_eq!(events[4], BlockEvent::SoftBreak);
        assert_eq!(get_text(input, &events[5]), "Line 3");
        assert_eq!(events[6], BlockEvent::ParagraphEnd);
    }

    #[test]
    fn test_paragraphs_separated_by_blank() {
        let input = "Para 1\n\nPara 2";
        let events = parse(input);

        assert_eq!(events.len(), 6);
        assert_eq!(events[0], BlockEvent::ParagraphStart);
        assert_eq!(get_text(input, &events[1]), "Para 1");
        assert_eq!(events[2], BlockEvent::ParagraphEnd);
        assert_eq!(events[3], BlockEvent::ParagraphStart);
        assert_eq!(get_text(input, &events[4]), "Para 2");
        assert_eq!(events[5], BlockEvent::ParagraphEnd);
    }

    #[test]
    fn test_thematic_break_dashes() {
        let events = parse("---");
        assert_eq!(events, vec![BlockEvent::ThematicBreak]);
    }

    #[test]
    fn test_thematic_break_asterisks() {
        let events = parse("***");
        assert_eq!(events, vec![BlockEvent::ThematicBreak]);
    }

    #[test]
    fn test_thematic_break_underscores() {
        let events = parse("___");
        assert_eq!(events, vec![BlockEvent::ThematicBreak]);
    }

    #[test]
    fn test_thematic_break_with_spaces() {
        let events = parse("- - -");
        assert_eq!(events, vec![BlockEvent::ThematicBreak]);
    }

    #[test]
    fn test_thematic_break_many() {
        let events = parse("----------");
        assert_eq!(events, vec![BlockEvent::ThematicBreak]);
    }

    #[test]
    fn test_thematic_break_too_few() {
        let input = "--";
        let events = parse(input);
        // Should be a paragraph, not a thematic break
        assert_eq!(events[0], BlockEvent::ParagraphStart);
    }

    #[test]
    fn test_thematic_break_mixed_invalid() {
        let input = "-*-";
        let events = parse(input);
        // Mixed markers = paragraph
        assert_eq!(events[0], BlockEvent::ParagraphStart);
    }

    #[test]
    fn test_atx_heading_h1() {
        let input = "# Heading";
        let events = parse(input);

        assert_eq!(events.len(), 3);
        assert_eq!(events[0], BlockEvent::HeadingStart { level: 1 });
        assert_eq!(get_text(input, &events[1]), "Heading");
        assert_eq!(events[2], BlockEvent::HeadingEnd { level: 1 });
    }

    #[test]
    fn test_atx_heading_h2() {
        let input = "## Heading";
        let events = parse(input);

        assert_eq!(events[0], BlockEvent::HeadingStart { level: 2 });
    }

    #[test]
    fn test_atx_heading_h6() {
        let input = "###### Heading";
        let events = parse(input);

        assert_eq!(events[0], BlockEvent::HeadingStart { level: 6 });
    }

    #[test]
    fn test_atx_heading_h7_invalid() {
        let input = "####### Heading";
        let events = parse(input);

        // 7 # is not a valid heading
        assert_eq!(events[0], BlockEvent::ParagraphStart);
    }

    #[test]
    fn test_atx_heading_empty() {
        let input = "#";
        let events = parse(input);

        assert_eq!(events.len(), 2);
        assert_eq!(events[0], BlockEvent::HeadingStart { level: 1 });
        assert_eq!(events[1], BlockEvent::HeadingEnd { level: 1 });
    }

    #[test]
    fn test_atx_heading_closing_hashes() {
        let input = "# Heading #";
        let events = parse(input);

        assert_eq!(events.len(), 3);
        assert_eq!(get_text(input, &events[1]), "Heading");
    }

    #[test]
    fn test_atx_heading_closing_hashes_multiple() {
        let input = "## Heading ##";
        let events = parse(input);

        assert_eq!(get_text(input, &events[1]), "Heading");
    }

    #[test]
    fn test_atx_heading_closing_hashes_with_space() {
        let input = "# Heading #  ";
        let events = parse(input);

        assert_eq!(get_text(input, &events[1]), "Heading");
    }

    #[test]
    fn test_atx_heading_no_space_after_hashes() {
        let input = "#Heading";
        let events = parse(input);

        // No space after # = not a heading
        assert_eq!(events[0], BlockEvent::ParagraphStart);
    }

    #[test]
    fn test_thematic_break_closes_paragraph() {
        // `---` after paragraph text is a setext heading (h2), not a thematic break
        // For thematic break after paragraph, need a blank line
        let input = "Text\n\n---";
        let events = parse(input);

        assert_eq!(events.len(), 4);
        assert_eq!(events[0], BlockEvent::ParagraphStart);
        assert_eq!(events[2], BlockEvent::ParagraphEnd);
        assert_eq!(events[3], BlockEvent::ThematicBreak);
    }

    #[test]
    fn test_heading_closes_paragraph() {
        let input = "Text\n# Heading";
        let events = parse(input);

        assert_eq!(events[0], BlockEvent::ParagraphStart);
        assert_eq!(events[2], BlockEvent::ParagraphEnd);
        assert_eq!(events[3], BlockEvent::HeadingStart { level: 1 });
    }

    #[test]
    fn test_indented_content() {
        let input = "   Text with indent";
        let events = parse(input);

        // Up to 3 spaces is allowed for normal blocks
        assert_eq!(events[0], BlockEvent::ParagraphStart);
        assert_eq!(get_text(input, &events[1]), "Text with indent");
    }

    #[test]
    fn test_thematic_break_with_leading_spaces() {
        let events = parse("   ---");
        assert_eq!(events, vec![BlockEvent::ThematicBreak]);
    }

    // Fenced code block tests

    fn get_code<'a>(input: &'a str, event: &BlockEvent) -> &'a str {
        match event {
            BlockEvent::Code(range) => std::str::from_utf8(range.slice(input.as_bytes())).unwrap(),
            _ => panic!("Expected Code event"),
        }
    }

    fn get_info<'a>(input: &'a str, event: &BlockEvent) -> Option<&'a str> {
        match event {
            BlockEvent::CodeBlockStart { info } => info
                .as_ref()
                .map(|r| std::str::from_utf8(r.slice(input.as_bytes())).unwrap()),
            _ => panic!("Expected CodeBlockStart event"),
        }
    }

    #[test]
    fn test_code_fence_backticks() {
        let input = "```\ncode\n```";
        let events = parse(input);

        assert_eq!(events.len(), 3);
        assert!(matches!(events[0], BlockEvent::CodeBlockStart { .. }));
        assert_eq!(get_code(input, &events[1]), "code\n");
        assert_eq!(events[2], BlockEvent::CodeBlockEnd);
    }

    #[test]
    fn test_code_fence_tildes() {
        let input = "~~~\ncode\n~~~";
        let events = parse(input);

        assert_eq!(events.len(), 3);
        assert!(matches!(events[0], BlockEvent::CodeBlockStart { .. }));
        assert_eq!(get_code(input, &events[1]), "code\n");
        assert_eq!(events[2], BlockEvent::CodeBlockEnd);
    }

    #[test]
    fn test_code_fence_with_info() {
        let input = "```rust\nfn main() {}\n```";
        let events = parse(input);

        assert_eq!(events.len(), 3);
        assert_eq!(get_info(input, &events[0]), Some("rust"));
        assert_eq!(get_code(input, &events[1]), "fn main() {}\n");
    }

    #[test]
    fn test_code_fence_info_with_spaces() {
        let input = "```rust cargo\ncode\n```";
        let events = parse(input);

        assert_eq!(get_info(input, &events[0]), Some("rust cargo"));
    }

    #[test]
    fn test_code_fence_longer_closing() {
        let input = "```\ncode\n`````";
        let events = parse(input);

        assert_eq!(events.len(), 3);
        assert_eq!(events[2], BlockEvent::CodeBlockEnd);
    }

    #[test]
    fn test_code_fence_shorter_closing_invalid() {
        let input = "````\ncode\n```";
        let events = parse(input);

        // Should not close, code continues and fence closes at EOF
        assert_eq!(events.len(), 4); // start, code, "```", end
    }

    #[test]
    fn test_code_fence_empty() {
        let input = "```\n```";
        let events = parse(input);

        assert_eq!(events.len(), 2);
        assert!(matches!(events[0], BlockEvent::CodeBlockStart { .. }));
        assert_eq!(events[1], BlockEvent::CodeBlockEnd);
    }

    #[test]
    fn test_code_fence_multiline() {
        let input = "```\nline1\nline2\nline3\n```";
        let events = parse(input);

        assert_eq!(events.len(), 5);
        assert_eq!(get_code(input, &events[1]), "line1\n");
        assert_eq!(get_code(input, &events[2]), "line2\n");
        assert_eq!(get_code(input, &events[3]), "line3\n");
    }

    #[test]
    fn test_code_fence_no_closing() {
        let input = "```\ncode";
        let events = parse(input);

        // Code block should be closed at EOF (no trailing newline)
        assert_eq!(events.len(), 3);
        assert!(matches!(events[0], BlockEvent::CodeBlockStart { .. }));
        assert_eq!(get_code(input, &events[1]), "code"); // No newline at EOF
        assert_eq!(events[2], BlockEvent::CodeBlockEnd);
    }

    #[test]
    fn test_code_fence_with_blank_lines() {
        let input = "```\n\ncode\n\n```";
        let events = parse(input);

        assert_eq!(events.len(), 5);
        assert_eq!(get_code(input, &events[1]), "\n");
        assert_eq!(get_code(input, &events[2]), "code\n");
        assert_eq!(get_code(input, &events[3]), "\n");
    }

    #[test]
    fn test_code_fence_backticks_in_tilde_fence() {
        let input = "~~~\n```\n~~~";
        let events = parse(input);

        assert_eq!(events.len(), 3);
        assert_eq!(get_code(input, &events[1]), "```\n");
    }

    #[test]
    fn test_code_fence_closes_paragraph() {
        let input = "text\n```\ncode\n```";
        let events = parse(input);

        assert_eq!(events[0], BlockEvent::ParagraphStart);
        assert_eq!(events[2], BlockEvent::ParagraphEnd);
        assert!(matches!(events[3], BlockEvent::CodeBlockStart { .. }));
    }

    #[test]
    fn test_code_fence_two_backticks_invalid() {
        let input = "``\ncode\n``";
        let events = parse(input);

        // Two backticks is not a valid fence
        assert_eq!(events[0], BlockEvent::ParagraphStart);
    }

    #[test]
    fn test_code_fence_backtick_in_info_invalid() {
        let input = "```rust`extra\ncode\n```";
        let events = parse(input);

        // Backtick in info string makes it not a code fence
        assert_eq!(events[0], BlockEvent::ParagraphStart);
    }

    #[test]
    fn test_code_fence_preserves_content() {
        let input = "```\n  indented\n    more\n```";
        let events = parse(input);

        assert_eq!(get_code(input, &events[1]), "  indented\n");
        assert_eq!(get_code(input, &events[2]), "    more\n");
    }

    // Blockquote tests

    #[test]
    fn test_blockquote_simple() {
        let input = "> quote";
        let events = parse(input);

        assert_eq!(events[0], BlockEvent::BlockQuoteStart { callout: None });
        assert_eq!(events[1], BlockEvent::ParagraphStart);
        assert_eq!(get_text(input, &events[2]), "quote");
        assert_eq!(events[3], BlockEvent::ParagraphEnd);
        assert_eq!(events[4], BlockEvent::BlockQuoteEnd);
    }

    #[test]
    fn test_blockquote_multiline() {
        let input = "> line1\n> line2";
        let events = parse(input);

        assert_eq!(events[0], BlockEvent::BlockQuoteStart { callout: None });
        assert_eq!(events[1], BlockEvent::ParagraphStart);
        assert_eq!(get_text(input, &events[2]), "line1");
        assert_eq!(events[3], BlockEvent::SoftBreak);
        assert_eq!(get_text(input, &events[4]), "line2");
    }

    #[test]
    fn test_blockquote_no_space() {
        let input = ">quote";
        let events = parse(input);

        // > without space is still valid
        assert_eq!(events[0], BlockEvent::BlockQuoteStart { callout: None });
    }

    #[test]
    fn test_blockquote_nested() {
        let input = "> > nested";
        let events = parse(input);

        assert_eq!(events[0], BlockEvent::BlockQuoteStart { callout: None });
        assert_eq!(events[1], BlockEvent::BlockQuoteStart { callout: None });
        assert!(matches!(events[2], BlockEvent::ParagraphStart));
    }

    #[test]
    fn test_blockquote_ends() {
        let input = "> quote\n\nparagraph";
        let events = parse(input);

        // Blockquote ends on blank line
        let mut found_quote_end = false;
        let mut found_para_after = false;
        for event in events.iter() {
            if *event == BlockEvent::BlockQuoteEnd {
                found_quote_end = true;
            }
            if found_quote_end && *event == BlockEvent::ParagraphStart {
                found_para_after = true;
            }
        }
        assert!(found_quote_end);
        assert!(found_para_after);
    }

    // List tests

    #[test]
    fn test_list_unordered_dash() {
        let input = "- item";
        let events = parse(input);

        assert!(matches!(
            events[0],
            BlockEvent::ListStart {
                kind: ListKind::Unordered,
                ..
            }
        ));
        assert!(matches!(events[1], BlockEvent::ListItemStart { .. }));
        assert_eq!(events[2], BlockEvent::ParagraphStart);
        assert_eq!(get_text(input, &events[3]), "item");
    }

    #[test]
    fn test_list_unordered_asterisk() {
        let input = "* item";
        let events = parse(input);

        assert!(matches!(
            events[0],
            BlockEvent::ListStart {
                kind: ListKind::Unordered,
                ..
            }
        ));
    }

    #[test]
    fn test_list_unordered_plus() {
        let input = "+ item";
        let events = parse(input);

        assert!(matches!(
            events[0],
            BlockEvent::ListStart {
                kind: ListKind::Unordered,
                ..
            }
        ));
    }

    #[test]
    fn test_list_multiple_items() {
        let input = "- item1\n- item2\n- item3";
        let events = parse(input);

        // Count list item starts
        let item_count = events
            .iter()
            .filter(|e| matches!(e, BlockEvent::ListItemStart { .. }))
            .count();
        assert_eq!(item_count, 3);

        // Should have exactly one list
        let list_count = events
            .iter()
            .filter(|e| matches!(e, BlockEvent::ListStart { .. }))
            .count();
        assert_eq!(list_count, 1);
    }

    #[test]
    fn test_list_ordered() {
        let input = "1. first\n2. second";
        let events = parse(input);

        assert!(matches!(
            events[0],
            BlockEvent::ListStart {
                kind: ListKind::Ordered { start: 1, .. },
                ..
            }
        ));
    }

    #[test]
    fn test_list_ordered_start_number() {
        let input = "5. fifth";
        let events = parse(input);

        assert!(matches!(
            events[0],
            BlockEvent::ListStart {
                kind: ListKind::Ordered { start: 5, .. },
                ..
            }
        ));
    }

    #[test]
    fn test_list_ordered_paren() {
        let input = "1) item";
        let events = parse(input);

        assert!(matches!(
            events[0],
            BlockEvent::ListStart {
                kind: ListKind::Ordered { .. },
                ..
            }
        ));
    }

    #[test]
    fn test_list_task_unchecked() {
        let input = "- [ ] task";
        let events = parse(input);

        assert!(matches!(
            events[1],
            BlockEvent::ListItemStart {
                task: TaskState::Unchecked
            }
        ));
    }

    #[test]
    fn test_list_task_checked() {
        let input = "- [x] done";
        let events = parse(input);

        assert!(matches!(
            events[1],
            BlockEvent::ListItemStart {
                task: TaskState::Checked
            }
        ));
    }

    #[test]
    fn test_list_task_checked_uppercase() {
        let input = "- [X] done";
        let events = parse(input);

        assert!(matches!(
            events[1],
            BlockEvent::ListItemStart {
                task: TaskState::Checked
            }
        ));
    }

    #[test]
    fn test_list_ends_on_blank() {
        let input = "- item\n\nparagraph";
        let events = parse(input);

        let has_list_end = events
            .iter()
            .any(|e| matches!(e, BlockEvent::ListEnd { .. }));
        assert!(has_list_end);
    }

    #[test]
    fn test_blockquote_with_list() {
        let input = "> - item";
        let events = parse(input);

        assert_eq!(events[0], BlockEvent::BlockQuoteStart { callout: None });
        assert!(matches!(events[1], BlockEvent::ListStart { .. }));
    }
}