html-to-markdown-rs 3.16.0

High-performance HTML to Markdown converter using the astral-tl parser. Part of the Xberg ecosystem.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
//! Tier-1 single-pass byte scanner.
//!
//! Walks `html.as_bytes()` once and emits Markdown directly to a pre-sized
//! output buffer.  On any construct it cannot handle exactly, returns a
//! [`BailReason`] so the dispatcher can fall back to Tier-2.
//!
//! # Supported subset (M9 + Phase E + Phase I)
//!
//! Paragraph, Heading(1-6), Strong, Emphasis, Code (inline), Pre, Hr,
//! `LineBreak`, Link, Image, List(Unordered), List(Ordered), `ListItem`,
//! Blockquote, Block (div/section/article/center/etc.), Inline (span/etc.),
//! Table (GFM — conservative bail set, inline-only cell content),
//! SVG (emitted as base64 data URI — Phase I), and custom elements (tag names
//! containing `-`, treated as Block containers).
//!
//! Bails on: RawText(script/style/textarea/etc.), `DefinitionTerm`,
//! `DefinitionDescription`, List(Definition), Ignored (head/meta/link),
//! nested tables, non-inlineable block children in cells (heading/list/blockquote/pre),
//! section-order violations, and any HTML construct with in-text whitespace
//! complexity or unclosed tags.

// TODO(xberg-io/html-to-markdown#465): 5 cyclomatic-complexity and 38 size/complexity findings
// in this file, currently excluded via the quality-debt baseline in alef.toml. Splitting
// these needs compiler-in-the-loop verification, not a mechanical pass. Delete this
// note and the file's baseline entry together once it goes green. Help wanted.

use crate::converter::inline::link::has_uri_scheme;
use crate::converter::tier1::bail::BailReason;
use crate::converter::tier1::parse;
use crate::converter::tier1::spec_rules;
use crate::converter::tier1::state::{EscapeCtx, OpenTag, Tier1State};
use crate::converter::tier1::tags::{ListKind, TagKind, TagSpec};
use crate::converter::tier1::{self};
use crate::converter::utility::attributes::NAV_KEYWORDS;
use crate::options::ConversionOptions;
use crate::text::ReferenceContext;

use memchr::{memchr2, memchr3};

/// Maximum byte length of a tag name lowercased into a stack buffer.
///
/// Names longer than this are silently truncated and will not match any
/// entry in the spec table, causing an `UnknownCustomElement` bail.
const MAX_TAG_NAME_BYTES: usize = 32;

/// Minimum number of dashes in a GFM separator cell.
///
/// Matches Tier-2's `col_widths.get(i).unwrap_or(0).max(MIN_SEPARATOR_DASHES)`.
const MIN_SEPARATOR_DASHES: usize = 3;

/// Minimum length of a Markdown code fence (```` ``` ````) per `CommonMark`.
///
/// ~keep Mirrors `converter::handlers::code_block::MIN_FENCE_LENGTH`. Not imported
/// from there: that module is owned by another concurrent edit lane and this
/// crate's `tier1/` ownership boundary forbids editing it to add a `pub(crate)`
/// re-export. Reported as a proposed shared-helper extraction (see module docs).
const MIN_FENCE_LENGTH: usize = 3;

/// Static `TagSpec` used for all unknown custom elements (tag names containing
/// `-`, e.g. `<x-foo>`, `<my-component>`).
///
/// ~keep Unknown/custom elements are inline by default in HTML (there is no
/// such thing as a block-level custom element absent a UA stylesheet
/// rule or CSS `display` override, neither of which this converter
/// applies) and Tier-2's DOM walk treats them exactly that way: an
/// `<x-widget>` inside flowing text stays inline in the surrounding
/// paragraph/list-item/blockquote instead of splitting it. A `Block`
/// spec here previously matched Tier-2 only for the common case of a
/// custom element as a whole top-level document/child; it diverged the
/// moment one appeared inline.
///
/// The static reference `&CUSTOM_ELEMENT_INLINE_SPEC` is used anywhere the
/// scanner needs a `&'static TagSpec` for a custom element open/close tag.
static CUSTOM_ELEMENT_INLINE_SPEC: TagSpec = TagSpec {
    kind: TagKind::Inline,
    is_void: false,
    is_block: false,
    optional_close: None,
    is_rawtext: false,
};

/// ATX heading prefixes indexed by level − 1 (0 = `h1`, 5 = `h6`).
const HEADING_PREFIXES: [&str; 6] = ["# ", "## ", "### ", "#### ", "##### ", "###### "];

/// List-item indentation strings indexed by depth (0 = top-level, no indent).
///
/// Depths beyond the table size fall back to a runtime allocation.
const LIST_ITEM_INDENTS: [&str; 8] = [
    "",
    "  ",
    "    ",
    "      ",
    "        ",
    "          ",
    "            ",
    "              ",
];

/// Successful output of the Tier-1 scanner.
#[derive(Debug, Clone, Default)]
pub struct ScanOutput {
    /// Accumulated Markdown body.
    pub body: String,
    /// Byte range of `<head>…</head>` content (if a `<head>` was seen) in
    /// the input the scanner walked.  Forwarded by `tier1::run` to
    /// `head_metadata::extract_frontmatter` so the YAML frontmatter step
    /// works without a `PrescanReport`.
    pub head_range: Option<std::ops::Range<usize>>,
}

/// Entry point for the Tier-1 scanner.
pub fn scan(
    html: &str,
    options: &ConversionOptions,
    effective_base: Option<std::rc::Rc<url::Url>>,
) -> Result<ScanOutput, BailReason> {
    let bytes = html.as_bytes();
    let mut state = Tier1State::new(html.len(), effective_base);
    let mut table_probes: Vec<TableLayoutProbe> = Vec::new();
    let mut pos = 0usize;
    let mut text_start = 0usize;

    while pos < bytes.len() {
        match bytes[pos] {
            b'<' => {
                if text_start < pos {
                    let next_tag_is_html = upcoming_tag_is_named(bytes, pos, b"html");
                    if !crate::converter::main_helpers::is_ignorable_before_head(
                        &html[text_start..pos],
                        next_tag_is_html,
                    ) {
                        state.start_body(text_start);
                    }
                    // ~keep Peek the upcoming tag BEFORE flushing the preceding text: a
                    // purely-whitespace run immediately after an inline-close marker
                    // (`**`/`*`/etc.) is collapsed to one space by default, but
                    // Tier-2's `text_node.rs` pushes it verbatim when the next
                    // sibling isn't inline — see `flush_text`'s use of this flag for
                    // why that only matters (byte-for-byte) when the next sibling is
                    // specifically a nested `<ul>`/`<ol>`.
                    let next_tag_is_list = upcoming_tag_is_list_open(bytes, pos);
                    // ~keep Same idea, narrower target: whether the whitespace about to be
                    // flushed sits directly in front of a following `<img>` — see
                    // `flush_text`'s use of `next_tag_is_img` alongside
                    // `Tier1State::last_emitted_was_img`.
                    let next_tag_is_img = upcoming_tag_is_named(bytes, pos, b"img");
                    // ~keep A trailing bare `\n` (no accompanying space/tab) on an
                    // otherwise non-whitespace text node needs to know whether the
                    // upcoming sibling is specifically `<span>` — see
                    // `trailing_single_newline_join`'s doc comment for why that one
                    // tag is special-cased.
                    let next_tag_is_span = upcoming_tag_is_named(bytes, pos, b"span");
                    flush_text(
                        &mut state,
                        &html[text_start..pos],
                        text_start,
                        next_tag_is_list,
                        next_tag_is_img,
                        next_tag_is_span,
                        options.br_in_tables,
                    )?;
                }

                let next = bytes.get(pos + 1).copied().unwrap_or(0);

                if next == b'!' {
                    if html[pos..].starts_with("<![CDATA[") {
                        return Err(BailReason::Cdata { offset: pos });
                    }
                    pos = skip_bang(bytes, pos)?;
                    text_start = pos;
                    continue;
                }

                // ~keep `<?` — processing instruction.  Tier-2 handles these
                // inconsistently depending on whether html5ever-repair
                // ran (it rewrites bogus comments) and how tl chooses
                // to parse the run.  Either way the byte shape
                // downstream differs from the simple skip Tier-1 could
                // perform, so bail and let the Tier-2 fallback produce
                // the authoritative output.
                if next == b'?' {
                    return Err(BailReason::Classifier);
                }

                if next == b'/' {
                    let name_start = pos + 2;
                    let name_end = parse::scan_tag_name(bytes, name_start);
                    if name_end == name_start {
                        // ~keep `</>` or similar — bail
                        return Err(BailReason::LiteralLt { offset: pos });
                    }
                    let close_bracket =
                        parse::find_tag_close(bytes, name_end).ok_or(BailReason::LiteralLt { offset: pos })?;

                    let tag_name_bytes = &bytes[name_start..name_end];
                    let len_before_close = state.cell_or_output_mut().len();
                    let join_open = state.pending_newline_join == Some(len_before_close);
                    emit_close(&mut state, tag_name_bytes, options, &mut table_probes)?;
                    // ~keep Tier-2 ends a block and the form elements its form handlers write with a
                    // ~keep line of their own before the `<br>`. An inline close can write its marker
                    // ~keep before the join (`~~First~~\n`), so the join is followed to the new end.
                    let mut name_buf = [0u8; MAX_TAG_NAME_BYTES];
                    let name_lower = lowercase_into(tag_name_bytes, &mut name_buf);
                    let ends_own_line = tier1::lookup(name_lower).is_some_and(|spec| spec.is_block)
                        || matches!(
                            name_lower,
                            b"label"
                                | b"select"
                                | b"option"
                                | b"optgroup"
                                | b"button"
                                | b"progress"
                                | b"meter"
                                | b"output"
                                | b"datalist"
                        );
                    let dest = state.cell_or_output_mut();
                    let (dest_len, ends_in_newline) = (dest.len(), dest.ends_with('\n'));
                    state.pending_newline_join = (join_open && ends_in_newline && !ends_own_line).then_some(dest_len);

                    pos = close_bracket.0 + 1;
                    text_start = pos;
                    continue;
                }

                // ~keep Not a tag-name-start byte → literal `<` in text. Tier-2
                // emits these verbatim (html5ever/astral-tl both parse a
                // bare `<x` as a text node). Emit the `<` and continue so
                // we don't bail on commonly-unescaped source like `x < 5`.
                if !parse::is_tag_name_start(next) {
                    state.start_body(pos);
                    flush_text(&mut state, "<", pos, false, false, false, options.br_in_tables)?;
                    pos += 1;
                    text_start = pos;
                    continue;
                }

                let name_start = pos + 1;
                let name_end = parse::scan_tag_name(bytes, name_start);
                let tag_name_bytes = &bytes[name_start..name_end];

                let mut name_buf = [0u8; MAX_TAG_NAME_BYTES];
                let name_lower = lowercase_into(tag_name_bytes, &mut name_buf);
                // ~keep Tier-2 strips `<script>` and `<style>` before parsing, so only a `<br>`
                // ~keep keeps a text's newline join open for removal (issue #683).
                if !matches!(name_lower, b"br" | b"script" | b"style") {
                    state.pending_newline_join = None;
                }

                // ~keep Audit #12 follow-up: `strip_hidden_elements`
                // (converter/utility/preprocessing.rs, outside tier1/) removes any
                // element carrying `hidden` or a `style="display:none"` /
                // `style="visibility:hidden"` / `style="font-size:0"` declaration — tag
                // and all descendant content — as a raw-string pass Tier-2 always runs
                // before parsing,
                // before either tier is even aware of tag identity. Checked here,
                // before the `<svg>`/`<template>` special cases below, so it is as
                // tag-agnostic as the pass it mirrors (a hidden `<svg>` must bail
                // too — its dedicated branch below has no hidden-element awareness
                // of its own). Reuses that pass's exact helpers (widened to
                // `pub(crate)`) rather than re-implementing the `hidden`/style
                // declaration scan a third time — see the code-fence/code-span
                // duplication this lane already fixed above.
                let tag_open_end =
                    crate::converter::utility::preprocessing::find_tag_end(bytes, pos + 1).unwrap_or(bytes.len());
                let tag_slice = &html[pos..tag_open_end];
                if crate::converter::utility::preprocessing::tag_has_hidden_attribute(tag_slice)
                    || crate::converter::utility::preprocessing::tag_has_hidden_style(tag_slice)
                {
                    return Err(BailReason::HiddenElement { offset: pos });
                }

                if crate::converter::main_helpers::starts_body(name_lower) {
                    state.start_body(pos);
                }

                // ~keep Phase I: `<svg>` — emit as base64 data URI matching Tier-2's
                // `handle_svg` output.  The entire subtree (open tag through
                // `</svg>`) is consumed here; the scanner skips past it without
                // pushing anything on the open-tag stack.
                // ~keep
                // ~keep `tl::parse` is called on just the SVG fragment to normalize
                // attribute order via `serialize_element` (which sorts attrs
                // alphabetically — raw source bytes differ, so slicing alone is
                // not byte-identical with Tier-2 output).
                if name_lower == b"svg" {
                    let tag_open_start = pos;
                    let Some((close_pos, is_self_closing)) = parse::find_tag_close(bytes, name_end) else {
                        // ~keep Unclosed SVG open tag — skip to end; Tier-2 handles it.
                        pos = bytes.len();
                        text_start = pos;
                        continue;
                    };
                    let open_tag_end = close_pos + 1;

                    let svg_end = if is_self_closing {
                        // ~keep `<svg ... />` — self-closing, no children.
                        open_tag_end
                    } else {
                        // ~keep Find matching `</svg>` with depth tracking.
                        find_svg_close(bytes, open_tag_end).unwrap_or(bytes.len())
                    };

                    let svg_slice = &html[tag_open_start..svg_end];

                    emit_svg_from_slice(svg_slice, tag_open_start, &mut state, options)?;

                    pos = svg_end;
                    text_start = pos;
                    continue;
                }

                // ~keep Phase N: `<template>` — inert script container; Tier-2 drops
                // its content. Skip the entire subtree without emitting anything.
                // Self-closing form is rare but handled.
                // ~keep
                // ~keep Audit #12 follow-up: this comment previously cited
                // plain_text.rs SKIP_TAGS as the reason, which was true only for
                // the plain-text output path — the two tiers were silently
                // mismatched for Markdown output until main.rs's `"template" |
                // "noscript" => {}` arm landed (converter/main.rs, outside
                // tier1/). Both tiers now agree `<template>` is inert.
                if name_lower == b"template" {
                    let Some((close_pos, is_self_closing)) = parse::find_tag_close(bytes, name_end) else {
                        pos = bytes.len();
                        text_start = pos;
                        continue;
                    };
                    let open_tag_end = close_pos + 1;
                    pos = if is_self_closing {
                        open_tag_end
                    } else {
                        find_balanced_close(bytes, open_tag_end, b"template").unwrap_or(bytes.len())
                    };
                    text_start = pos;
                    continue;
                }

                // ~keep Resolve the tag spec.  Custom elements (names containing `-`)
                // are not in the static TAGS table but are treated as generic
                // inline passthroughs, matching `TagKind::Inline` behaviour and
                // HTML's default inline rendering for unknown elements.  All
                // other unknown tags are still bailed immediately.
                let spec: &'static TagSpec = if name_lower.contains(&b'-') {
                    &CUSTOM_ELEMENT_INLINE_SPEC
                } else {
                    match tier1::lookup(name_lower) {
                        Some(s) => s,
                        None => {
                            return Err(BailReason::UnknownCustomElement {
                                name: bytes_to_string(tag_name_bytes).into(),
                                offset: pos,
                            });
                        }
                    }
                };

                // ~keep Raw-text "ignored" tags (`<script>`, `<style>`): their
                // spec is `TagKind::Ignored` with `is_rawtext = true` (see
                // tags.rs `rawtext_ignored`).  Prescan also strips their
                // content (STRIP_CONTENT_TAGS); Tier-2 does the same.  Skip
                // them inline so we don't bail to Tier-2 just because a page
                // contains an empty `<script></script>` left over from
                // prescan.  Other `RawText` kinds (textarea / title / xmp /
                // iframe / noscript / noembed / noframes) keep their text
                // content in Tier-2 and must continue to bail until Tier-1
                // learns to emit it correctly.
                if matches!(spec.kind, TagKind::Ignored) && spec.is_rawtext {
                    let open_end = match parse::find_tag_close(bytes, name_end) {
                        Some(close) => close.0 + 1,
                        None => bytes.len(),
                    };
                    pos = find_raw_text_close(bytes, open_end, name_lower).unwrap_or(bytes.len());

                    // ~keep Tier-2's `strip_script_and_style_tags` preprocessing pass
                    // (converter/utility/preprocessing.rs, outside tier1/) inserts a
                    // boundary space *per removed element* when its source-adjacent
                    // bytes are non-whitespace.  Two `<script>`/`<style>` tags sitting
                    // back-to-back with zero separating whitespace therefore each
                    // contribute a boundary space, and — because they collapse to a
                    // single whitespace-only DOM text node — Tier-2's downstream
                    // whitespace-mode handling of that node produces an idiosyncratic
                    // byte pattern (observed: a stray `\n\n  \n` at the nuxt-example
                    // fixture's trailing `<script><script></body>`) that is specific
                    // to whitespace-only-node handling, not reproducible by mirroring
                    // the boundary-space rule alone.  Bail so Tier-2 (authoritative)
                    // handles this rare, adjacency-only case; the single-tag word-glue
                    // mirror below still covers the common case.
                    if is_adjacent_rawtext_ignored_open(bytes, pos) {
                        return Err(BailReason::AdjacentRawTextTags { offset: pos });
                    }
                    // ~keep Tier-2 reads the whitespace on both sides of the removed element as one
                    // ~keep text, so `First\n<script>x</script>\n<br>` ends in a blank line, as
                    // ~keep `First\n\n<br>` does: the `<br>` must not remove the join (issue #683).
                    let after = &bytes[pos..];
                    let after_ws = &after[..after
                        .iter()
                        .position(|b| !b.is_ascii_whitespace())
                        .unwrap_or(after.len())];
                    let newline_before = name_start >= 2 && bytes[name_start - 2] == b'\n';
                    if (newline_before && after_ws.first() == Some(&b'\n')) || after_ws.windows(2).any(|w| w == b"\n\n")
                    {
                        state.pending_newline_join = None;
                    }

                    text_start = pos;
                    // ~keep Mirror the single-element boundary-space rule: a space is
                    // inserted only when the removed tag would otherwise glue two
                    // word characters together.  The "before" check uses the emitted
                    // output tail (not the raw source byte) so that a space already
                    // produced by a preceding sibling is never doubled up; the "after"
                    // check peeks the next source byte, matching Tier-2's boundary
                    // condition exactly.
                    if name_lower == b"script" || name_lower == b"style" {
                        let after_is_word = pos < bytes.len() && !bytes[pos].is_ascii_whitespace();
                        if after_is_word {
                            let dest = state.cell_or_output_mut();
                            let ends_with_word = !dest.is_empty()
                                && !dest.ends_with(' ')
                                && !dest.ends_with('\t')
                                && !dest.ends_with('\n')
                                && !dest.ends_with('<')
                                && !dest.ends_with("<br>");
                            if ends_with_word {
                                dest.push(' ');
                            }
                        }
                    }
                    continue;
                }

                // ~keep Non-rawtext `Ignored` tags (`<head>`, `<meta>`, `<link>`):
                // Tier-2 does not emit any markdown from their bodies — head
                // is consumed by metadata extraction; meta/link are void.
                // Silent-skip them here so Tier-1 can be invoked on inputs
                // that contain a `<head>` (the common case for full HTML
                // documents) without bailing.  For non-void `<head>`, capture
                // the content range on `state.head_range` so `tier1::run` can
                // hand it to `head_metadata::extract_frontmatter` when
                // metadata extraction is enabled.
                if matches!(spec.kind, TagKind::Ignored) {
                    let open_end = match parse::find_tag_close(bytes, name_end) {
                        Some(close) => close.0 + 1,
                        None => bytes.len(),
                    };
                    if spec.is_void {
                        pos = open_end;
                        text_start = pos;
                        continue;
                    }
                    let (close_start, close_end) = match find_close_tag_range(bytes, open_end, name_lower) {
                        Some(pair) => pair,
                        None => (bytes.len(), bytes.len()),
                    };
                    if state.head_range.is_none() {
                        state.head_range = Some(open_end..close_start);
                    }
                    pos = close_end;
                    text_start = pos;
                    continue;
                }

                // ~keep Bail on unsupported tag kinds for M3c
                bail_unsupported(spec, pos)?;

                // ~keep Phase D': mirror Tier-2's preprocessing pipeline <nav> /
                // nav-hinted <header> / <footer> / <aside> / <form> strip.
                // When the user's preprocessing options request the strip,
                // jump past the matching close tag without pushing any frame.
                // Matches Tier-2's should_drop_for_preprocessing
                // (preprocessing_helpers.rs).
                if is_preprocessing_skip_candidate(name_lower) {
                    let close = parse::find_tag_close(bytes, name_end).ok_or(BailReason::LiteralLt { offset: pos })?;
                    let attrs_end = if close.1 { close.0.saturating_sub(1) } else { close.0 };
                    let skip_attrs = parse::collect_attrs(bytes, name_end, attrs_end);
                    if should_skip_preprocessing(name_lower, &skip_attrs, options) {
                        // ~keep Tier-2 still sees the dropped block between two parts of a list
                        // ~keep item (issue #583); see `BailReason::ListItemUnsupportedBlockChild`.
                        if !state.in_table_cell() && state.list_continuation_indent_width() > 0 {
                            return Err(BailReason::ListItemUnsupportedBlockChild);
                        }
                        // ~keep Tier-2 still sees the dropped block before the content after it.
                        state.last_closed_block = true;
                        let open_end = close.0 + 1;
                        if close.1 {
                            pos = open_end;
                        } else {
                            pos = find_balanced_close(bytes, open_end, name_lower).unwrap_or(bytes.len());
                        }
                        text_start = pos;
                        continue;
                    }
                }

                // ~keep Bail on <pre> when code_block_style is not Indented.
                // Phase Q.4: Tier-1 supports Indented (4-space) and
                // Backticks (`` ``` ``-fenced) code blocks via open_pre /
                // close_pre.  Tildes still require Tier-2's fence emitter.
                if matches!(spec.kind, TagKind::Pre)
                    && options.code_block_style == crate::options::CodeBlockStyle::Tildes
                {
                    return Err(BailReason::Classifier);
                }

                let close = parse::find_tag_close(bytes, name_end).ok_or(BailReason::LiteralLt { offset: pos })?;

                let attrs_end = if close.1 { close.0.saturating_sub(1) } else { close.0 };
                // ~keep Most tag kinds (headings, paragraphs, emphasis, code, etc.) do
                // not read attributes during emit.  Skip the allocation in the
                // common case; only collect for the kinds whose emit paths
                // actually consult attributes.  `<abbr>` is `TagKind::Inline`
                // but its `title` attribute is read at open time to mirror
                // Tier-2's `handle_abbr` — include it in the collect-set.
                // `Table` is in the collect-set for `border`, which feeds the
                // `has_span && border="0"` leg of Tier-2's `looks_like_layout`.
                // Omitting it silently disables that bail: `attrs` is empty, so the
                // lookup returns None, `border_zero` stays false, and Tier-1 emits a
                // GFM table where Tier-2 emits a bullet list. `TableCell` was already
                // here for colspan, which is why only the border half was affected.
                // `Blockquote` is here for `cite`, and it fell into the same trap: the
                // `BailReason::BlockquoteCite` check in `emit_open` read an empty `attrs`
                // and never fired, so Tier-1 kept dropping the citation while looking
                // fixed. Any new attribute read from `emit_open` needs its kind added here
                // in the same change, or the read silently sees nothing. `<input>` is here
                // for `type`, which `emit_void` reads to spot a checkbox in a list item.
                let needs_attrs = matches!(
                    spec.kind,
                    TagKind::Link
                        | TagKind::Image
                        | TagKind::List(ListKind::Ordered)
                        | TagKind::Table
                        | TagKind::TableCell { .. }
                        | TagKind::Pre
                        | TagKind::Code
                        | TagKind::Blockquote
                ) || matches!(name_lower, b"abbr" | b"input");
                let attrs: Vec<(&[u8], Option<&[u8]>)> = if needs_attrs {
                    parse::collect_attrs(bytes, name_end, attrs_end)
                } else {
                    Vec::new()
                };

                pos = close.0 + 1;

                // ~keep Any child tag opening while a link is on the stack means that
                // link's label buffer is no longer flat text — Tier-2's autolink
                // predicate strips such tags before comparing to href, so
                // `close_link` cannot safely trust a literal buffer mismatch here.
                // Mark every currently open link (not just the innermost, in case
                // of malformed nested `<a>`) so `close_link` can bail via
                // `BailReason::LinkAutolinkNestedMarkup` instead of risking a false
                // negative against Tier-2's tag-stripped text.
                for entry in &mut state.link_stack {
                    entry.2 = true;
                }

                if spec.is_void || close.1 {
                    if cell_needs_tier2(&mut state, spec, name_lower) {
                        return Err(BailReason::TableBlockChildInCell);
                    }
                    emit_void(&mut state, spec, name_lower, &attrs, html, options)?;
                    text_start = pos;
                    continue;
                }

                // ~keep Phase HH: nested tables are NO LONGER bailed here.  An inner
                // table is opened with `inline_mode = true` (set inside
                // `open_table`), and on `</table>` the rendered GFM markdown
                // is written into the parent cell buffer rather than
                // `state.output`.  The parent cell's newline-collapse step
                // then flattens the inner table to a single inline run,
                // matching Tier-2's behaviour.

                // ~keep M4: HTML5 implicit-close transitions.
                // Run BEFORE the block-in-cell check so that structural table
                // elements like `<tr>` correctly close any open `<td>`/`<th>`
                // before the block check evaluates `in_table_cell()`.  Without
                // this ordering, `<th>h1<tr>` would fire the bail even though
                // `<tr>` is not a content element inside the cell.
                while let Some(top) = state.stack.last() {
                    if !spec_rules::should_close_for_new_tag(top.spec, spec) {
                        break;
                    }
                    emit_close_for_implicit(&mut state, options, &mut table_probes)?;
                }

                // ~keep M9: Block-in-cell bail.
                // Evaluated AFTER M4 implicit closes so that table-structural
                // elements (e.g. a `<tr>` following an unclosed `<th>`) correctly
                // collapse the cell state before the check runs.
                // ~keep
                // ~keep The `inlineable` set below is the source of truth for what may
                // appear in a cell; every kind in it has cell-aware open/close helpers
                // that redirect output to the cell accumulator and match Tier-2's
                // `cell_text_content` normalisation (`text.replace('\n', " ")` when
                // `br_in_tables` is false).  Blockquote and Pre are included: in a cell
                // their close helpers write the cell break before the content rather
                // than a `> ` prefix or a code fence, which is what Tier-2 does too.
                // A block kind bails only when it has no cell-aware helper, so adding
                // one here without adding the helper will silently diverge from Tier-2.
                if cell_needs_tier2(&mut state, spec, name_lower) {
                    return Err(BailReason::TableBlockChildInCell);
                }
                if state.in_table_cell() && spec.is_block {
                    let inlineable = matches!(
                        spec.kind,
                        TagKind::Paragraph
                            | TagKind::Block
                            | TagKind::Summary
                            | TagKind::Figcaption
                            | TagKind::Blockquote
                            | TagKind::Pre
                            | TagKind::List(_)
                            | TagKind::ListItem
                            | TagKind::Heading(_)
                            | TagKind::DefinitionTerm
                            | TagKind::DefinitionDescription
                            | TagKind::Table
                    );
                    if !inlineable {
                        return Err(BailReason::TableBlockChildInCell);
                    }
                }

                // ~keep A nested list's indent must equal the cumulative width of every
                // ancestor marker ("- " = 2, "1. " = 3, "10. " = 4, ...); Tier-1's
                // `push_list_item_indent` hardcodes a uniform 2-space-per-depth
                // scheme. That is correct for ul-in-ul (all markers are 2 wide) but
                // wrong the moment an ordered list is anywhere in the ancestor chain
                // of a nested list. Bail so Tier-2's cumulative-width logic wins.
                if let TagKind::List(kind) = spec.kind {
                    if kind != ListKind::Definition
                        && state.list_depth > 0
                        && (kind == ListKind::Ordered || find_parent_list_kind(&state.stack) == Some(ListKind::Ordered))
                    {
                        return Err(BailReason::ListNestedOrdered);
                    }
                    if let Some(end) = state.last_ordered_list_end.filter(|_| kind == ListKind::Ordered) {
                        if state
                            .cell_or_output_mut()
                            .get(end..)
                            .is_some_and(|rest| rest.trim().is_empty())
                        {
                            return Err(BailReason::OrderedListAfterOrderedList);
                        }
                    }
                }

                // ~keep See `BailReason::ListItemUnsupportedBlockChild`'s doc comment for the
                // full root-cause writeup. `<blockquote>`, `<div>` and every other generic
                // block container, `<table>`, `<dl>` and headings bail unconditionally
                // inside a list item (any position); `<p>` bails only as
                // a continuation of already-started text (its bare-marker/first-content
                // shape is already correct); `<pre>` bails only as bare-marker/first
                // content (its continuation shape is already correct).
                if !state.in_table_cell() && state.list_continuation_indent_width() > 0 {
                    let bare_marker_line = line_is_bare_list_marker(&state.output);
                    let bails = match spec.kind {
                        TagKind::Blockquote | TagKind::Table | TagKind::Heading(_) => true,
                        TagKind::Block | TagKind::List(ListKind::Definition) => true,
                        TagKind::Paragraph => !bare_marker_line,
                        TagKind::Pre => bare_marker_line,
                        TagKind::List(_) | TagKind::ListItem => false,
                        // ~keep A stray term or description is pasted onto the item's line by both
                        // ~keep paths, so it does not end the item here.
                        TagKind::DefinitionTerm | TagKind::DefinitionDescription => false,
                        // ~keep Any other block after the item's content: Tier-2 starts it, or the
                        // ~keep text after it, at the content column.
                        _ => is_block_tag(name_lower) && !bare_marker_line,
                    };
                    if bails {
                        return Err(BailReason::ListItemUnsupportedBlockChild);
                    }
                }

                let prev_ctx = state.escape_ctx;
                let ol_start = if matches!(spec.kind, TagKind::List(ListKind::Ordered)) {
                    extract_ol_start(&attrs)
                } else {
                    1
                };
                if matches!(spec.kind, TagKind::Link) {
                    let (href, title) = extract_link_attrs(&attrs)?;
                    let href = href.map(|h| state.resolve_url(&h).unwrap_or(h));
                    state.link_stack.push((href, title, false));
                }
                // ~keep Mirror Tier-2's `semantic/attributes.rs::handle_abbr`:
                // capture the abbreviation's `title` attribute and emit
                // `" (title)"` after the abbr's text content at close time.
                if name_lower == b"abbr" {
                    // ~keep Decoded, not raw: Tier-2 reads this through `decoded_attribute`
                    // (issue #494), so a raw read here would reintroduce the defect in
                    // the fast path alone and split the two tiers.
                    let title = find_attr(&attrs, b"title")
                        .map(decode_attr)
                        .transpose()?
                        .map(|t| t.trim().to_owned())
                        .filter(|s| !s.is_empty());
                    state.abbr_titles.push(title);
                }

                // ~keep TIER1-57: `state.stack` is an explicit `Vec`, not native
                // recursion — the scanner itself has no stack-overflow risk.
                // But Tier-2's recursive `walk_node` silently truncates once
                // `depth >= effective_max_depth` (main.rs), and this scanner
                // had no equivalent ceiling: a pathologically deep DOM would
                // scan to completion here while Tier-2 truncates, diverging
                // from the byte-equality contract. Bail so Tier-2's (truncated,
                // authoritative) output wins instead of silently accepting
                // input Tier-2 would reject part of. `state.stack.len()` (open
                // tags below this one) is the same `depth` Tier-2 checks before
                // dispatching this node.
                let max_depth = crate::converter::main_helpers::effective_max_depth(options);
                if state.stack.len() >= max_depth {
                    return Err(BailReason::DepthLimitExceeded {
                        depth: state.stack.len(),
                        max_depth,
                    });
                }

                emit_open(&mut state, spec, name_lower, &attrs, &mut table_probes, options)?;

                // ~keep Record the content-start position AFTER emit_open so that
                // close-side post-processing operates on the correct slice.
                // When inside a table cell the position is in the cell buffer;
                // otherwise it is in the main output buffer.
                let output_content_start = state.cell_or_output_mut().len();

                let list_index = 0u16;

                state.stack.push(OpenTag {
                    spec,
                    content_start: output_content_start,
                    prev_escape_ctx: prev_ctx,
                    list_index,
                    ol_start,
                    name_range: name_start..name_end,
                    dropped_whitespace_only_text: false,
                    own_buffer: renders_into_own_buffer(spec.kind, name_lower, prev_ctx),
                    starts_with_whitespace: false,
                    children_in_own_buffer: matches!(name_lower, b"mark" | b"sub" | b"sup" | b"abbr")
                        || matches!(spec.kind, TagKind::DefinitionTerm | TagKind::DefinitionDescription),
                });

                apply_open_escape_ctx(&mut state, spec);

                text_start = pos;
            }
            _ => {
                // ~keep Batch ASCII fast-path: skip forward to the next `<` or `&`
                // (the only two bytes that require special handling) in one
                // memchr2 call instead of advancing one byte at a time.
                // flush_text handles entity decoding and whitespace collapsing
                // for whatever raw slice [text_start..pos] we hand it, so it
                // is correct to jump pos all the way to the next special byte.
                // This is safe across every context (<pre>, table cells, etc.)
                // because:
                //   • `<` still triggers the tag-dispatch path above.
                //   • `&` is preserved in the slice passed to flush_text, which
                //     entity-decodes it correctly regardless of context.
                //   • Raw-text elements (script/style/textarea/…) bail before
                //     reaching this arm, so we never skip inside them.
                match memchr2(b'<', b'&', &bytes[pos..]) {
                    Some(offset) if offset > 0 => pos += offset,
                    Some(_) => pos += 1,
                    None => pos = bytes.len(),
                }
            }
        }
    }

    if text_start < pos {
        flush_text(
            &mut state,
            &html[text_start..pos],
            text_start,
            false,
            false,
            false,
            options.br_in_tables,
        )?;
    }

    // ~keep Phase N2: implicitly close all remaining open elements at EOF.
    // HTML5 parsers (html5ever and tl) close every open element when input
    // ends, so Tier-2 produces output even for malformed input like
    // `<p>hello <b>world` (no `</b>`, no `</p>`).  Mirror that here by
    // running emit_close_for_implicit on every remaining frame, regardless
    // of whether it has an OptionalCloseRule.
    // ~keep
    // ~keep Before closing, trim trailing inline whitespace (spaces, tabs, newlines)
    // from the output buffer.  In well-formed HTML the close tag arrives
    // before the file's trailing newline; the inline close-marker emission
    // (e.g. `**` for `</strong>`) lands flush against the content.  At EOF
    // any trailing newline is between the implicit close and the file end,
    // not inside the inline body, so we trim it before pushing the close
    // marker to match Tier-2's `world**` instead of `world\n**`.
    while !state.stack.is_empty() {
        let buf = &mut state.output;
        while matches!(buf.as_bytes().last(), Some(b' ' | b'\t' | b'\n' | b'\r')) {
            buf.pop();
        }
        emit_close_for_implicit(&mut state, options, &mut table_probes)?;
    }

    // ~keep Mirror Tier-2's final render-stage order exactly (main.rs):
    // `trim_line_end_whitespace` runs BEFORE `collapse_excess_blank_lines`.
    // Without this, a code span's delimiter padding space that lands right
    // before an embedded newline in `<code>` content (e.g. a leading
    // `\n`-starting body next to a trailing backtick run needing a pad)
    // survives in Tier-1 but is stripped by Tier-2 as ordinary
    // end-of-line trailing whitespace — this is a general per-line pass,
    // not something scoped to code spans specifically, so reuse the exact
    // Tier-2 helper rather than reimplementing it.
    crate::converter::main_helpers::trim_line_end_whitespace(&mut state.output);

    // ~keep Collapse runs of 3+ consecutive newlines to exactly 2, matching Tier-2's
    // `collapse_excess_blank_lines` post-processing step.
    if state.output.contains("\n\n\n") {
        collapse_excess_blank_lines(&mut state.output);
    }

    // ~keep Normalise trailing newlines to match Tier-2's final-output contract:
    //   `format!("{}\n", output.trim_end_matches('\n'))`
    // Tier-2 strips all trailing newlines and appends exactly one.  We mirror
    // that here so paragraphs (which emit "\n\n") don't leave an extra blank
    // line at the end.
    if !state.output.is_empty() {
        let trimmed_end = state.output.trim_end_matches('\n');
        if trimmed_end.is_empty() {
            state.output.clear();
        } else {
            let trimmed_len = trimmed_end.len();
            state.output.truncate(trimmed_len);
            state.output.push('\n');
        }
    }

    Ok(ScanOutput {
        body: state.output,
        head_range: state.head_range,
    })
}

// ~keep ── Bail guard ────────────────────────────────────────────────────────────────

/// Return `Err(BailReason::Classifier)` for tag kinds not supported in M9.
///
/// Table-related tags are now handled by the scanner (M9); they are no longer
/// bailed here.  Table-specific bail reasons are emitted by the table-handling
/// code in `emit_open` and `emit_close`.
/// Locate the matching close tag for `tag_name` starting at `open_end`.
///
/// Returns `Some((close_start, close_end))` where `close_start` is the byte
/// index of the `<` opening the `</tag>` close and `close_end` is the byte
/// index immediately after its `>`.  `None` when no matching close exists.
///
/// Used by `<head>` silent-skip to record the content slice
/// (`open_end..close_start`) for metadata extraction while advancing past the
/// entire `<head>…</head>` block.
fn find_close_tag_range(bytes: &[u8], open_end: usize, tag_name: &[u8]) -> Option<(usize, usize)> {
    let len = bytes.len();
    let mut idx = open_end;
    while idx < len {
        match memchr3(b'<', b'<', b'<', &bytes[idx..]) {
            Some(off) => idx += off,
            None => return None,
        }
        if idx + 2 < len && bytes[idx + 1] == b'/' {
            let after_slash = idx + 2;
            if after_slash + tag_name.len() <= len
                && bytes[after_slash..after_slash + tag_name.len()].eq_ignore_ascii_case(tag_name)
            {
                let post_name = after_slash + tag_name.len();
                if matches!(bytes.get(post_name), Some(b'>' | b'/' | b' ' | b'\t' | b'\n' | b'\r')) {
                    let mut j = post_name;
                    while j < len && bytes[j] != b'>' {
                        j += 1;
                    }
                    if j < len {
                        return Some((idx, j + 1));
                    }
                    return None;
                }
            }
        }
        idx += 1;
    }
    None
}

// ~keep ── SVG helpers ───────────────────────────────────────────────────────────────

/// Find the byte offset immediately after the matching `</svg>` close tag,
/// starting from `open_end` (the byte after the `>` of the opening `<svg ...>`).
///
/// Tracks nesting depth so nested `<svg>` elements (valid in SVG 1.1) are
/// handled correctly.  Returns `None` when no matching close is found.
fn find_svg_close(bytes: &[u8], open_end: usize) -> Option<usize> {
    find_balanced_close(bytes, open_end, b"svg")
}

/// Find the byte offset immediately after the matching close tag for
/// `tag_name`, starting from `open_end` (the byte after the `>` of the
/// opening tag).  Tracks nesting depth so nested same-name elements are
/// handled correctly.  Returns `None` when no matching close is found.
fn find_balanced_close(bytes: &[u8], open_end: usize, tag_name: &[u8]) -> Option<usize> {
    let len = bytes.len();
    let mut idx = open_end;
    let mut depth = 1usize;
    while idx < len {
        match memchr::memchr(b'<', &bytes[idx..]) {
            Some(off) => idx += off,
            None => return None,
        }
        if idx + 1 < len && bytes[idx + 1] == b'/' {
            let name_start = idx + 2;
            if name_start + tag_name.len() <= len
                && bytes[name_start..name_start + tag_name.len()].eq_ignore_ascii_case(tag_name)
            {
                let after = name_start + tag_name.len();
                if matches!(
                    bytes.get(after),
                    Some(b'>' | b'/' | b' ' | b'\t' | b'\n' | b'\r') | None
                ) {
                    depth -= 1;
                    if depth == 0 {
                        let mut j = after;
                        while j < len && bytes[j] != b'>' {
                            j += 1;
                        }
                        // ~keep A closing tag with no terminating `>` before EOF must
                        // return `None` (not `Some(len + 1)`, an out-of-bounds
                        // offset one past the last valid slice/index into `bytes`).
                        // Callers (`find_svg_close` via `.unwrap_or(bytes.len())`)
                        // already handle `None` by clamping to end-of-input.
                        return if j < len { Some(j + 1) } else { None };
                    }
                }
            }
        } else if idx + 1 < len {
            let name_start = idx + 1;
            if name_start + tag_name.len() <= len
                && bytes[name_start..name_start + tag_name.len()].eq_ignore_ascii_case(tag_name)
            {
                let after = name_start + tag_name.len();
                if matches!(
                    bytes.get(after),
                    Some(b'>' | b'/' | b' ' | b'\t' | b'\n' | b'\r') | None
                ) {
                    let mut j = after;
                    let mut in_q: Option<u8> = None;
                    let tag_end = loop {
                        if j >= len {
                            break len;
                        }
                        match bytes[j] {
                            b'"' | b'\'' => {
                                if let Some(q) = in_q {
                                    if q == bytes[j] {
                                        in_q = None;
                                    }
                                } else {
                                    in_q = Some(bytes[j]);
                                }
                            }
                            b'>' if in_q.is_none() => {
                                break j + 1;
                            }
                            _ => {}
                        }
                        j += 1;
                    };
                    let is_self_closing = tag_end >= 2 && bytes[tag_end - 2] == b'/';
                    if !is_self_closing {
                        depth += 1;
                    }
                }
            }
        }
        idx += 1;
    }
    None
}

/// Emit a `<svg>` element as a Markdown base64 data URI, matching Tier-2's
/// `handle_svg` output byte-for-byte.
///
/// `svg_slice` is the raw HTML source bytes for the entire `<svg…>…</svg>`
/// element.  We re-parse it with `tl::parse` to get the canonical attribute
/// order that `serialize_element` produces (it sorts attributes alphabetically,
/// so raw-source slicing would diverge from Tier-2).
///
/// Mirrors Tier-2's `media/svg.rs::handle_svg`:
/// - Walks children for a `<title>` tag → alt text.  Default: "SVG Image".
/// - Calls `serialize_element` on the root SVG node.
/// - Base64-encodes (STANDARD engine) the serialized bytes.
/// - Emits `![{title}](data:image/svg+xml;base64,{b64})`.
/// - When `options.skip_images` → emits nothing (matches Tier-2 skip).
fn emit_svg_from_slice(
    svg_slice: &str,
    svg_start_offset: usize,
    state: &mut Tier1State,
    options: &ConversionOptions,
) -> Result<(), BailReason> {
    // ~keep CDATA inside SVG cannot be processed correctly without the prescan's
    // entity-escaping transformation.  Bail to Tier-2 so it sees the
    // prescan-normalized form (where `<![CDATA[` is escaped to `&lt;![CDATA[`).
    if svg_slice.contains("<![CDATA[") {
        return Err(BailReason::Cdata {
            offset: svg_start_offset,
        });
    }

    if options.skip_images {
        return Ok(());
    }

    use crate::converter::media::svg::serialize_element;
    use base64::{Engine as _, engine::general_purpose::STANDARD};

    // ~keep Re-parse just the SVG fragment.  Wrap it in a minimal document so
    // tl has proper context — the same pattern used by head_metadata.rs.
    let wrapped = format!("<html><body>{svg_slice}</body></html>");
    let dom = match tl::parse(&wrapped, tl::ParserOptions::default()) {
        Ok(d) => d,
        Err(_) => {
            // ~keep Parse failure: emit nothing rather than bail — matches
            // Tier-2's silent skip on serialization failure.
            return Ok(());
        }
    };
    let parser = dom.parser();

    // ~keep Locate the first `<svg>` node in the parsed fragment.
    let svg_handle = dom.nodes().iter().enumerate().find_map(|(i, node)| {
        if let tl::Node::Tag(tag) = node {
            if tag.name().as_utf8_str().as_ref().eq_ignore_ascii_case("svg") {
                Some(tl::NodeHandle::new(i as u32))
            } else {
                None
            }
        } else {
            None
        }
    });

    let Some(handle) = svg_handle else {
        return Ok(());
    };

    // ~keep Extract title from a direct `<title>` child, mirroring Tier-2.
    let title = if let Some(tl::Node::Tag(svg_tag)) = handle.get(parser) {
        let mut found = String::from("SVG Image");
        for child_handle in svg_tag.children().top().iter() {
            if let Some(tl::Node::Tag(child)) = child_handle.get(parser) {
                if child.name().as_utf8_str().as_ref().eq_ignore_ascii_case("title") {
                    let mut text = String::new();
                    for grandchild in child.children().top().iter() {
                        if let Some(tl::Node::Raw(raw)) = grandchild.get(parser) {
                            text.push_str(&raw.as_utf8_str());
                        }
                    }
                    let trimmed = text.trim().to_owned();
                    if !trimmed.is_empty() {
                        found = trimmed;
                    }
                    break;
                }
            }
        }
        found
    } else {
        String::from("SVG Image")
    };

    let svg_html = serialize_element(&handle, parser);
    let base64_svg = STANDARD.encode(svg_html.as_bytes());

    // ~keep Security fix mirror (media/svg.rs::handle_svg, outside tier1/): an
    // unescaped `<title>` here lets `x](https://evil.example)y` in the SVG
    // source close the image label early and open a second, attacker-
    // controlled Markdown image/link — the input is inert HTML, but the
    // unescaped label turns it into a live injection. `escape_link_label`
    // (utility/content.rs) is the shared helper Tier-2's `<a>` label path
    // already uses; call the same one here rather than a third
    // hand-written escaper.
    let escaped_title = crate::converter::utility::escaping::escape_link_label(&title);

    let dest = state.cell_or_output_mut();
    dest.push_str("![");
    dest.push_str(&escaped_title);
    dest.push_str("](data:image/svg+xml;base64,");
    dest.push_str(&base64_svg);
    dest.push(')');

    Ok(())
}

/// Skip the body of a raw-text element (script/style/textarea/iframe/…).
///
/// `open_end` is the byte index immediately after the tag's `>`.  `tag_name`
/// is the lowercased open-tag name.  Returns the byte index after the
/// matching `</tag>` close, or `None` if no matching close tag exists in the
/// remainder of the input.
///
/// Mirrors the prescan's STRIP_CONTENT_TAGS handling: content is discarded,
/// only the position advances.  Matches Tier-2's behaviour byte-for-byte
/// because Tier-2 sees this content already stripped by the prescan.
fn find_raw_text_close(bytes: &[u8], open_end: usize, tag_name: &[u8]) -> Option<usize> {
    let len = bytes.len();
    let mut idx = open_end;
    while idx < len {
        match memchr3(b'<', b'<', b'<', &bytes[idx..]) {
            Some(off) => idx += off,
            None => return None,
        }
        if idx + 2 < len && bytes[idx + 1] == b'/' {
            let after_slash = idx + 2;
            if after_slash + tag_name.len() <= len
                && bytes[after_slash..after_slash + tag_name.len()].eq_ignore_ascii_case(tag_name)
            {
                let post_name = after_slash + tag_name.len();
                if matches!(bytes.get(post_name), Some(b'>' | b'/' | b' ' | b'\t' | b'\n' | b'\r')) {
                    let mut j = post_name;
                    while j < len && bytes[j] != b'>' {
                        j += 1;
                    }
                    if j < len {
                        return Some(j + 1);
                    }
                    return None;
                }
            }
        }
        idx += 1;
    }
    None
}

#[inline]
const fn bail_unsupported(spec: &TagSpec, _offset: usize) -> Result<(), BailReason> {
    match spec.kind {
        // ~keep This arm IS load-bearing — do not delete it as unreachable.  The inline
        // raw-text handling above is gated on `TagKind::Ignored && is_rawtext`, which
        // is only `<script>`/`<style>`.  The seven genuine `TagKind::RawText` kinds
        // (title / xmp / textarea / iframe / noscript / noembed / noframes) fall
        // through to here, and this is the bail that keeps Tier-1 from emitting their
        // text content incorrectly.  See the sibling note above `find_raw_text_close`.
        TagKind::RawText(_) => Err(BailReason::Classifier),

        // ~keep `Ignored` tags (head/meta/link/script/style) are now handled inline
        // by the main scan loop (see the dispatch above `bail_unsupported`).
        // The match arm is kept for exhaustiveness — it cannot fire in
        // practice.
        TagKind::Ignored => Err(BailReason::Classifier),

        _ => Ok(()),
    }
}

// ~keep `TagKind::Block` is Tier-1's catch-all for HTML5 "generic block container"
// elements, but Tier-2's `main.rs` dispatch match does NOT give every one of
// them a dedicated separator-emitting handler. `<div>` (block/div.rs), the
// semantic/media/form-dispatched names (section, article, header, footer,
// aside, main, nav, details, dialog, figure, menu, audio, video, fieldset,
// legend, form), and -- as of the fix below -- `address`/`search`/`hgroup`/
// `center` (routed straight to `block::div::handle`, since they are
// content-bearing containers with no formatting beyond block separation) all
// render through a handler that pushes a leading and/or trailing `"\n\n"`.
// The names below are the ones that still fall through to Tier-2's `_ =>` arm
// (`block::unknown::handle`) or, for `html`/`body`,
// `block::container::handle_structural_container` -- both of which just walk
// children with NO separator of their own, and deliberately so:
// `colgroup`/`col` are table-internal metadata (never render visible content
// of their own), `base` is void metadata, and `html`/`body` are document
// wrappers whose children ARE the document -- giving them a separator would
// change the shape of every converted document, not fix a content-merging bug.
// `nav`/`form`/`header`/`footer`/`aside` are excluded from this list even
// though they can also hit a preprocessing-strip shortcut elsewhere
// (`is_preprocessing_skip_candidate`): when that shortcut does NOT fire, they
// get semantic-handler separator behaviour like `<div>`.
fn block_container_is_passthrough(name_lower: &[u8]) -> bool {
    matches!(name_lower, b"colgroup" | b"col" | b"base" | b"html" | b"body")
}

fn emit_open(
    state: &mut Tier1State,
    spec: &'static TagSpec,
    name_lower: &[u8],
    attrs: &[(&[u8], Option<&[u8]>)],
    table_probes: &mut Vec<TableLayoutProbe>,
    options: &ConversionOptions,
) -> Result<(), BailReason> {
    // ~keep Opening any tag ends the "just closed a custom element" boundary
    // window (see the field's doc comment on `Tier1State`).
    state.last_closed_custom_element = false;
    // ~keep Opening any tag ends the "just emitted an <img>" window too (see
    // `Tier1State::last_emitted_was_img`); the `TagKind::Image` arm below
    // re-sets it to true after this reset runs.
    state.last_emitted_was_img = false;
    if std::mem::take(&mut state.last_closed_block) && is_inline_tag(name_lower) {
        // ~keep An inline element after a block in a cell is left to Tier-2 (see `cell_needs_tier2`).
        if state.in_table_cell() {
            return Err(BailReason::TableBlockChildInCell);
        }
        separate_inline_after_block(state, options.br_in_tables)?;
    }

    // ~keep Tier-2 wraps these in markers this scanner has no arm for, so emitting them as
    // transparent inline content would silently drop the markers. See
    // `BailReason::InlineMarkerNotReproduced`.
    if name_lower == b"q" || (name_lower == b"mark" && options.highlight_style != crate::options::HighlightStyle::None)
    {
        return Err(BailReason::InlineMarkerNotReproduced);
    }

    // ~keep Phase V: when a block-level tag opens inside a link, bail.  Tier-2's
    // link handler collapses block children (img alt, paragraph text) into
    // an inline link label; replicating that in Tier-1 requires content
    // capture similar to Phase R's summary buffer.  Until that lands, bail
    // so Tier-2's fallback handles the collapse.
    if matches!(
        spec.kind,
        TagKind::Block
            | TagKind::Paragraph
            | TagKind::Heading(_)
            | TagKind::Blockquote
            | TagKind::Pre
            | TagKind::List(_)
            | TagKind::Table
            | TagKind::Summary
    ) && state.stack.iter().any(|f| matches!(f.spec.kind, TagKind::Link))
    {
        return Err(BailReason::Classifier);
    }
    match spec.kind {
        TagKind::Paragraph => open_paragraph(state, options.br_in_tables),
        TagKind::Heading(_) => open_heading(state),
        TagKind::Blockquote => {
            // ~keep A citation is rendered after the quoted content and resolved against
            // `base_url`; Tier-1 does neither. See `BailReason::BlockquoteCite`.
            if find_attr(attrs, b"cite").is_some_and(|value| !value.is_empty()) {
                return Err(BailReason::BlockquoteCite);
            }
            open_blockquote(state);
        }
        TagKind::Pre => open_pre(state, attrs),
        TagKind::List(ListKind::Definition) => open_dl(state),
        TagKind::List(kind) => open_list(state, kind, options),
        TagKind::ListItem => open_list_item(state, options),
        TagKind::DefinitionTerm => open_dt(state),
        TagKind::DefinitionDescription => open_dd(state),
        TagKind::Strong => {
            // ~keep Inside a <summary> accumulation buffer, Tier-2 processes
            // children with `in_strong: true` which suppresses nested
            // strong markers.  Mirror that by not pushing `**` when inside
            // a summary, so `<strong>b</strong>` inside `<summary>` emits
            // just `b` instead of `**b**`.
            // Phase FF-2: figcaption uses the same buffer stack but
            // Tier-2 does NOT set in_strong for figcaption children, so
            // emit `**` normally when the topmost wrap-buf is a
            // figcaption (or there's no wrap-buf at all).
            //
            // ~keep `EscapeCtx::STRONG` here is `state.escape_ctx` BEFORE this
            // tag's own bit is applied (`apply_open_escape_ctx` runs after
            // `emit_open` returns) — i.e. "is there already a `<strong>`
            // ancestor" — matching Tier-2's `ctx.in_strong` check in
            // `handle_strong`, which likewise tests the context inherited
            // from ancestors before forcing it true for its own children.
            // Without this, `<strong><strong>x</strong></strong>` emits
            // `****x****`, which is not valid CommonMark strong emphasis.
            // Tier-2's `handle_strong` walks children with no markers under `in_code`,
            // which covers both a `<code>` span and a `<pre>` block. Mirror via EscapeCtx.
            if !state.summary_at_top()
                && !state.escape_ctx.contains(EscapeCtx::STRONG)
                && !state.escape_ctx.contains(EscapeCtx::CODE)
                && !state.escape_ctx.contains(EscapeCtx::PRE)
            {
                // ~keep issue #483: opening `**` right after the buffer's own matching
                // `**` close (no intervening content) would form one longer
                // CommonMark delimiter run on reparse, not two independent strong
                // spans. Tier-2 merges this case (`merge_adjacent_emphasis`);
                // Tier-1 does not replicate the merge, so it bails instead.
                if state.cell_or_output_mut().ends_with("**") {
                    return Err(BailReason::AdjacentInlineEmphasis);
                }
                state.cell_or_output_mut().push_str("**");
            }
        }
        TagKind::Emphasis => {
            // ~keep issue #483: same reasoning as the `Strong` arm above, for the lone
            // `*` marker -- but a lone `*` must not match the second half of a `**`
            // (that is a `<strong>` close, an unrelated tag kind), hence excluding
            // `ends_with("**")` here.
            // `handle_emphasis` is likewise transparent under `in_code`.
            if state.escape_ctx.contains(EscapeCtx::CODE) || state.escape_ctx.contains(EscapeCtx::PRE) {
                return Ok(());
            }
            let buf = state.cell_or_output_mut();
            if buf.ends_with('*') && !buf.ends_with("**") {
                return Err(BailReason::AdjacentInlineEmphasis);
            }
            buf.push('*');
        }
        TagKind::Strikethrough => {
            // ~keep Tier-2's handle_strikethrough suppresses the `~~` wrapping
            // when inside `<code>`/`<pre>` (in_code).  Mirror via EscapeCtx.
            if !state.escape_ctx.contains(EscapeCtx::CODE) && !state.escape_ctx.contains(EscapeCtx::PRE) {
                // ~keep issue #483, `~~` form: opening right after the buffer's own matching
                // close forms one longer run on reparse, not two spans. Tier-2 merges
                // this (`emit_wrapped_inline`); Tier-1 does not, so it bails.
                if state.cell_or_output_mut().ends_with("~~") {
                    return Err(BailReason::AdjacentInlineEmphasis);
                }
                state.cell_or_output_mut().push_str("~~");
            }
        }
        TagKind::Inserted => {
            // ~keep Tier-2's handle_inserted emits `==` markers unconditionally for
            // <ins>.  Mirror Strikethrough's in-code/pre suppression for
            // consistency (no `==` inside backtick spans / fenced blocks).
            if !state.escape_ctx.contains(EscapeCtx::CODE) && !state.escape_ctx.contains(EscapeCtx::PRE) {
                // ~keep issue #483, `==` form: same reasoning as the `~~` arm above.
                if state.cell_or_output_mut().ends_with("==") {
                    return Err(BailReason::AdjacentInlineEmphasis);
                }
                state.cell_or_output_mut().push_str("==");
            }
        }
        // ~keep Phase CC: defer the open backtick marker — close_code does
        // smart escaping based on the content (mirrors Tier-2's
        // render_code_with_escaping at inline/code.rs:260).  Inside an
        // outer <code> or <pre>, the inner code is transparent.
        TagKind::Code if !state.escape_ctx.contains(EscapeCtx::PRE) && !state.escape_ctx.contains(EscapeCtx::CODE) => {}
        TagKind::Code if state.pre_lang.is_none() && state.escape_ctx.contains(EscapeCtx::PRE) => {
            if let Some(lang) = extract_language_from_class(attrs) {
                state.pre_lang = Some(lang);
            }
        }
        TagKind::Link => open_link(state),
        TagKind::Table => open_table(state, attrs, table_probes),
        TagKind::TableCaption => open_table_caption(state),
        TagKind::TableHead => open_table_head(state)?,
        TagKind::TableBody => open_table_body(state)?,
        TagKind::TableFoot => open_table_foot(state),
        TagKind::TableRow => open_table_row(state),
        TagKind::TableCell { is_header } => open_table_cell(state, attrs, is_header, table_probes)?,
        // ~keep Block containers: emit a leading blank-line separator when there's
        // already preceding content.  Mirrors Tier-2's div/sectioning handlers
        // (`block/div.rs`'s `needs_leading_sep` branch and the separator push in
        // `semantic/sectioning.rs`) which prefix block content with `\n\n` to
        // separate it from siblings.
        // ~keep
        // ~keep Inside a table cell, Tier-2's `is_table_continuation` in `div.rs` treats
        // a sibling-div as a "table continuation" and emits `"  \n"` when
        // the cell already has non-`|`/non-`<br>` content.  After
        // `close_table_cell`'s `replace('\n', ' ')` step, this becomes a 3-space
        // run between sibling divs — matching Tier-2's lists_timeline cell
        // layout `[link]   [other-link]`.  Without this, Tier-1 emits 1 space.
        TagKind::Block => {
            if block_container_is_passthrough(name_lower) {
                // ~keep No separator, in or out of a table cell: Tier-2's catch-all
                // handler for these names never emits one. See
                // `block_container_is_passthrough`'s doc comment.
            } else if state.in_table_cell() {
                break_cell_before_block(state, options.br_in_tables);
            } else {
                // ~keep Tier-2's `needs_leading_sep` (block/div.rs) appends "\n\n" BLINDLY
                // whenever the output doesn't already end with a blank line — it does
                // NOT special-case a lone trailing newline into pushing just one more.
                // That produces a transient run of 3 newlines when a
                // single-newline-terminated sibling (a list/table/`<hr>`) precedes this
                // div; ordinarily harmless, since the final `collapse_excess_blank_lines`
                // pass folds any 3+ run back down to exactly 2 — EXCEPT when the div's
                // own first child is a `<blockquote>`, whose entry logic
                // (`close_blockquote`) inspects the exact trailing state before that
                // collapse runs and treats "ends with \n\n" (true for the transient
                // 3-run too) as "pop one", landing on the blank line Tier-2 actually
                // keeps. `ensure_blank_line`'s normalized (never-3+) output would make
                // that pop collapse a lone newline straight back down to one, losing the
                // separator — hence the blind push here instead of `ensure_blank_line`.
                // ~keep The open summary, figcaption or caption buffer, as `close_block_container` uses.
                let dest = state.cell_or_output_mut();
                if !dest.is_empty() && !dest.ends_with("\n\n") {
                    crate::converter::tier1::state::trim_trailing_horizontal(dest);
                    dest.push_str("\n\n");
                }
            }
        }
        // ~keep Summary: push accumulation buffer so children redirect into it (Phase R).
        TagKind::Summary => {
            if state.in_table_cell() {
                break_cell_before_block(state, options.br_in_tables);
            }
            open_summary(state);
        }
        // ~keep Figcaption: same buffer mechanism as summary (Phase FF-2); the
        // wrap delimiter differs (`*…*` vs `**…**`) and is emitted by
        // close_figcaption.
        TagKind::Figcaption => open_figcaption(state),
        // ~keep Button: no leading separator (matches Tier-2 handle_button which
        // does nothing on open).  Close-side `\n\n` is emitted by close_button.
        TagKind::Button => {}
        TagKind::Inline => {}
        _ => {}
    }

    Ok(())
}

/// Writes the cell break Tier-2's `div::handle` writes before a block in a cell that already has
/// content.
fn break_cell_before_block(state: &mut Tier1State, br_in_tables: bool) {
    with_cell_scratch(state, |cell_buf| {
        if !cell_buf.is_empty() && !cell_buf.ends_with('|') && !cell_buf.ends_with("<br>") && !cell_buf.ends_with('\n')
        {
            // ~keep Tier-2's helper, so the break follows `br_in_tables` as Tier-2's does.
            crate::converter::main_helpers::emit_table_cell_break(cell_buf, br_in_tables);
        }
    });
}

fn open_paragraph(state: &mut Tier1State, br_in_tables: bool) {
    // ~keep When inside a table cell, treat `<p>` as a transparent container.
    // Tier-2's paragraph.rs writes the cell break (`<br>` under `br_in_tables`,
    // a space otherwise) when `in_table_cell` and there is already cell content
    // (issue #647); we mirror that behaviour so the cell buffer stays on one
    // logical line (no `\n` in cell output to collapse later).
    if state.in_table_cell() {
        with_cell_scratch(state, |cell_buf| {
            if !cell_buf.is_empty() && !cell_buf.ends_with("<br>") && !cell_buf.ends_with('\n') {
                crate::converter::main_helpers::emit_table_cell_break(cell_buf, br_in_tables);
            }
        });
        return;
    }
    // ~keep Mirrors Tier-2: when output is non-empty and doesn't already end
    // with "\n\n", push "\n\n" (may produce three newlines total when
    // output ends with a single "\n", e.g. right after a table row or
    // an `<hr>`).
    // Phase EE: when the paragraph is the first child of a list-item
    // (output ends with a freshly-emitted bullet like `- ` or `1. `),
    // the paragraph content joins the bullet inline.  Tier-2's
    // paragraph.rs (`is_list_continuation`) only applies this special case
    // when `ctx.in_list_item` is true -- gate on the same condition here.
    // Without it, ordinary top-level text that happens to end in "- "/"* "/
    // "+ "/"N. " (a real bullet-looking suffix, OR the `<strong>`/`<em>`
    // ambiguity `line_is_bare_list_marker` exists to rule out) wrongly
    // skipped the "\n\n" separator before a following `<p>` and glued the
    // two blocks onto a single line, even with no list anywhere in sight.
    // Check BEFORE `trim_trailing_horizontal`, which would strip the
    // trailing space from the bullet.
    let in_list_item = state
        .stack
        .iter()
        .any(|frame| matches!(frame.spec.kind, TagKind::ListItem));
    if in_list_item {
        let dest = state.cell_or_output_mut();
        if dest.ends_with("- ") || dest.ends_with("* ") || dest.ends_with("+ ") || ends_with_ordered_marker(dest) {
            return;
        }
    }
    // ~keep Drop trailing horizontal whitespace from inter-tag preservation
    // (Phase U-2) before the block separator.
    let dest = state.cell_or_output_mut();
    crate::converter::tier1::state::trim_trailing_horizontal(dest);
    if !dest.is_empty() && !dest.ends_with("\n\n") {
        dest.push_str("\n\n");
    }
}

fn open_heading(state: &mut Tier1State) {
    // ~keep When inside a table cell, Tier-2 does NOT add a leading separator before
    // the heading (`needs_leading_sep = false` when `in_table_cell`).  The
    // heading text is emitted directly into the cell accumulator with no `#`
    // prefix and no surrounding newlines.
    if state.in_table_cell() {
        return;
    }
    // ~keep A heading inside `<summary>`/`<figcaption>` is not in a table cell but
    // also must not touch `state.output`: Tier-2's `handle_summary` walks
    // children with a fresh LOCAL `content` buffer as `output`, so
    // `heading.rs`'s leading-separator step runs against that buffer, not
    // the real document output. `cell_or_output_mut` already resolves to the
    // active summary/figcaption buffer here (it takes priority over table
    // cells), so routing through it — instead of the hardcoded
    // `state.ensure_blank_line()` — keeps the separator (and, in
    // `close_heading`, the `#` prefix) inside the same buffer the heading's
    // own text lands in. Without this, `content_start` (captured right after
    // this call, from that same buffer's length) gets treated as an offset
    // into `state.output` instead — an unrelated, much larger buffer — and
    // `close_heading` splices its `#` prefix into the middle of whatever
    // text happens to sit at that byte offset in the real output.
    ensure_blank_line_buf(state.cell_or_output_mut());
}

/// Buffer-generic equivalent of [`Tier1State::ensure_blank_line`].
///
/// Operates on whichever accumulator buffer the caller passes in — `state.output`,
/// a table cell, or a `<summary>`/`<figcaption>` wrap buffer — rather than assuming
/// `state.output`. See `Tier1State::cell_or_output_mut`'s buffer-selection priority.
fn ensure_blank_line_buf(buf: &mut String) {
    if buf.is_empty() {
        return;
    }
    while buf.ends_with(' ') || buf.ends_with('\t') {
        buf.pop();
    }
    if buf.ends_with("\n\n") {
        return;
    }
    if buf.ends_with('\n') {
        buf.push('\n');
    } else {
        buf.push_str("\n\n");
    }
}

fn open_blockquote(state: &mut Tier1State) {
    // ~keep Tier-2's `handle_blockquote` (blockquote.rs) branches on nesting: a
    // NESTED blockquote (already inside an outer one, per `EscapeCtx::BLOCKQUOTE`)
    // unconditionally gets a blank-line separator on open. A TOP-LEVEL
    // blockquote instead computes its separator from whatever the
    // immediately preceding sibling already left in `output` — see
    // `close_blockquote`, which needs that untouched pre-open tail, so
    // nothing is done here for the top-level case.
    if state.escape_ctx.contains(EscapeCtx::BLOCKQUOTE) {
        state.ensure_blank_line();
    }
}

fn open_pre(state: &mut Tier1State, attrs: &[(&[u8], Option<&[u8]>)]) {
    state.ensure_blank_line();
    if let Some(lang) = extract_language_from_class(attrs) {
        state.pre_lang = Some(lang);
    }
}

/// Extract the language tag from a `class` attribute matching `language-X`
/// or `lang-X`.  Mirrors Tier-2's `extract_language_from_pre`.
fn extract_language_from_class(attrs: &[(&[u8], Option<&[u8]>)]) -> Option<String> {
    let class_bytes = find_attr(attrs, b"class")?;
    // ~keep Decoded before the `language-` prefix scan, matching Tier-2's `code_block.rs`
    // (issue #494). Decoding first is also what makes the split correct: a character
    // reference can encode the whitespace this splits on.
    let class = decode_attr(class_bytes).ok()?;
    for cls in class.split_ascii_whitespace() {
        if let Some(rest) = cls.strip_prefix("language-") {
            return Some(rest.to_owned());
        }
        if let Some(rest) = cls.strip_prefix("lang-") {
            return Some(rest.to_owned());
        }
    }
    None
}

/// Strip one bare list marker -- a single bullet char (`-`, `*`, `+`) followed by a space,
/// or one-or-more ASCII digits followed by `". "` -- from the front of `text`, returning
/// what remains after it. Returns `None` when `text` does not start with a marker. Mirrors
/// Tier-2's `strip_leading_bare_marker` (`list/utils.rs`).
fn strip_leading_bare_marker(text: &str) -> Option<&str> {
    let digit_count = text.bytes().take_while(u8::is_ascii_digit).count();
    if digit_count > 0 {
        if let Some(rest) = text[digit_count..].strip_prefix(". ") {
            return Some(rest);
        }
    }
    let mut chars = text.chars();
    let first = chars.next()?;
    if matches!(first, '-' | '*' | '+') {
        return chars.as_str().strip_prefix(' ');
    }
    None
}

/// Whether the current line of `output` (from the last `\n`, or the very start of the
/// buffer) is nothing but one or more bare list markers -- concatenated bullets
/// (`"- "`, `"* "`, `"+ "`) and/or ordered markers (`"N. "`) -- with optional leading
/// indentation and no other content. Mirrors Tier-2's `line_is_bare_list_marker`
/// (`list/utils.rs`).
///
/// ~keep A plain suffix check like `output.ends_with("* ")` also matches the closing
/// `"**"` of `<strong>` (or the closing `"*"` of `<em>`) immediately followed by a
/// migrated trailing space, e.g. `"**b** "`: its last two bytes are literally `'*'`
/// and `' '`, indistinguishable by suffix alone from a real bare `"* "` bullet. That
/// false positive suppressed the newline before a nested list, flattening it onto
/// the parent line and destroying it on reparse. Requiring the WHOLE line (after
/// stripping only leading indentation) to decompose into nothing but marker tokens
/// rules that out, and also handles several single-child lists nested directly
/// inside each other, whose bare markers stack on one physical line with nothing
/// else between them.
/// Whether the scanner is inside a `<dt>` or `<dd>` that a list item holds without a `<dl>`.
/// Tier-2 writes such a term below an empty item, so the rule after it and the text after that
/// stay on the fast path, where `- t` keeps the term in the item.
fn inside_stray_definition(state: &Tier1State) -> bool {
    for frame in state.stack.iter().rev() {
        match frame.spec.kind {
            TagKind::DefinitionTerm | TagKind::DefinitionDescription => return true,
            TagKind::ListItem | TagKind::List(_) => return false,
            _ => {}
        }
    }
    false
}

fn line_is_bare_list_marker(output: &str) -> bool {
    let line_start = output.rfind('\n').map_or(0, |pos| pos + 1);
    let mut rest = output[line_start..].trim_start_matches([' ', '\t']);
    if rest.is_empty() {
        return false;
    }
    while let Some(next) = strip_leading_bare_marker(rest) {
        if next.is_empty() {
            return true;
        }
        rest = next;
    }
    false
}

fn open_list(state: &mut Tier1State, kind: ListKind, options: &ConversionOptions) {
    // ~keep When inside a table cell, mirror Tier-2's `add_list_leading_separator`:
    // emit a line-break separator if there is already cell content (but not if it
    // already ends with `|`, ` `, or `<br>`) -- a literal `<br>` under
    // `br_in_tables`, otherwise a single space, exactly like
    // `main_helpers::emit_table_cell_break`.  Do not touch `state.output`.
    if state.in_table_cell() {
        with_cell_scratch(state, |cell_buf| {
            if !cell_buf.is_empty()
                && !cell_buf.ends_with('|')
                && !cell_buf.ends_with(' ')
                && !cell_buf.ends_with("<br>")
            {
                if options.br_in_tables {
                    cell_buf.push_str("<br>");
                } else {
                    cell_buf.push(' ');
                }
            }
        });
        state.list_depth = state.list_depth.saturating_add(1);
        if matches!(kind, ListKind::Unordered) {
            state.ul_depth = state.ul_depth.saturating_add(1);
        }
        return;
    }
    let current_list_depth = state.list_depth;
    {
        let dest = state.cell_or_output_mut();
        if !dest.is_empty() {
            if current_list_depth == 0 {
                // ~keep Mirror Tier-2's top-level `add_list_leading_separator` branch
                // (`!ctx.in_list`, list/utils.rs): append "\n\n" unless the tail is
                // already a blank line or the current line is nothing but a bare
                // list marker (see `line_is_bare_list_marker`'s doc comment for why
                // a plain suffix check on "* "/"- "/". " is not enough here).
                let needs_newline = !dest.ends_with("\n\n") && !line_is_bare_list_marker(dest);
                if needs_newline {
                    dest.push_str("\n\n");
                }
            } else {
                // ~keep Mirror Tier-2's `ctx.in_list_item` branch the same way: the same
                // whole-line bare-marker check (against a bare newline instead of a
                // blank line), trimming ONLY once it actually decides to insert the
                // separator — not eagerly beforehand.
                let needs_newline = !dest.ends_with('\n') && !line_is_bare_list_marker(dest);
                if needs_newline {
                    crate::converter::tier1::state::trim_trailing_horizontal(dest);
                    dest.push('\n');
                }
            }
        }
    }
    state.list_depth = state.list_depth.saturating_add(1);
    if matches!(kind, ListKind::Unordered) {
        state.ul_depth = state.ul_depth.saturating_add(1);
    }
}

/// Cycle through the canonical default `options.bullets` value (`"-*+"`) by
/// `<ul>` nesting depth.  The router (`router.rs::classify`) gates Tier-1 to
/// the literal default, so this hardcoded cycle reproduces Tier-2 byte-for-byte.
const TIER1_BULLETS: [u8; 3] = [b'-', b'*', b'+'];

fn open_list_item(state: &mut Tier1State, options: &ConversionOptions) {
    // ~keep When inside a table cell, Tier-2 does NOT emit bullet/number prefixes
    // for list items (see list/item.rs: `if !ctx.in_table_cell { ... bullet ... }`).
    // Sibling <li>s still need a boundary though — mirror Tier-2's reuse of
    // `add_list_leading_separator` per item (list/item.rs's `else if
    // ctx.in_table_cell` arm) with the same continuation condition already used by
    // `open_list` above: a literal `<br>` under `br_in_tables`, otherwise a single
    // space (mirroring `main_helpers::emit_table_cell_break`), so
    // `<li>a</li><li>b</li>` in a cell becomes `a<br>b` (or `a b` with
    // `br_in_tables: false`) instead of the two items' raw text running together.
    if state.in_table_cell() {
        if find_parent_list_kind(&state.stack) == Some(ListKind::Ordered) {
            increment_ol_counter(&mut state.stack);
        }
        with_cell_scratch(state, |cell_buf| {
            if !cell_buf.is_empty()
                && !cell_buf.ends_with('|')
                && !cell_buf.ends_with(' ')
                && !cell_buf.ends_with("<br>")
            {
                if options.br_in_tables {
                    cell_buf.push_str("<br>");
                } else {
                    cell_buf.push(' ');
                }
            }
        });
        return;
    }
    let parent_kind = find_parent_list_kind(&state.stack);
    let indent_depth = state.list_depth.saturating_sub(1);
    // ~keep Mirror Tier-2's fresh-line-only indent (list/item.rs): a nested list that is
    // the sole/first content of its enclosing <li> renders directly after that
    // parent's own bare marker on the SAME physical line -- the parent marker's own
    // printed width already reaches this item's target column, so indenting here
    // too would double-count it. The indent is only needed when this item genuinely
    // starts a fresh physical line.
    let ordered_index = (parent_kind == Some(ListKind::Ordered)).then(|| {
        let counter = increment_ol_counter(&mut state.stack);
        find_ol_start(&state.stack).saturating_sub(1) + counter
    });
    // ~keep Mirror Tier-2 (list/item.rs, issue #625): text inside the list before this item
    // ~keep ends its line, with a blank line when the marker line cannot interrupt the text. A
    // ~keep bullet with content always can.
    let line_start = state.output.rfind('\n').map_or(0, |pos| pos + 1);
    let after_text = !state.output[line_start..].trim().is_empty() && !line_is_bare_list_marker(&state.output);
    state.list_items_after_text.push(after_text);
    if after_text {
        state.output.push('\n');
        if ordered_index
            .is_some_and(|index| !crate::converter::utility::escaping::line_opens_block(&format!("{index}. x")))
        {
            state.output.push('\n');
        }
    }
    if indent_depth > 0 && (state.output.is_empty() || state.output.ends_with('\n')) {
        push_list_item_indent(&mut state.output, indent_depth);
    }
    if let Some(index) = ordered_index {
        let marker = format!("{index}. ");
        state.list_item_marker_widths.push(marker.len());
        state.output.push_str(&marker);
    } else {
        let bullet_idx = state.ul_depth.saturating_sub(1) as usize % TIER1_BULLETS.len();
        state.list_item_marker_widths.push(2);
        state.output.push(TIER1_BULLETS[bullet_idx] as char);
        state.output.push(' ');
    }
}

fn open_link(state: &mut Tier1State) {
    // ~keep Track link count inside tables for layout-table detection.
    if let Some(ts) = state.table_stack.last_mut() {
        ts.link_count += 1;
    }
    state.cell_or_output_mut().push('[');
}

/// Per-table inputs to Tier-2's layout-table heuristic that `TableState` does not
/// already carry.
///
/// Mirrors the two `TableScan` fields (`block/table/scanner.rs`) that Tier-2's
/// `looks_like_layout` reads in `block/table/builder.rs`:
///
/// ```text
/// looks_like_layout = nested_table_count > 1 || (has_span && has_border_zero)
/// ```
///
/// Both are collected here; `TableState` already tracks everything else `close_table`
/// needs, including `inconsistent_cols` (ragged row lengths), which is no longer part of
/// Tier-2's formula (issue #500) but stays a Tier-1-only bail: a stricter-than-Tier-2 bail
/// is parity-safe since it only ever routes more input to the fallback, and Tier-1 has no
/// need to learn Tier-2's ragged-row padding (issue #13) just to stay in step with it. One
/// entry is pushed by [`open_table`] and popped by [`close_table`], in lockstep with
/// `Tier1State::table_stack`, so `last_mut()` is always the innermost open table.
#[derive(Debug, Clone, Copy, Default)]
struct TableLayoutProbe {
    /// Number of directly-nested `<table>` elements closed inside this table.
    ///
    /// Counts one level only: a table nested inside a nested table increments its
    /// immediate parent, never this frame — matching Tier-2's `scan_own_structure`,
    /// which stops its walk at each nested `<table>` boundary.
    nested_table_count: usize,
    /// True once any cell in this table carried a `colspan`/`rowspan` attribute.
    has_span: bool,
    /// True when the `<table>` tag carried `border="0"` exactly.
    border_zero: bool,
}

fn open_table(state: &mut Tier1State, attrs: &[(&[u8], Option<&[u8]>)], table_probes: &mut Vec<TableLayoutProbe>) {
    // ~keep Phase HH: nested tables are accumulated natively; an inner table inherits
    // `inline_mode = true` so its final GFM rendering writes into the parent
    // cell buffer rather than `state.output`.  The parent cell's newline
    // collapse then flattens the inner table to a single inline run.
    let inline_mode = !state.table_stack.is_empty();
    state.table_stack.push(crate::converter::tier1::state::TableState {
        inline_mode,
        ..Default::default()
    });
    // ~keep Tier-2 compares the raw attribute value against the literal string "0"
    // (`builder.rs`: `b.as_utf8_str() == "0"`), with no trimming and no numeric
    // parse: `border="00"`, `border=" 0"` and a valueless `border` are all NOT
    // border-zero there, so they must not be here either.
    table_probes.push(TableLayoutProbe {
        border_zero: find_attr(attrs, b"border").is_some_and(|value| value == b"0".as_slice()),
        ..TableLayoutProbe::default()
    });
}

fn open_table_caption(state: &mut Tier1State) {
    if let Some(ts) = state.table_stack.last_mut() {
        ts.caption_buf.clear();
        ts.in_caption = true;
    }
}

fn open_table_head(state: &mut Tier1State) -> Result<(), BailReason> {
    if let Some(ts) = state.table_stack.last_mut() {
        if ts.seen_tbody_close || ts.seen_tfoot {
            return Err(BailReason::TableSectionOrder);
        }
        ts.in_thead = true;
    }
    Ok(())
}

fn open_table_body(state: &mut Tier1State) -> Result<(), BailReason> {
    if let Some(ts) = state.table_stack.last_mut() {
        if ts.seen_tfoot {
            return Err(BailReason::TableSectionOrder);
        }
    }
    Ok(())
}

fn open_table_foot(state: &mut Tier1State) {
    if let Some(ts) = state.table_stack.last_mut() {
        ts.seen_tfoot = true;
    }
}

fn open_table_row(state: &mut Tier1State) {
    if let Some(ts) = state.table_stack.last_mut() {
        ts.current_row.clear();
    }
}

fn open_table_cell(
    state: &mut Tier1State,
    attrs: &[(&[u8], Option<&[u8]>)],
    is_header: bool,
    table_probes: &mut [TableLayoutProbe],
) -> Result<(), BailReason> {
    // ~keep Tier-2's `has_span` (block/table/scanner.rs::scan_row_cells) is set by the
    // mere *presence* of a `colspan`/`rowspan` attribute — `attrs.get(k).is_some()`
    // — so `colspan="1"` and a valueless `colspan` both count.  Deliberately NOT
    // `value > 1`: this feeds `looks_like_layout` in close_table and a tighter
    // predicate would leave the byte-equality divergence in place for exactly the
    // tables it excluded.
    let spanning = has_attr(attrs, b"colspan") || has_attr(attrs, b"rowspan");
    if let Some(probe) = table_probes.last_mut() {
        probe.has_span |= spanning;
    }
    // ~keep rowspan: accepted but not expanded (lossy — a spanned cell renders once,
    // matching mdream).  colspan: expanded by `close_table_cell` adding
    // `(colspan - 1)` empty cells so Tier-2's column-count expectations are
    // met (without this, infobox-style `<th colspan="2">` rows trigger Tier-2's
    // layout-table fallback in close_table on what should be a normal GFM table).
    let colspan = find_attr(attrs, b"colspan")
        .and_then(|b| std::str::from_utf8(b).ok())
        .and_then(|s| s.parse::<u16>().ok())
        .unwrap_or(1)
        .max(1);
    if let Some(ts) = state.table_stack.last_mut() {
        ts.current_cell.clear();
        ts.in_cell = true;
        ts.definition_in_cell = false;
        ts.current_cell_colspan = colspan;
        if is_header {
            ts.has_th = true;
        }
    }
    Ok(())
}

/// Emit a void element (no closing tag).
fn emit_void(
    state: &mut Tier1State,
    spec: &'static TagSpec,
    name_lower: &[u8],
    attrs: &[(&[u8], Option<&[u8]>)],
    html: &str,
    options: &ConversionOptions,
) -> Result<(), BailReason> {
    // ~keep A void element closes the "just closed a custom element" boundary
    // window too (see the field's doc comment on `Tier1State`).
    state.last_closed_custom_element = false;
    if name_lower == b"input"
        && attrs.iter().any(|(key, value)| {
            key.eq_ignore_ascii_case(b"type") && value.is_some_and(|v| v.eq_ignore_ascii_case(b"checkbox"))
        })
    {
        // ~keep Tier-2 writes the list item that holds a checkbox as a task item (issue #632).
        if state
            .stack
            .iter()
            .any(|frame| matches!(frame.spec.kind, TagKind::ListItem))
        {
            return Err(BailReason::ListItemCheckbox);
        }
    }
    // ~keep Closes the "just emitted an <img>" window too (see
    // `Tier1State::last_emitted_was_img`); the `TagKind::Image` arm below
    // re-sets it to true after this reset runs.
    state.last_emitted_was_img = false;
    // ~keep A `<br>` ends the line of the text before it: a `'\n'` join still at the end would put
    // ~keep the marker on a line of its own, which cleanup turns into a paragraph break (issue
    // ~keep #683). The join goes before the block check below, which must not see a line end
    // ~keep Tier-2 never wrote (`<canvas>First\n</canvas><br>`).
    if let Some(join_end) = state.pending_newline_join.take() {
        let dest = state.cell_or_output_mut();
        if matches!(spec.kind, TagKind::LineBreak) && join_end == dest.len() {
            dest.pop();
        }
    }
    // ~keep In a cell a line break is a break of its own (issue #645).
    if std::mem::take(&mut state.last_closed_block)
        && is_inline_tag(name_lower)
        && !(state.in_table_cell() && matches!(spec.kind, TagKind::LineBreak))
    {
        separate_inline_after_block(state, options.br_in_tables)?;
    }
    state.last_closed_block = is_block_tag(name_lower);

    match spec.kind {
        TagKind::Hr => {
            if state.in_summary()
                || state.in_table_caption()
                || state.stack.iter().any(|frame| {
                    matches!(
                        frame.spec.kind,
                        TagKind::Strong | TagKind::Emphasis | TagKind::Strikethrough | TagKind::Inserted
                    )
                })
            {
                return Err(BailReason::RuleBetweenInlineMarkers);
            }
            // ~keep Tier-2 starts a rule after an item's content at the item's content column
            // ~keep (issue #583); see `BailReason::ListItemUnsupportedBlockChild`.
            if !state.in_table_cell() && state.list_continuation_indent_width() > 0 && !inside_stray_definition(state) {
                if !line_is_bare_list_marker(&state.output) {
                    return Err(BailReason::ListItemUnsupportedBlockChild);
                }
                // ~keep A rule at the marker is `___` on the marker line, as in Tier-2: `- ---` is
                // ~keep a rule of its own.
                state.output.push_str("___\n");
                return Ok(());
            }
            let in_cell = state.in_table_cell();
            let write_rule = |dest: &mut String| {
                // ~keep Tier-2 trims the space a cell break left before the rule (issue #628).
                if in_cell {
                    crate::converter::main_helpers::trim_trailing_whitespace(dest);
                }
                if !dest.is_empty() && !dest.ends_with("\n\n") {
                    if dest.ends_with('\n') {
                        dest.push('\n');
                    } else {
                        dest.push_str("\n\n");
                    }
                }
                dest.push_str("---\n");
            };
            if in_cell {
                with_cell_scratch(state, write_rule);
            } else {
                write_rule(state.cell_or_output_mut());
            }
        }

        TagKind::LineBreak => {
            // ~keep Three context-dependent emissions:
            //   - Inside a link (anywhere): `"  \n"`, unmodified, UNLESS the link's
            //     body is still empty (nothing emitted since the `<a>`/wrapper
            //     opened), in which case nothing is emitted at all. Tier-2's
            //     `normalize_link_label` (utility/content.rs) now preserves this
            //     exact marker mid-label instead of collapsing it (CommonMark
            //     spec examples 642/643 — a hard break inside link text is legal
            //     and must survive a convert/render/convert round trip), trimming
            //     it away only if it ends up at the label's start/end — a break
            //     with nothing before it has no preceding line to break, so a
            //     leading `<br>` (`<a><br>bar</a>`) must produce `[bar]`, not
            //     `[  \nbar]`. Router (`router.rs`) bails Tier-1 whenever
            //     `newline_style` is not `Spaces`, so this literal is the only
            //     marker Tier-1 ever needs to match. No trim beforehand otherwise,
            //     matching the non-heading branch below and Tier-2's own
            //     `line_break.rs`, which does not trim here either — only the
            //     label's own start/end trimming (in `normalize_link_label` /
            //     `close_link` below) cleans up the ends.
            //   - Inside a table cell (not in a link): mirrors Tier-2's
            //     `emit_table_cell_break` (main_helpers.rs) — trim trailing
            //     spaces/tabs, then emit a literal `<br>` when `br_in_tables`
            //     is true, or collapse to a single space (guarded against a
            //     leading space on an empty cell) otherwise.  `newline_style`
            //     is never consulted inside a cell (issue #453, issue #454).
            //   - Inside a regular block (paragraph, div, etc.): `"  \n"`, with any
            //     trailing whitespace already in the buffer (e.g. a decoded
            //     `&nbsp;` folded to a plain space) trimmed first so the hard-break
            //     prefix is exactly two spaces, not two-plus-N.  Mirrors the
            //     table-cell branch's own `trim_trailing_whitespace` call below.
            // Guarded off when `EscapeCtx::CODE` is set (issue #487): an open code
            // SPAN or BLOCK inside this link must run through the code-aware
            // branches below instead, not this one. Pushing this branch's literal
            // "  \n" straight into a still-open code span's content buffer would
            // land ahead of `close_code`'s segment split, so `content.split('\n')`
            // on "A  \nB" would cut "A  " -- not "A" -- as the first segment, and
            // those two spaces end up trapped inside its closing backtick, wrong
            // regardless of the link. Deferring here still comes out right: the
            // code-span branch pushes the same "  \n" shape OUTSIDE the backticks
            // once `close_code` re-joins the split segments, and `close_link`'s
            // `normalize_link_label` then finds that already-correct marker in the
            // assembled label text exactly as it would for plain (non-code) content.
            let inside_link_frame = !state.escape_ctx.contains(EscapeCtx::CODE)
                && state.stack.iter().any(|frame| matches!(frame.spec.kind, TagKind::Link));
            if inside_link_frame {
                // ~keep #497: emitted even when the link's body is still empty. A leading
                // `<br>` is real content -- `B<a href="H"><br>A</a>` renders as B, a
                // line break, then A -- and `close_link` below, mirroring Tier-2's
                // `normalize_link_label`, is where a break that turns out to have
                // nothing to break away from is dropped again.
                state.cell_or_output_mut().push_str("  \n");
            } else if state.escape_ctx.contains(EscapeCtx::CODE)
                && !state.escape_ctx.contains(EscapeCtx::PRE)
                && state.escape_ctx.contains(EscapeCtx::HEADING)
            {
                // ~keep Mirrors Tier-2's `line_break.rs`: a single-line ATX heading cannot
                // carry a hard break at all, so a code SPAN nested inside one folds
                // straight to a space here rather than reaching `close_code` as a
                // splittable marker -- `close_heading`'s own blind whitespace fold
                // runs AFTER `close_code` has already wrapped the content in
                // backticks, so by then it can only collapse whitespace BETWEEN two
                // already-separate spans, not merge them back into one (issue #487).
                let dest = state.cell_or_output_mut();
                crate::converter::main_helpers::trim_trailing_whitespace(dest);
                dest.push(' ');
            } else if state.escape_ctx.contains(EscapeCtx::PRE) {
                // ~keep A `<pre>` code BLOCK's line structure is real content: push a
                // genuine `\n`, matching Tier-2's `in_code_block` branch. When the
                // `<pre>` is itself inside a table cell, `close_pre` intentionally
                // leaves this newline as-is and defers the cell's own
                // newline-to-space fold to `close_table_cell`, exactly as it already
                // does for every other line ending a `<pre>` accumulates.
                state.cell_or_output_mut().push('\n');
            } else if state.in_table_cell() {
                // ~keep A code SPAN inside a table cell (not caught above, since it is
                // not also inside a heading) lands here too: neither a cell nor a
                // code span can carry a hard break, and this table-cell branch
                // already folds to a single space (or emits nothing under an empty
                // cell) before `close_code` ever sees a splittable byte -- the same
                // "fold before it can split" reasoning as the heading arm above,
                // just via the branch that already existed for ordinary (non-code)
                // cell content. Not a literal `<br>`: that HTML tag is not valid
                // content inside a code span regardless of `br_in_tables`.
                // ~keep Tier-2 writes the space into an inline element's own buffer even when that
                // ~keep buffer is empty; only a break at the start of the cell writes nothing.
                let emit_literal_br = options.br_in_tables && !state.escape_ctx.contains(EscapeCtx::CODE);
                let cell_is_empty = state.cell_or_output_mut().is_empty();
                with_cell_scratch(state, |dest| {
                    crate::converter::main_helpers::trim_trailing_whitespace(dest);
                    if emit_literal_br {
                        dest.push_str("<br>");
                    } else if !cell_is_empty {
                        dest.push(' ');
                    }
                });
            } else if state.escape_ctx.contains(EscapeCtx::CODE) {
                // ~keep A code SPAN otherwise reproduces its content literally but has no
                // interior line structure of its own: `<br>` is a DOM-level split
                // point, not span content. Push a plain '\n' as an internal-only
                // split marker -- `close_code` below splits on it into one backtick
                // span per segment, joined by the "  \n" hard-break marker OUTSIDE
                // the backticks (Tier-1 only ever runs under `NewlineStyle::Spaces`;
                // the router bails to Tier-2 for `Backslash`, so that is the only
                // marker shape this scanner ever needs -- issue #487). This byte can
                // only have come from a real `<br>`: a source text node's own
                // literal line ending is folded to a space before it ever reaches
                // this buffer (`flush_text`'s `in_code && !in_pre` branch).
                state.cell_or_output_mut().push('\n');
            } else {
                // ~keep Also a `<br>` that no element encloses (`a<br>b`): Tier-2 writes the
                // same marker there as inside `<body>`, so the top level is not a case of its own.
                let dest = state.cell_or_output_mut();
                crate::converter::main_helpers::trim_trailing_whitespace(dest);
                dest.push_str("  \n");
            }
        }

        TagKind::Image => {
            let src = find_attr(attrs, b"src").unwrap_or_default();

            // ~keep Tier-2's `handle_img` (`handlers/image.rs`'s `resolve_effective_src`,
            // landed in commit 55699777d5, after this scanner's pinned baseline) falls
            // back to `data-src` / `data-lazy-src` / `data-original` / `data-srcset` /
            // `srcset` -- in that precedence order -- whenever `src` is empty/whitespace
            // or a `data:` URI (the standard lazy-loading placeholder pattern: the real
            // image URL sits in a `data-*` attribute until the element scrolls into
            // view). See `BailReason::ImageLazyLoadSrc`'s doc comment for why this bails
            // rather than reimplementing that precedence (including `srcset`'s
            // width/density-descriptor comparison) here. A plain `<img src="x.png">`
            // with none of the fallback attributes is unaffected and stays on this path.
            let src_is_lazy_load_placeholder = {
                let trimmed = src.trim_ascii();
                trimmed.is_empty()
                    || trimmed
                        .get(..5)
                        .is_some_and(|scheme| scheme.eq_ignore_ascii_case(b"data:"))
            };
            if src_is_lazy_load_placeholder
                && [
                    b"data-src".as_slice(),
                    b"data-lazy-src".as_slice(),
                    b"data-original".as_slice(),
                    b"data-srcset".as_slice(),
                    b"srcset".as_slice(),
                ]
                .iter()
                .any(|name| find_attr(attrs, name).is_some())
            {
                return Err(BailReason::ImageLazyLoadSrc);
            }

            let alt = find_attr(attrs, b"alt").unwrap_or_default();
            let title = find_attr(attrs, b"title");

            let src = decode_attr(src)?;
            let src = state.resolve_url(&src).unwrap_or(src);
            // ~keep Tier-2 decodes every user-visible attribute (issue #494), so its answer no
            // longer depends on whether html5ever repaired the document: `&#x22;`,
            // `&quot;` and a literal `"` all converge on `"`. The canonicalize/bail fork
            // that stood here existed only to mirror that dependency, and with it gone
            // Tier-1 both matches Tier-2 and stops bailing on entity-bearing attributes.
            let alt_owned = decode_attr(alt)?;
            let alt: &str = &alt_owned;

            let keep_as_markdown = should_keep_image_as_markdown(html, &state.stack, options);

            let dest = state.cell_or_output_mut();
            if keep_as_markdown {
                // ~keep Security fix mirror (`handlers/image.rs::format_image_markdown`,
                // outside tier1/ — same class of bug as the SVG title / link label
                // fixes above): an unescaped `alt` lets `x](https://evil.example`
                // close the image label early and open a second,
                // attacker-controlled Markdown image/link. Only applied on this
                // (markdown-emitting) branch — the `!keep_as_markdown` branch below
                // emits `alt` as plain text with no `![...]` wrapping at all,
                // matching `format_image_markdown`'s `use_alt_only` branch, which
                // also does not call `escape_link_label`.
                let escaped_alt = crate::converter::utility::escaping::escape_link_label(alt);
                if let Some(title_bytes) = title {
                    // ~keep Escaped exactly as Tier-2's `handlers/image.rs` does. Before
                    // issue #494 this path could not produce a raw `"` -- the entity
                    // survived undecoded -- so the missing escape was invisible. Full
                    // decoding surfaces it: `title="&#x22;t&#x22;"` emitted `""t""`,
                    // which closes the title early and is not the document's text.
                    let decoded_title = decode_attr(title_bytes)?;
                    let title_owned =
                        crate::converter::inline::link::escape_markdown_title(&decoded_title).into_owned();
                    let title_str: &str = &title_owned;
                    // ~keep Destination written by Tier-2's own `append_url_destination`
                    // rather than interpolated, so the two tiers cannot drift on
                    // `(`/`)` escaping or the angle-bracket wrapping a whitespace-
                    // bearing URL needs. Decoding (#494) made both reachable from an
                    // entity, and a swept parity check found all four spellings
                    // diverging here.
                    dest.push_str("![");
                    dest.push_str(&escaped_alt);
                    dest.push_str("](");
                    crate::converter::inline::link::append_url_destination(dest, &src, options.url_escape_style, true);
                    dest.push_str(" \"");
                    dest.push_str(title_str);
                    dest.push_str("\")");
                } else {
                    dest.push_str("![");
                    dest.push_str(&escaped_alt);
                    dest.push_str("](");
                    crate::converter::inline::link::append_url_destination(dest, &src, options.url_escape_style, false);
                    dest.push(')');
                }
            } else {
                // ~keep Strip to alt-text only — mirrors Tier-2 behaviour when the image
                // is in a heading whose tag is not in `keep_inline_images_in`.
                dest.push_str(alt);
            }
            // ~keep Set regardless of `keep_as_markdown` — Tier-2's `is_empty_inline_element`
            // (paragraph.rs) checks the DOM tag name only, not how it renders.
            state.last_emitted_was_img = true;
        }

        TagKind::Ignored | TagKind::Inline | TagKind::Block => {}

        _ => {}
    }
    Ok(())
}

/// Decide whether an `<img>` should be emitted as `![alt](src)` markdown.
///
/// When the `inline-images` feature is disabled, images are always kept as
/// markdown (original Tier-1 behaviour).
///
/// When the feature is enabled this mirrors the Tier-2 logic in
/// `converter.rs`:
/// - `keep_inline_images_in` empty → always emit markdown image.
/// - `keep_inline_images_in` non-empty → emit markdown when the nearest
///   heading or link ancestor (`h1`–`h6`, or `a`, whichever is closer to the
///   `<img>`) has a (lowercased) tag name in the list, walking outward past a
///   non-matching link to a heading further out (#492); otherwise emit
///   alt-text only.
///
/// Ancestor matching is ASCII-case-insensitive so callers may supply "H1" or
/// "h1" interchangeably.
#[inline]
#[allow(clippy::missing_const_for_fn)]
fn should_keep_image_as_markdown(html: &str, stack: &[OpenTag], options: &ConversionOptions) -> bool {
    #[cfg(feature = "inline-images")]
    {
        keep_inline_image_for_ancestors(html.as_bytes(), stack, &options.keep_inline_images_in)
    }
    #[cfg(not(feature = "inline-images"))]
    {
        let _ = html;
        let _ = stack;
        let _ = options;
        true
    }
}

/// Return `true` when the `<img>` should be emitted as `![alt](src)` markdown.
///
/// Mirrors the Tier-2 logic in `converter.rs`: images are kept as markdown
/// unconditionally when `keep_inline_images_in` is empty.  When the list is
/// non-empty, the nearest heading OR link ancestor decides: if it is a link
/// (`<a>`) whose tag name is in the list, the image is kept regardless of any
/// heading further out (#492, mirroring `ctx.link_allow_inline_images` in
/// `handlers/link.rs`); if it is a link NOT in the list, that link imposes no
/// restriction of its own and the scan continues outward to the next heading
/// or link ancestor; if it is a heading, that heading's own list membership
/// decides and the scan stops there, matching the pre-#492 rule.
///
/// The comparison is ASCII-case-insensitive on both the stack name bytes and the
/// user-supplied strings, so callers may supply "H1" or "h1" interchangeably.
#[cfg(feature = "inline-images")]
fn keep_inline_image_for_ancestors(input: &[u8], stack: &[OpenTag], keep: &[String]) -> bool {
    // ~keep No `keep.is_empty()` short-circuit. One stood here returning `true`, described as
    // "the Tier-2 default", but Tier-2 strips an image in a heading to its alt text
    // exactly when the list does not name that heading -- and an empty list names
    // nothing. Falling through handles both cases correctly: the heading branch's inner
    // loop matches nothing and returns `false`, and a document with no heading ancestor
    // still reaches the `true` at the end. Unreachable until issue #494 removed the
    // entity bail that had been sending these documents to Tier 2 anyway.
    for frame in stack.iter().rev() {
        if matches!(frame.spec.kind, TagKind::Heading(_)) {
            let name = &input[frame.name_range.clone()];
            for keep_name in keep {
                if eq_ascii_ignore_case(name, keep_name.as_bytes()) {
                    return true;
                }
            }
            return false;
        }
        // ~keep #492: a link ancestor whose tag name is in the keep list keeps the image as
        // markdown outright (mirrors `ctx.link_allow_inline_images` in Tier-2, which is
        // OR'd into `keep_as_markdown` independent of any heading). A non-matching link
        // imposes no restriction of its own -- unlike a heading, it does not stop the
        // scan -- so a heading further out still gets to decide. A link frame OUTSIDE a
        // heading frame is unreachable here: `<a>…<h1>` (heading opening inside a link)
        // already bails to Tier-2 before this scanner runs (scanner.rs:1111-1128), so
        // any `Link` frame this loop sees is nested INSIDE whichever `Heading` frame, if
        // any, sits further down this same stack.
        if matches!(frame.spec.kind, TagKind::Link) {
            let name = &input[frame.name_range.clone()];
            if keep
                .iter()
                .any(|keep_name| eq_ascii_ignore_case(name, keep_name.as_bytes()))
            {
                return true;
            }
        }
    }
    // ~keep No heading or matching-link ancestor at all: no restriction applies — emit
    // markdown image.
    // This matches Tier-2 behaviour: the `keep_inline_images_in` guard only
    // fires when `ctx.in_heading` is true.
    true
}

/// Byte-level ASCII case-insensitive comparison — no allocation.
#[cfg(feature = "inline-images")]
fn eq_ascii_ignore_case(a: &[u8], b: &[u8]) -> bool {
    a.eq_ignore_ascii_case(b)
}

/// Returns `true` when `bytes[pos..]` opens a `<script` or `<style` tag with no
/// separating whitespace — i.e. a second raw-text-ignored element sitting directly
/// adjacent to the one the scanner just finished skipping.  See the bail site in
/// the `TagKind::Ignored`-and-`is_rawtext` branch above for why this forces a
/// Tier-2 fallback rather than being handled inline.
fn is_adjacent_rawtext_ignored_open(bytes: &[u8], pos: usize) -> bool {
    const CANDIDATES: [&[u8]; 2] = [b"script", b"style"];
    if bytes.get(pos) != Some(&b'<') {
        return false;
    }
    let name_start = pos + 1;
    for name in CANDIDATES {
        let name_end = name_start + name.len();
        if bytes.len() < name_end {
            continue;
        }
        if !bytes[name_start..name_end].eq_ignore_ascii_case(name) {
            continue;
        }
        // ~keep Require a valid tag-name terminator so `<scriptx>` doesn't match.
        if let Some(b' ' | b'\t' | b'\n' | b'\r' | b'>' | b'/') = bytes.get(name_end) {
            return true;
        }
    }
    false
}

fn emit_close(
    state: &mut Tier1State,
    tag_name_bytes: &[u8],
    options: &ConversionOptions,
    table_probes: &mut Vec<TableLayoutProbe>,
) -> Result<(), BailReason> {
    let mut name_buf = [0u8; MAX_TAG_NAME_BYTES];
    let name_lower = lowercase_into(tag_name_bytes, &mut name_buf);

    // ~keep Custom element close tags (e.g. `</x-foo>`) use the same static Inline
    // spec as their corresponding open tag.  All other unknown close tags bail.
    let spec: &'static TagSpec = if name_lower.contains(&b'-') {
        &CUSTOM_ELEMENT_INLINE_SPEC
    } else {
        match tier1::lookup(name_lower) {
            Some(s) => s,
            None => {
                return Err(BailReason::UnknownCustomElement {
                    name: bytes_to_string(tag_name_bytes).into(),
                    offset: 0,
                });
            }
        }
    };

    // ~keep Closing any tag ends the "just emitted an <img>" window too (see
    // `Tier1State::last_emitted_was_img`) — an intervening close means the
    // two images are not both unwrapped direct siblings any more.
    state.last_emitted_was_img = false;

    while let Some(top) = state.stack.last() {
        if kinds_match(&top.spec.kind, &spec.kind) {
            break;
        }
        if top.spec.optional_close.is_some() {
            emit_close_for_implicit(state, options, table_probes)?;
        } else {
            break;
        }
    }

    // ~keep Pop the matching frame from the open-tag stack.
    // Tier-2 is lenient about mismatched tags; for M3c we bail.
    let actual_depth = state.stack.len() as u8;
    let frame = pop_matching_frame(&mut state.stack, spec).ok_or_else(|| BailReason::DepthMismatch {
        tag: bytes_to_string(name_lower),
        expected: 1,
        actual: actual_depth,
    })?;

    state.escape_ctx = frame.prev_escape_ctx;
    state.last_closed_custom_element = std::ptr::eq(spec, &raw const CUSTOM_ELEMENT_INLINE_SPEC);
    if matches!(spec.kind, TagKind::DefinitionTerm | TagKind::DefinitionDescription) {
        trim_start_of_cell_content(state, frame.content_start)?;
    }
    check_whitespace_led_block_in_cell(state, &frame)?;

    match spec.kind {
        TagKind::Paragraph => close_paragraph(state),
        TagKind::Heading(n) => close_heading(state, &frame, n, false, options)?,
        TagKind::Blockquote => close_blockquote(state, &frame, options.br_in_tables),
        TagKind::Pre => close_pre(state, &frame, options),
        // ~keep Strong: suppress close marker when inside summary, or when this
        // frame nested inside another `<strong>` and so never emitted an
        // open marker either (see open-side guard) — `state.escape_ctx` was
        // just restored to `frame.prev_escape_ctx` above.
        TagKind::Strong
            if state.summary_at_top()
                || state.escape_ctx.contains(EscapeCtx::STRONG)
                || state.escape_ctx.contains(EscapeCtx::CODE)
                || state.escape_ctx.contains(EscapeCtx::PRE) => {}
        TagKind::Strong => close_inline_marker(state, &frame, "**")?,
        TagKind::Emphasis
            if state.escape_ctx.contains(EscapeCtx::CODE) || state.escape_ctx.contains(EscapeCtx::PRE) => {}
        TagKind::Emphasis => close_inline_marker(state, &frame, "*")?,
        TagKind::Strikethrough
            if state.escape_ctx.contains(EscapeCtx::CODE) || state.escape_ctx.contains(EscapeCtx::PRE) => {}
        TagKind::Strikethrough => close_inline_marker(state, &frame, "~~")?,
        TagKind::Inserted
            if state.escape_ctx.contains(EscapeCtx::CODE) || state.escape_ctx.contains(EscapeCtx::PRE) => {}
        TagKind::Inserted => close_inline_marker(state, &frame, "==")?,
        TagKind::Code => close_code(state, &frame)?,
        TagKind::Link => close_link(state, &frame, options)?,
        TagKind::List(ListKind::Definition) => close_dl(state, &frame),
        TagKind::List(kind) => close_list(state, kind),
        TagKind::ListItem => close_list_item(state, &frame)?,
        TagKind::DefinitionTerm => close_dt(state),
        TagKind::DefinitionDescription => close_dd(state),
        TagKind::Hr => {}
        TagKind::Table => close_table(state, options, table_probes)?,
        TagKind::TableHead => close_table_head(state),
        TagKind::TableBody => close_table_body(state),
        TagKind::TableFoot => {}
        TagKind::TableRow => close_table_row(state),
        TagKind::TableCell { .. } => close_table_cell(state, false)?,
        TagKind::TableCaption => close_table_caption(state),
        // ~keep Generic block container close: when it produced visible content,
        // ensure a paragraph-break separator follows so the next sibling
        // doesn't run together with this div's last byte.  Mirrors Tier-2's
        // `div::handle` post-children block: `output.push_str("\n\n")` when
        // `has_content` (see block/div.rs around line 124-130).
        TagKind::Block => close_block_container(state, &frame, name_lower),
        // ~keep Summary: pop accumulation buffer, trim, emit `**…**\n\n` (Phase R).
        TagKind::Summary => close_summary(state, &frame),
        // ~keep Figcaption: pop accumulation buffer, trim, emit `*…*\n\n` (Phase FF-2).
        TagKind::Figcaption => close_figcaption(state, &frame),
        // ~keep Button (Phase T): emit `\n\n` when content was produced — mirrors
        // Tier-2 `form/elements.rs`'s `handle_button`.  No leading separator on open.
        TagKind::Button => close_button(state, &frame),
        TagKind::Inline => {
            if name_lower == b"abbr" {
                if let Some(Some(title)) = state.abbr_titles.pop() {
                    let dest = state.cell_or_output_mut();
                    dest.push_str(" (");
                    dest.push_str(&title);
                    dest.push(')');
                }
            }
        }
        TagKind::LineBreak | TagKind::Image => {}
        TagKind::RawText(_) | TagKind::Ignored => {}
    }
    // ~keep An inline element whose last content is a block ends in that block too (issue #585).
    // ~keep In a cell Tier-2 writes no break after a nested table (see `separate_from_block`).
    let breaks_after = is_block_tag(name_lower) && !(matches!(spec.kind, TagKind::Table) && state.in_table_cell());
    state.last_closed_block = breaks_after || (state.last_closed_block && is_inline_tag(name_lower));

    Ok(())
}

/// Append a paragraph-break separator after a generic block container close
/// (`<div>`, `<section>`, etc.) when it produced visible content.
///
/// Without this Tier-1 emits adjacent block content with no separator
/// (e.g. `[image-link](href)EN` instead of `[image-link](href)\n\nEN`),
/// diverging from Tier-2 which always emits `\n\n` after a block-with-content
/// close (see Tier-2 `block/div.rs`).  Skipped inside table cells and inline
/// contexts where the surrounding code already handles spacing.
fn close_block_container(state: &mut Tier1State, frame: &OpenTag, name_lower: &[u8]) {
    if block_container_is_passthrough(name_lower) {
        // ~keep Mirrors the open-side skip in `emit_open`'s `TagKind::Block` arm:
        // Tier-2's catch-all handler for these names never emits a trailing
        // separator either.
        return;
    }
    if state.in_table_cell() {
        return;
    }
    let buf = state.cell_or_output_mut();
    if buf.len() <= frame.content_start {
        return;
    }
    // ~keep Drop trailing horizontal whitespace (left over from inter-tag whitespace
    // preservation) before emitting the block separator.  Same rationale as
    // `ensure_blank_line` (Phase U-2).
    while buf.ends_with(' ') || buf.ends_with('\t') {
        buf.pop();
    }
    if buf.ends_with("\n\n") {
        return;
    }
    if buf.ends_with('\n') {
        buf.push('\n');
    } else {
        buf.push_str("\n\n");
    }
}

// ~keep ── Summary strong-wrap (Phase R) ────────────────────────────────────────────

/// Open a `<summary>` element.
///
/// Push a fresh accumulation buffer so all child text collects here instead
/// of in the outer destination (main output, table cell, or caption).
/// The summary buffer has the highest priority in `cell_or_output_mut`, so
/// even when inside a table cell the children write to this buffer rather
/// than the cell buffer.  This matches Tier-2's `handle_summary` which
/// always processes children into a local `content` buffer then wraps with
/// `**…**\n\n` before writing to the outer output.
///
/// No leading separator is emitted on open; deferred to `close_summary`
/// once we know whether the content is non-empty.
fn open_summary(state: &mut Tier1State) {
    state.push_summary_buf(crate::converter::tier1::state::WrapKind::Summary);
}

/// Close a `<summary>` element.
///
/// Pops the accumulation buffer (if any), trims it, and emits
/// `**{trimmed}**\n\n` into the parent destination (main output, an outer
/// summary buffer, a table cell, or a caption).
///
/// Mirrors Tier-2's `handle_summary` (semantic/summary.rs:138–249):
/// - collect children with `in_strong: true` (block children render inline)
/// - trim
/// - emit `**…**\n\n`
fn close_summary(state: &mut Tier1State, _frame: &OpenTag) {
    // ~keep Pop the buffer we pushed in open_summary.
    let buf = match state.pop_summary_buf() {
        Some(b) => b,
        None => return,
    };
    let trimmed = buf.trim();
    if trimmed.is_empty() {
        return;
    }
    // ~keep Acquire the parent destination.  Because we already popped the buffer
    // above, cell_or_output_mut now returns the next-outer target — which may
    // be the table cell buffer (when the summary was inside a <td>), an outer
    // summary buffer, or the main output.
    // ~keep
    // ~keep Check whether we're emitting into a table cell BEFORE borrowing `dest`,
    // so we can decide whether to add a leading separator without conflicting
    // with the mutable borrow.
    let writing_to_cell = state.in_table_cell();
    let dest = state.cell_or_output_mut();
    // ~keep Ensure a blank-line separator before the summary block when there is
    // preceding content and we're NOT writing to a table cell (cells are
    // rendered to a single line; block separators would be collapsed anyway).
    if !writing_to_cell && !dest.is_empty() && !dest.ends_with("\n\n") {
        if dest.ends_with('\n') {
            dest.push('\n');
        } else {
            dest.push_str("\n\n");
        }
    }
    dest.push_str("**");
    dest.push_str(trimmed);
    dest.push_str("**\n\n");
}

// ~keep ── Figcaption italic-wrap (Phase FF-2) ──────────────────────────────────────

/// Open a `<figcaption>` element.
///
/// Reuses the summary accumulation buffer stack — children write into it,
/// `close_figcaption` pops + wraps with `*…*\n\n` (vs Summary's `**…**`).
fn open_figcaption(state: &mut Tier1State) {
    state.push_summary_buf(crate::converter::tier1::state::WrapKind::Figcaption);
}

/// Close a `<figcaption>` element.
///
/// Mirrors Tier-2's `semantic/figure.rs::handle_figcaption`:
/// - collect children into a local buffer
/// - trim
/// - prepend single-space-or-blank-line separator
/// - emit `*{trimmed}*\n\n`
///
/// An empty/whitespace-only caption emits nothing (Tier-2 returns early).
fn close_figcaption(state: &mut Tier1State, _frame: &OpenTag) {
    let buf = match state.pop_summary_buf() {
        Some(b) => b,
        None => return,
    };
    let trimmed = buf.trim();
    if trimmed.is_empty() {
        return;
    }
    let writing_to_cell = state.in_table_cell();
    let dest = state.cell_or_output_mut();
    // ~keep Phase FF-2: trim trailing horizontal whitespace introduced by
    // Phase U-2's inter-tag-whitespace preservation, so the block
    // separator (\n\n) doesn't sit after a stray space.  Tier-2 does
    // not emit that space when the figcaption follows inline content.
    while dest.ends_with(' ') || dest.ends_with('\t') {
        dest.pop();
    }
    if !writing_to_cell && !dest.is_empty() && !dest.ends_with("\n\n") {
        if dest.ends_with('\n') {
            dest.push('\n');
        } else {
            dest.push_str("\n\n");
        }
    }
    dest.push('*');
    dest.push_str(trimmed);
    dest.push_str("*\n\n");
}

/// Close a `<button>` (Phase T).  When the button produced visible content,
/// emit `\n\n` after.  Skipped in table cells (cells stay one logical line).
///
/// Mirrors the block-separator tail of Tier-2 `form/elements.rs`'s `handle_button`:
/// ```text
/// if !ctx.convert_as_inline && output.len() > start_len {
///     output.push_str("\n\n");
/// }
/// ```
fn close_button(state: &mut Tier1State, frame: &OpenTag) {
    if state.in_table_cell() {
        return;
    }
    let dest = state.cell_or_output_mut();
    if dest.len() <= frame.content_start {
        return;
    }
    // ~keep Drop trailing horizontal whitespace from the inter-tag fix before the
    // block separator (Phase U-2).
    while dest.ends_with(' ') || dest.ends_with('\t') {
        dest.pop();
    }
    if dest.ends_with("\n\n") {
        return;
    }
    if dest.ends_with('\n') {
        dest.push('\n');
    } else {
        dest.push_str("\n\n");
    }
}

/// Clamp a stored byte offset (e.g. `OpenTag::content_start`, captured as
/// `buf.len()` when the tag opened) to a valid, in-bounds char boundary of
/// `buf` as it stands *now*.
///
/// `content_start` is read back at close time, sometimes against a different
/// buffer than the one it was captured against (`state.output` vs. the
/// current table-cell accumulator — see the `state.in_table_cell()` branches
/// throughout this file) or after other frames' close handlers have mutated
/// the buffer. On the correct path `content_start` is already valid, so this
/// is a no-op there (500k-case fuzzing under `TierStrategy::Auto` never hit a
/// clamp); it exists so a stale offset degrades to a clamped position instead
/// of an out-of-bounds or not-a-char-boundary panic in `&buf[start..]`,
/// `buf.truncate(start)`, or `buf.insert_str(start, …)`.
fn clamp_to_char_boundary(buf: &str, at: usize) -> usize {
    let mut at = at.min(buf.len());
    while at > 0 && !buf.is_char_boundary(at) {
        at -= 1;
    }
    at
}

/// Close an inline emphasis-style element (`<strong>`, `<em>`, `<b>`, `<i>`).
///
/// When the element produced no visible content (the source had `<strong></strong>`
/// or `<i>   </i>`), erase the open marker too instead of emitting an empty
/// `**` / `*` pair.  Tier-2's DOM walker reaches the same result by emitting
/// nothing for an empty inline node; the byte-equality oracle requires us to
/// match that.
fn close_inline_marker(state: &mut Tier1State, frame: &OpenTag, marker: &str) -> Result<(), BailReason> {
    let buf = state.cell_or_output_mut();
    let content_start = clamp_to_char_boundary(buf, frame.content_start);
    let content_is_absent = buf.len() <= content_start;
    let is_whitespace_only_not_empty = !content_is_absent
        && buf[content_start..]
            .bytes()
            .all(|b| matches!(b, b' ' | b'\t' | b'\n' | b'\r'));
    let body_is_empty = content_is_absent || is_whitespace_only_not_empty;
    if body_is_empty {
        // ~keep issue #481: a body that is (or, per `dropped_whitespace_only_text`, WAS
        // before `flush_text` dropped it) non-empty but entirely whitespace (e.g.
        // `<i> </i>`) is not the same as a genuinely empty one (`<i></i>`) --
        // Tier-2's `chomp_inline` preserves it as a single space OUTSIDE the
        // markers, while erasing the markers here (as the genuinely-empty case
        // correctly does) would silently drop that space. Only bail for
        // every marker this function serves: Strikethrough (`~~`) and Inserted (`==`)
        // now go through Tier-2's shared `emit_wrapped_inline`, which preserves that
        // separator exactly as strong/emphasis do, so they are no longer exempt.
        let was_whitespace_only =
            is_whitespace_only_not_empty || (content_is_absent && frame.dropped_whitespace_only_text);
        if was_whitespace_only && matches!(marker, "**" | "*" | "~~" | "==") {
            return Err(BailReason::WhitespaceOnlyInlineEmphasis);
        }
        let open_marker_start = clamp_to_char_boundary(buf, content_start.saturating_sub(marker.len()));
        buf.truncate(open_marker_start);
        return Ok(());
    }

    // ~keep Mirror Tier-2's `chomp_inline` (utility/content.rs:31): leading/trailing
    // whitespace (including Unicode whitespace like NBSP `\u{a0}`) inside the
    // strong/emphasis markers gets pushed OUTSIDE them so `**\u{a0}X**` becomes
    // `\u{a0}**X**`.  Required for byte-equality on Wikipedia fixtures with
    // `<b><span>&nbsp;</span>X</b>` patterns.
    let content_str = &buf[content_start..];
    let leading_len = content_str.len() - content_str.trim_start().len();
    // ~keep `content_start` is re-bound (not just conditionally mutated in place)
    // because the trailing check below indexes `buf` at this offset again:
    // moving `leading_len` bytes from right after the open marker to right
    // before it shifts every later byte's position forward by `leading_len`
    // without changing the buffer's total length, so the ORIGINAL
    // `content_start` value no longer points at the start of the real
    // content — it now lands `marker.len()` bytes into whatever sits at
    // the old marker position, which is a char boundary only by
    // coincidence. Reusing the stale value panicked
    // ("byte index is not a char boundary") on `<em>\u{2003}x</em>`-shaped
    // input, where the 1-byte `*` marker and the 3-byte migrated space
    // don't line up.
    let content_start = if leading_len > 0 {
        let leading: String = content_str[..leading_len].to_owned();
        buf.replace_range(content_start..content_start + leading_len, "");
        let marker_start = clamp_to_char_boundary(buf, content_start.saturating_sub(marker.len()));
        buf.insert_str(marker_start, &leading);
        content_start + leading_len
    } else {
        content_start
    };

    // ~keep Trailing counterpart of the leading-whitespace migration above: a
    // trailing whitespace run (e.g. a decoded `&nbsp;` folded to a plain
    // space) is pushed OUTSIDE the closing marker instead of staying
    // inside it, matching Tier-2's `chomp_inline` suffix handling.
    let content_str = &buf[content_start..];
    let trailing_len = content_str.len() - content_str.trim_end().len();
    if trailing_len > 0 {
        let trailing_start = buf.len() - trailing_len;
        let trailing: String = buf[trailing_start..].to_owned();
        buf.truncate(trailing_start);
        buf.push_str(marker);
        buf.push_str(&trailing);
        return Ok(());
    }

    buf.push_str(marker);
    Ok(())
}

/// Implicitly close the top-of-stack frame without a matching `</tag>` in the
/// input.  Called by the M4 implicit-close loop when HTML5 optional-tag rules
/// require an open element to be closed before the next tag is pushed.
///
/// Mirrors `emit_close` but skips the stack-pop search (we always close the
/// literal top frame) and skips the tag-name lookup (we use the frame's spec
/// directly).
fn emit_close_for_implicit(
    state: &mut Tier1State,
    options: &ConversionOptions,
    table_probes: &mut Vec<TableLayoutProbe>,
) -> Result<(), BailReason> {
    let frame = state.stack.pop().ok_or_else(|| BailReason::DepthMismatch {
        tag: String::from("(implicit)"),
        expected: 1,
        actual: 0,
    })?;
    let spec = frame.spec;

    state.escape_ctx = frame.prev_escape_ctx;
    state.last_closed_custom_element = std::ptr::eq(spec, &raw const CUSTOM_ELEMENT_INLINE_SPEC);

    match spec.kind {
        TagKind::Paragraph => close_paragraph(state),
        TagKind::Heading(n) => close_heading(state, &frame, n, true, options)?,
        TagKind::Blockquote => close_blockquote(state, &frame, options.br_in_tables),
        TagKind::Pre => close_pre(state, &frame, options),
        // ~keep Strong: suppress close marker when inside summary, or when this
        // frame nested inside another `<strong>` and so never emitted an
        // open marker either (see open-side guard) — `state.escape_ctx` was
        // just restored to `frame.prev_escape_ctx` above.
        TagKind::Strong
            if state.summary_at_top()
                || state.escape_ctx.contains(EscapeCtx::STRONG)
                || state.escape_ctx.contains(EscapeCtx::CODE)
                || state.escape_ctx.contains(EscapeCtx::PRE) => {}
        TagKind::Strong => close_inline_marker(state, &frame, "**")?,
        TagKind::Emphasis
            if state.escape_ctx.contains(EscapeCtx::CODE) || state.escape_ctx.contains(EscapeCtx::PRE) => {}
        TagKind::Emphasis => close_inline_marker(state, &frame, "*")?,
        TagKind::Strikethrough
            if state.escape_ctx.contains(EscapeCtx::CODE) || state.escape_ctx.contains(EscapeCtx::PRE) => {}
        TagKind::Strikethrough => close_inline_marker(state, &frame, "~~")?,
        TagKind::Inserted
            if state.escape_ctx.contains(EscapeCtx::CODE) || state.escape_ctx.contains(EscapeCtx::PRE) => {}
        TagKind::Inserted => close_inline_marker(state, &frame, "==")?,
        TagKind::Code => close_code(state, &frame)?,
        TagKind::Link => close_link(state, &frame, options)?,
        TagKind::List(ListKind::Definition) => close_dl(state, &frame),
        TagKind::List(kind) => close_list(state, kind),
        TagKind::ListItem => close_list_item(state, &frame)?,
        TagKind::DefinitionTerm => close_dt(state),
        TagKind::DefinitionDescription => close_dd(state),
        TagKind::TableCell { .. } => close_table_cell(state, true)?,
        TagKind::TableRow => close_table_row(state),
        // ~keep Summary: pop accumulation buffer, trim, emit `**…**\n\n` (Phase R).
        TagKind::Summary => close_summary(state, &frame),
        // ~keep Figcaption: pop accumulation buffer, trim, emit `*…*\n\n` (Phase FF-2).
        TagKind::Figcaption => close_figcaption(state, &frame),
        // ~keep Button (Phase T): emit `\n\n` on EOF close just like explicit close.
        TagKind::Button => close_button(state, &frame),
        // ~keep An unclosed `<table>` at EOF (html5ever/tl both implicitly close every
        // open element there, per the loop's own doc comment) used to hit the
        // do-nothing arm below, discarding the WHOLE accumulated table --
        // including fully-formed rows -- instead of rendering it. `close_table`
        // already tolerates an incomplete/empty table (its `is_blank` check
        // bails rather than emitting), so it is exactly as safe to call here as
        // it is from `emit_close`'s explicit `</table>` arm.
        TagKind::Table => close_table(state, options, table_probes)?,
        TagKind::Block | TagKind::Inline => {}
        TagKind::LineBreak
        | TagKind::Image
        | TagKind::Hr
        | TagKind::TableHead
        | TagKind::TableBody
        | TagKind::TableFoot
        | TagKind::TableCaption
        | TagKind::RawText(_)
        | TagKind::Ignored => {}
    }

    Ok(())
}

fn close_paragraph(state: &mut Tier1State) {
    // ~keep When inside a table cell, `<p>` is transparent — no block separators.
    // Any inter-paragraph separators were already added as `<br>` at open time
    // by `open_paragraph`; `close_paragraph` does nothing in this context.
    if state.in_table_cell() {
        return;
    }
    // ~keep Tier-2 appends "\n\n" after paragraph content (always two newlines).
    // Matching this precisely is required for byte-equal output.
    trim_trailing_inline_whitespace(state);
    state.cell_or_output_mut().push_str("\n\n");
}

/// Close a heading element.
///
/// When `is_implicit` is true the empty-heading guard is skipped: implicitly
/// closed headings have already had their content flushed through the normal
/// path, so we just prepend the prefix unconditionally.
fn close_heading(
    state: &mut Tier1State,
    frame: &OpenTag,
    n: u8,
    is_implicit: bool,
    options: &ConversionOptions,
) -> Result<(), BailReason> {
    // ~keep When inside a table cell, Tier-2 emits the heading text directly into
    // the cell accumulator — no `#` prefix, no block separators.  The
    // `frame.content_start` is a position in the CELL buffer (set by
    // `cell_or_output_mut().len()` at emit_open time), so all position
    // arithmetic must use the cell buffer, not `state.output`.
    if state.in_table_cell() {
        let cell_buf = state.cell_or_output_mut();
        // ~keep Only the heading's own trailing whitespace: a cell break before it stays.
        while cell_buf.len() > frame.content_start && (cell_buf.ends_with(' ') || cell_buf.ends_with('\t')) {
            cell_buf.pop();
        }
        if !is_implicit {
            let cell_buf = state.cell_or_output_mut();
            let content_start = clamp_to_char_boundary(cell_buf, frame.content_start);
            let content = &cell_buf[content_start..];
            if content.trim().is_empty() {
                state.cell_or_output_mut().truncate(content_start);
            }
        }
        separate_closed_block_in_cell(state, frame.content_start, options.br_in_tables);
        return Ok(());
    }

    trim_trailing_inline_whitespace(state);
    // ~keep All buffer touches below go through `cell_or_output_mut` rather than
    // `state.output` directly. A heading inside `<summary>`/`<figcaption>`
    // is not a table cell (the early return above doesn't catch it) but its
    // `frame.content_start` was captured from the active wrap buffer's
    // length (see the open-tag push site), not `state.output`'s — using
    // `state.output` here would insert the `#` prefix at that same small
    // offset into the real, much longer document output instead, splicing
    // it into the middle of unrelated already-emitted text. See
    // `open_heading`'s matching note.
    let buf = state.cell_or_output_mut();
    let content_start = clamp_to_char_boundary(buf, frame.content_start);

    if !is_implicit {
        let content = &buf[content_start..];
        if content.trim().is_empty() {
            // ~keep Empty heading: Tier-2 emits nothing. Roll back to before
            // the heading's block separator was added.
            buf.truncate(content_start);
            let trimmed_len = buf.trim_end_matches('\n').len();
            if trimmed_len > 0 {
                buf.truncate(trimmed_len);
                buf.push('\n');
            } else {
                buf.clear();
            }
            return Ok(());
        }
    }

    // ~keep Normalize whitespace in the heading body: Tier-2's heading.rs walks
    // children with `convert_as_inline: true` which routes text through
    // text-node normalization, folding `\n + indent` runs to a single space.
    // Mirror that here so `<h3>Mozilla\n   sponsorship</h3>` emits
    // `### Mozilla sponsorship` rather than `### Mozilla\n  sponsorship`.
    if buf[content_start..].contains('\n') {
        let content = buf[content_start..].to_owned();
        let mut normalized = String::with_capacity(content.len());
        let mut prev_was_space = false;
        for ch in content.chars() {
            let is_ws = ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r';
            if is_ws {
                if !prev_was_space {
                    normalized.push(' ');
                    prev_was_space = true;
                }
            } else {
                normalized.push(ch);
                prev_was_space = false;
            }
        }
        buf.truncate(content_start);
        buf.push_str(normalized.trim_end());
    }

    // ~keep Tier-2's `text.trim()` (heading.rs) trims the ENTIRE rendered heading
    // body — not just internal whitespace runs — before prefixing. A leading
    // whitespace character (a decoded `&nbsp;`, or one migrated out of an
    // `<em>`/`<strong>` open marker by `close_inline_marker`'s leading-migration
    // step) would otherwise double up against the "# " prefix's own trailing
    // space (`<h3>&nbsp;x</h3>` -> "###  x" instead of Tier-2's "### x").
    // Trailing side of the same `text.trim()`. The whitespace-normalizing block above
    // only runs when the body contains a newline, so a heading whose body simply ENDS
    // in whitespace never reached a trailing trim -- `<h4><img alt="cafe &nbsp;"></h4>`
    // kept the decoded U+00A0 where Tier-2 dropped it. Found by the generated-corpus
    // parity test once issue #494's decoding made `&nbsp;` reach this path as a real
    // whitespace character rather than the literal text `&nbsp;`.
    let trailing_ws_len = buf[content_start..]
        .char_indices()
        .rev()
        .take_while(|&(_, c)| c.is_whitespace())
        .count();
    if trailing_ws_len > 0 {
        let cut = buf[content_start..]
            .char_indices()
            .rev()
            .take(trailing_ws_len)
            .last()
            .map_or(buf.len(), |(i, _)| content_start + i);
        buf.truncate(cut);
    }

    let leading_ws_len = buf[content_start..]
        .char_indices()
        .find(|&(_, c)| !c.is_whitespace())
        .map_or(buf.len() - content_start, |(i, _)| i);
    if leading_ws_len > 0 {
        buf.replace_range(content_start..content_start + leading_ws_len, "");
    }

    // ~keep Mirror Tier-2 (heading.rs, issue #661): a `#` run the line would close on stays text.
    // ~keep A Djot heading has no closing sequence.
    if options.output_format == crate::options::OutputFormat::Markdown {
        if let Some(at) = crate::converter::utility::escaping::atx_closing_sequence_offset(&buf[content_start..]) {
            buf.insert(content_start + at, '\\');
        }
    }

    let prefix = heading_prefix(n);
    buf.insert_str(content_start, prefix);
    // ~keep Tier-2 leaves a blank line ("\n\n") after a heading. A
    // following paragraph's "\n\n" guard then finds it already and appends
    // nothing, yielding the expected single blank line.
    ensure_blank_line_buf(state.cell_or_output_mut());
    Ok(())
}

fn close_blockquote(state: &mut Tier1State, frame: &OpenTag, br_in_tables: bool) {
    // ~keep Phase GG follow-up: inside a table cell `frame.content_start` indexes
    // into the cell buffer, not `state.output`.  Don't prefix `> ` — Tier-2
    // also sheds the quote marker inside cells (issue #647).
    if state.in_table_cell() {
        if state.escape_ctx.contains(EscapeCtx::CODE) {
            // ~keep In code Tier-2 keeps the line ends the quote writes there; the cell folds them.
            let cell_buf = state.cell_or_output_mut();
            let content_start = clamp_to_char_boundary(cell_buf, frame.content_start);
            // ~keep A quote that holds only whitespace writes nothing, as in Tier-2.
            let content = cell_buf.split_off(content_start);
            if !content.trim().is_empty() {
                if !cell_buf.is_empty() && !cell_buf.ends_with('\n') {
                    cell_buf.push('\n');
                }
                cell_buf.push_str(content.trim());
                cell_buf.push('\n');
            }
        } else {
            separate_closed_block_in_cell(state, frame.content_start, br_in_tables);
        }
        return;
    }
    let content_start = clamp_to_char_boundary(&state.output, frame.content_start);
    let mut content = state.output[content_start..].to_owned();
    // ~keep Trailing horizontal whitespace (e.g. a decoded `&nbsp;` folded to a
    // plain space) sitting right before `</blockquote>` is trimmed here,
    // mirroring `close_inline_marker`'s and `<br>`'s own trailing-whitespace
    // trim — Tier-2 does not carry it into the quoted line.
    crate::converter::main_helpers::trim_trailing_whitespace(&mut content);
    // ~keep Tier-2's `content.trim()` (blockquote.rs) trims the ENTIRE accumulated
    // child content — not just internal whitespace runs — before the "> "
    // per-line prefixing. A leading whitespace character (a decoded
    // `&nbsp;`, or one migrated out of an `<em>`/`<strong>` open marker by
    // `close_inline_marker`'s leading-migration step) would otherwise double
    // up against the prefix's own trailing space (`<blockquote>&nbsp;x</blockquote>`
    // -> ">  x" instead of Tier-2's "> x").
    let leading_ws_len = content
        .char_indices()
        .find(|&(_, c)| !c.is_whitespace())
        .map_or(content.len(), |(i, _)| i);
    if leading_ws_len > 0 {
        content.replace_range(0..leading_ws_len, "");
    }
    let prefixed = prefix_blockquote_lines(&content);
    state.output.truncate(content_start);
    if frame.prev_escape_ctx.contains(EscapeCtx::BLOCKQUOTE) {
        // ~keep Nested blockquote: `open_blockquote` already normalized the tail to
        // a clean blank line above; collapse it back to one newline here,
        // mirroring Tier-2's nested-blockquote separator handling.
        if state.output.ends_with("\n\n") {
            state.output.pop();
        }
    } else if !state.output.is_empty() {
        // ~keep Mirror Tier-2's top-level branch exactly (blockquote.rs:135-143): an
        // existing blank-line separator collapses to a single newline, but a
        // lone trailing newline (or none at all) is PROMOTED up to a blank
        // line. This is a literal function of the untouched pre-open tail —
        // see `open_blockquote` for why nothing runs there in this branch.
        if state.output.ends_with("\n\n") {
            state.output.pop();
        } else if !state.output.ends_with('\n') {
            state.output.push_str("\n\n");
        } else {
            state.output.push('\n');
        }
    }
    push_list_item_continuation_lines(state, &prefixed);

    // ~keep Tier-2's `handle_blockquote` (blockquote.rs:225-232) unconditionally trims
    // every trailing newline and re-pushes exactly "\n\n" after EVERY close --
    // top-level or nested, and regardless of what follows (a sibling, or nothing
    // at all; a trailing "\n\n" at document end is trimmed back down by the
    // shared end-of-document normalization both tiers already share). Existing
    // tests only covered "nothing follows the blockquote", where a missing
    // trailing separator here is invisible. `<blockquote>a</blockquote>after`
    // (top-level) and `<blockquote><blockquote>a</blockquote>b</blockquote>`
    // (nested) both need it: Tier-2 emits a blank line before `after` / a bare
    // `>` line before `b`. Gated on `!in_list_item` to mirror Tier-2's own
    // `!ctx.in_table_cell && !ctx.in_list_item` guard -- `in_table_cell` already
    // returned early above. In practice every list-item blockquote already bails
    // via `BailReason::ListItemUnsupportedBlockChild` before reaching here; the
    // guard is kept so this stays correct if that bail is ever narrowed.
    let in_list_item = state
        .stack
        .iter()
        .any(|open_frame| matches!(open_frame.spec.kind, TagKind::ListItem));
    if !in_list_item {
        state.ensure_blank_line();
    }
}

/// Whether Tier-2 renders the content of the element `name_lower` of kind `kind`, opened in the
/// escape context `ctx`, into a buffer of its own rather than into its parent's.
///
/// A cell break checks and trims only that buffer in Tier-2, so Tier-1 must not look past the
/// start of such an element in the flat cell buffer (see [`cell_scratch_start`]).
fn renders_into_own_buffer(kind: TagKind, name_lower: &[u8], ctx: EscapeCtx) -> bool {
    match kind {
        // ~keep In a cell Tier-2 writes a figure, fieldset, dl, details, dialog, menu and form
        // ~keep straight into the cell. It gives a legend and a figure caption a buffer of their
        // ~keep own, but this scanner writes neither the way Tier-2 does there, so they are not
        // ~keep marked here.
        TagKind::Blockquote
        | TagKind::Heading(_)
        | TagKind::Pre
        | TagKind::DefinitionTerm
        | TagKind::DefinitionDescription => true,
        // ~keep Inside code Tier-2 writes these straight into the code span.
        TagKind::Code | TagKind::Strong | TagKind::Emphasis | TagKind::Strikethrough | TagKind::Inserted => {
            !ctx.contains(EscapeCtx::CODE)
        }
        _ => matches!(name_lower, b"sub" | b"sup" | b"abbr"),
    }
}

/// The start, in the current cell buffer, of the buffer Tier-2 writes the current content into:
/// the content start of the innermost element opened in this cell that has a buffer of its own,
/// or 0 for the cell itself.
fn cell_scratch_start(state: &Tier1State) -> usize {
    innermost_own_buffer(state).map_or(0, |frame| frame.content_start)
}

/// The innermost element opened in the current cell that has a buffer of its own.
fn innermost_own_buffer(state: &Tier1State) -> Option<&OpenTag> {
    state
        .stack
        .iter()
        .rev()
        .take_while(|frame| !matches!(frame.spec.kind, TagKind::TableCell { .. } | TagKind::Summary))
        .find(|frame| frame.own_buffer)
}

/// Whether Tier-2 lays out `name_lower` in the current table cell in a way this scanner does not
/// reproduce, so the cell goes to Tier-2 (issue #645): a block inside an inline element with a
/// buffer of its own, a line break at the start of such an element or of a definition term or
/// definition, a block at the start of a definition term or definition after other cell content, a
/// legend, a
/// figure caption or a label, and a sectioning element after other cell content, which Tier-2
/// separates with a blank line that the cell folds into two spaces. An inline element right
/// after a block in a cell is left to Tier-2 too (see `emit_open`), and so are a definition after
/// another definition in the cell and a quote or heading that starts with whitespace (see
/// `check_whitespace_led_block_in_cell`).
fn cell_needs_tier2(state: &mut Tier1State, spec: &TagSpec, name_lower: &[u8]) -> bool {
    if !state.in_table_cell() {
        return false;
    }
    if matches!(name_lower, b"legend" | b"figcaption" | b"label") {
        return true;
    }
    let definition = matches!(spec.kind, TagKind::DefinitionTerm | TagKind::DefinitionDescription);
    if definition && state.table_stack.last().is_some_and(|ts| ts.definition_in_cell) {
        return true;
    }
    let sectioning = matches!(
        name_lower,
        b"article" | b"section" | b"nav" | b"aside" | b"header" | b"footer" | b"main"
    );
    let in_inline_buffer = state
        .stack
        .iter()
        .rev()
        .take_while(|frame| !matches!(frame.spec.kind, TagKind::TableCell { .. } | TagKind::Summary))
        .any(|frame| frame.own_buffer && !frame.spec.is_block);
    let inline_buffer = innermost_own_buffer(state)
        .filter(|frame| {
            !frame.spec.is_block
                || matches!(
                    frame.spec.kind,
                    TagKind::DefinitionTerm | TagKind::DefinitionDescription
                )
        })
        .map(|frame| frame.content_start);
    let cell_buf = state.cell_or_output_mut();
    let buffer_so_far = inline_buffer.map(|start| &cell_buf[clamp_to_char_boundary(cell_buf, start)..]);
    let at_buffer_start = buffer_so_far.is_some_and(|text| text.trim().is_empty());
    let break_at_buffer_start = matches!(spec.kind, TagKind::LineBreak) && at_buffer_start;
    let block_at_buffer_start = spec.is_block && at_buffer_start && !cell_buf.trim().is_empty();
    (sectioning && !cell_buf.is_empty())
        || (spec.is_block && in_inline_buffer)
        || break_at_buffer_start
        || block_at_buffer_start
}

/// Drop the whitespace at the start of the content a definition term or definition wrote into a
/// table cell from `content_start`, as Tier-2 trims the buffer of each. Tier-2 separates a rule at
/// the start of a definition from the cell content before it, and this scanner cannot tell a rule
/// from `---` text there, so content that starts with whitespace and `---` goes to Tier-2.
fn trim_start_of_cell_content(state: &mut Tier1State, content_start: usize) -> Result<(), BailReason> {
    if !state.in_table_cell() {
        return Ok(());
    }
    let cell_buf = state.cell_or_output_mut();
    let start = clamp_to_char_boundary(cell_buf, content_start);
    let content = cell_buf[start..].trim_start();
    let leading = cell_buf.len() - start - content.len();
    if leading > 0 && content.starts_with("---") {
        return Err(BailReason::TableBlockChildInCell);
    }
    cell_buf.replace_range(start..start + leading, "");
    Ok(())
}

/// Leave a table cell to Tier-2 when a quote or heading in it closes with content after
/// whitespace at its start: Tier-2 keeps that whitespace in the element's own buffer and breaks
/// the cell twice before the content. A quote or heading with no other content writes nothing.
fn check_whitespace_led_block_in_cell(state: &mut Tier1State, frame: &OpenTag) -> Result<(), BailReason> {
    if !frame.starts_with_whitespace || !state.in_table_cell() {
        return Ok(());
    }
    let cell_buf = state.cell_or_output_mut();
    let start = clamp_to_char_boundary(cell_buf, frame.content_start);
    if cell_buf[start..].trim().is_empty() {
        return Ok(());
    }
    Err(BailReason::TableBlockChildInCell)
}

/// Run `write` on the part of the cell buffer Tier-2 writes the current content into, so a cell
/// break checks and trims only that content, as Tier-2's does (issue #645).
fn with_cell_scratch<R>(state: &mut Tier1State, write: impl FnOnce(&mut String) -> R) -> R {
    let start = cell_scratch_start(state);
    let cell_buf = state.cell_or_output_mut();
    let start = clamp_to_char_boundary(cell_buf, start);
    if start == 0 {
        return write(cell_buf);
    }
    let mut scratch = cell_buf.split_off(start);
    let result = write(&mut scratch);
    cell_buf.push_str(&scratch);
    result
}

/// Write the cell break at `at` in the cell buffer, between a block in a table cell and the cell
/// content before it, as Tier-2 does (issue #645).
///
/// Only the content written since the innermost element with a buffer of its own opened counts
/// (see [`cell_scratch_start`]). Inside a heading or code Tier-2 writes the content inline with no
/// break. Tier-2 trims the start of a block's content, so the content after `at` is trimmed too.
fn separate_block_in_cell_at(state: &mut Tier1State, at: usize, br_in_tables: bool) {
    if state.escape_ctx.intersects(EscapeCtx::HEADING | EscapeCtx::CODE) {
        return;
    }
    let scratch_start = cell_scratch_start(state);
    let cell_buf = state.cell_or_output_mut();
    let at = clamp_to_char_boundary(cell_buf, at);
    let scratch_start = clamp_to_char_boundary(cell_buf, scratch_start.min(at));
    if cell_buf[scratch_start..at].trim().is_empty() {
        return;
    }
    let content = cell_buf.split_off(at);
    crate::converter::main_helpers::separate_block_in_cell(cell_buf, br_in_tables);
    cell_buf.push_str(content.trim_start());
}

/// Separate the content of a block that closes in a table cell from the cell content before it.
fn separate_closed_block_in_cell(state: &mut Tier1State, content_start: usize, br_in_tables: bool) {
    let cell_buf = state.cell_or_output_mut();
    let content_start = clamp_to_char_boundary(cell_buf, content_start);
    if cell_buf[content_start..].trim().is_empty() {
        return;
    }
    separate_block_in_cell_at(state, content_start, br_in_tables);
}

fn close_pre(state: &mut Tier1State, frame: &OpenTag, options: &ConversionOptions) {
    use crate::options::CodeBlockStyle;
    // ~keep Phase GG follow-up: when `<pre>` opened inside a table cell, its content
    // was accumulated into `current_cell` (the cell buffer), not `state.output`.
    // The frame's `content_start` indexes into the cell buffer.  Don't emit a
    // code fence — Tier-2 also collapses pre inside cells to plain inline text
    // (the cell's `replace('\n', ' ')` step does the rest).
    if state.in_table_cell() {
        separate_closed_block_in_cell(state, frame.content_start, options.br_in_tables);
        return;
    }
    let content_start = clamp_to_char_boundary(&state.output, frame.content_start);
    let raw = state.output[content_start..].to_owned();
    state.output.truncate(content_start);
    // ~keep Render into a scratch buffer first, then (when inside a list item)
    // indent every physical line to the item's continuation column
    // before appending to `state.output` — see `push_list_item_continuation_lines`.
    let mut rendered = String::new();
    match options.code_block_style {
        CodeBlockStyle::Indented => {
            rendered.push_str(&indent_pre_lines(&raw));
        }
        CodeBlockStyle::Backticks => {
            // ~keep the fence must be strictly longer than the longest run of `` ` ``
            // inside the content, otherwise the fence terminates early and
            // corrupts the rest of the document (CommonMark 4.5). Mirrors
            // `handlers::code_block::format_code_block`'s Backticks branch.
            let fence_length = (longest_consecutive_backtick_run(&raw) + 1).max(MIN_FENCE_LENGTH);
            let fence: String = std::iter::repeat_n('`', fence_length).collect();

            rendered.push_str(&fence);
            if let Some(lang) = state.pre_lang.take() {
                rendered.push_str(&lang);
            } else if !options.code_language.is_empty() {
                rendered.push_str(&options.code_language);
            }
            rendered.push('\n');
            // ~keep Strip a single leading newline (Tier-2 emits `\ncontent...`) but
            // ALL trailing newlines, not just one: Tier-2's `format_code_block`
            // (handlers/code_block.rs) closes the fenced branch with
            // `content.trim_end_matches('\n')`, unconditionally, regardless of
            // how many trailing newlines `handle_pre` reconstructed upstream.
            // A nested block element that itself forces a full blank-line
            // separator on close (e.g. `<blockquote>`, since its fix) leaves 2
            // trailing newlines here when it is the last child of `<pre>` --
            // stripping only one left a spurious blank line before the closing
            // fence that Tier-2 never emits.
            let raw = raw.strip_prefix('\n').unwrap_or(&raw);
            let raw = raw.trim_end_matches('\n');
            rendered.push_str(raw);
            rendered.push('\n');
            rendered.push_str(&fence);
            // ~keep Tier-2's `format_code_block` (handlers/code_block.rs) ends the
            // Backticks/Tildes branch with `output.push_str("\n\n")` — a clean
            // blank-line terminator, not a single newline.  Matching that
            // precisely matters beyond the general case (where a following
            // sibling's own leading-separator logic papers over a single-vs-
            // double difference either way): `close_blockquote`'s top-level
            // branch inspects this exact trailing state to decide whether to
            // collapse or promote the separator, so leaving only one newline
            // here made a `<pre>` directly followed by a `<blockquote>`
            // diverge from Tier-2 (discovered via that fix; see tests).
            rendered.push_str("\n\n");
        }
        CodeBlockStyle::Tildes => {
            rendered.push_str(&indent_pre_lines(&raw));
        }
    }
    push_list_item_continuation_lines(state, &rendered);
    state.pre_lang = None;
}

/// Indent a text node that starts a fresh, still-unindented physical line
/// inside a list item (e.g. sibling text right after a heading, which only
/// emits a single trailing newline rather than a blank line) to the item's
/// continuation column — the same indent every block handler
/// (`push_list_item_continuation_lines`) adds before its own first line.
/// Without it the line lands flush left and the item (and the rest of the
/// list) falls out of the list on reparse (CommonMark spec example 300).
///
/// Excluded from verbatim contexts (checked by the caller: `in_pre`/`in_code`
/// text never reaches this point) and from contexts that accumulate into a
/// detached scratch buffer rather than the real document (`in_table_cell`,
/// `in_summary`, `in_table_caption`), where `cell_or_output_mut()` is not the
/// list item's own accumulating text and indenting it would corrupt literal
/// or already-wrapped content instead. Mirrors Tier-2's `text_node.rs`
/// (`ctx.in_list_item && output.ends_with('\n') && !output.ends_with("\n\n")`).
fn indent_fresh_list_item_text_line(state: &mut Tier1State) {
    if state.in_table_cell() || state.in_summary() || state.in_table_caption() {
        return;
    }
    let in_list_item = state
        .stack
        .iter()
        .any(|frame| matches!(frame.spec.kind, TagKind::ListItem));
    if !in_list_item {
        return;
    }
    let indent_width = state.list_continuation_indent_width();
    if indent_width == 0 {
        return;
    }
    let dest = state.cell_or_output_mut();
    if dest.ends_with('\n') && !dest.ends_with("\n\n") {
        let indent: String = std::iter::repeat_n(' ', indent_width).collect();
        dest.push_str(&indent);
    }
}

/// Append `rendered` (a fully-formatted block's text, possibly spanning
/// several physical lines) to `state.output`, indenting every line to the
/// innermost open list item's continuation column when inside one.
///
/// CommonMark matches list containment per physical line (spec examples
/// 263, 273, 274, 318, 324): a non-blank line that isn't indented to the
/// item's continuation width falls out of the item — and the list — on
/// reparse. Mirrors Tier-2's `format_code_block_in_list_item`
/// (handlers/code_block.rs): the very first line skips the indent when it
/// is NOT a continuation (i.e. it sits directly after the item's own
/// marker, like `- ` + the block's first line, and already starts at the
/// right column); every other non-blank line always gets indented. Blank
/// lines are left bare — an indented blank line would just be trailing
/// whitespace.
fn push_list_item_continuation_lines(state: &mut Tier1State, rendered: &str) {
    let indent_width = state.list_continuation_indent_width();
    if indent_width == 0 {
        state.output.push_str(rendered);
        return;
    }
    // ~keep A plain suffix check like `ends_with("* ")` also matches the closing
    // "**"/"*" of `<strong>`/`<em>` immediately followed by a migrated trailing
    // space, indistinguishable from a real bare bullet by suffix alone. Reuse
    // `line_is_bare_list_marker` (this file, mirrors Tier-2's
    // `list::utils::line_is_bare_list_marker`) instead of repeating that ambiguity.
    let is_continuation = !state.output.is_empty() && !line_is_bare_list_marker(&state.output);
    let indent: String = std::iter::repeat_n(' ', indent_width).collect();
    for (index, segment) in rendered.split_inclusive('\n').enumerate() {
        let line = segment.strip_suffix('\n').unwrap_or(segment);
        if line.is_empty() || (index == 0 && !is_continuation) {
            state.output.push_str(segment);
        } else {
            state.output.push_str(&indent);
            state.output.push_str(segment);
        }
    }
}

fn close_code(state: &mut Tier1State, frame: &OpenTag) -> Result<(), BailReason> {
    if state.escape_ctx.contains(EscapeCtx::PRE) || state.escape_ctx.contains(EscapeCtx::CODE) {
        return Ok(());
    }
    // ~keep Phase CC: smart backtick escaping (mirrors inline/code.rs:260).
    // Open emitted nothing; content from `frame.content_start` to buf
    // end is the raw code content.  Choose num_backticks + delimiter
    // spaces from that slice, then truncate and re-emit wrapped.
    let buf = state.cell_or_output_mut();
    let content_start = clamp_to_char_boundary(buf, frame.content_start);
    if content_start >= buf.len() {
        // ~keep issue #481: a body that WAS non-empty but entirely whitespace before
        // `flush_text` dropped it is not an empty one. Tier-2 keeps `<code> </code>` as
        // a code span whose content is that space; erasing it here, as the genuinely
        // empty `<code></code>` case correctly does, would drop both the span and the
        // word separator it stands between.
        if frame.dropped_whitespace_only_text {
            return Err(BailReason::WhitespaceOnlyInlineEmphasis);
        }
        // ~keep No content emitted between open and close — Tier-2 emits
        // nothing for empty <code></code>.
        return Ok(());
    }

    // ~keep issue #483, backtick form: this span's opening backtick is about to be inserted
    // right after a preceding code span's closing one, which reparses as a single span
    // carrying both literal backticks. Tier-2 merges the two spans
    // (`wrapped::emit_code_span`); Tier-1 does not, so it bails.
    if buf[..content_start].ends_with('`') {
        return Err(BailReason::AdjacentInlineEmphasis);
    }

    // ~keep issue #487: `content` may contain internal '\n' bytes, each marking where a
    // `<br>` split this span (`emit_void`'s `TagKind::LineBreak` arm) -- a text
    // node's own line ending never reaches this buffer as a bare '\n' (`flush_text`'s
    // `in_code` branch already folds it to a space). Split on it and render each
    // segment as its own smart-escaped backtick span (`format_inline_code_segment`,
    // computed per segment rather than once over the whole original content), joined
    // by the "  \n" hard-break marker OUTSIDE the backticks -- the only marker shape
    // this scanner ever needs, since the router bails to Tier-2 whenever
    // `newline_style` is not `Spaces`. An empty segment (an adjacent, leading, or
    // trailing `<br>`) is dropped rather than rendered as a dangling empty `` `` ``
    // pair with nothing before or after it. Only the FIRST segment can ever be
    // adjacent to a preceding sibling's closing backtick -- checked once, above,
    // against `buf[..content_start]` before this loop runs -- every later segment is
    // preceded by our own separator instead.
    let content = buf[content_start..].to_owned();
    buf.truncate(content_start);

    let mut first = true;
    for segment in content.split('\n').filter(|segment| !segment.is_empty()) {
        if !first {
            buf.push_str("  \n");
        }
        format_inline_code_segment(buf, segment);
        first = false;
    }
    Ok(())
}

/// Wrap `content` in backtick delimiters, choosing the fence width and delimiter-space
/// padding from `content` alone.
///
/// The per-segment counterpart to what this replaced: `close_code` used to compute these
/// once over the whole span's content, but a `<br>`-split span now needs them computed
/// independently for each segment, since a backtick run in one half must not force a wider
/// fence on a half that has none (issue #487). Mirrors
/// `handlers::code_block::format_inline_code`.
fn format_inline_code_segment(buf: &mut String, content: &str) {
    let contains_backtick = content.contains('`');
    let first_char = content.chars().next();
    let last_char = content.chars().last();
    let starts_with_space = first_char == Some(' ');
    let ends_with_space = last_char == Some(' ');
    let starts_with_backtick = first_char == Some('`');
    let ends_with_backtick = last_char == Some('`');
    // ~keep No all-spaces case: CommonMark strips one space from each end of a code span
    // only when the content is NOT entirely spaces, so padding an all-spaces body
    // changes what it contains. Mirrors `handlers::code_block::format_inline_code`.
    let needs_spaces =
        starts_with_backtick || ends_with_backtick || (starts_with_space && ends_with_space && contains_backtick);
    let num_backticks = if contains_backtick {
        min_safe_code_span_delimiter_length(content)
    } else {
        1
    };

    for _ in 0..num_backticks {
        buf.push('`');
    }
    if needs_spaces {
        buf.push(' ');
    }
    buf.push_str(content);
    if needs_spaces {
        buf.push(' ');
    }
    for _ in 0..num_backticks {
        buf.push('`');
    }
}

/// Compute the length of the longest consecutive run of `` ` `` in `content`.
///
/// ~keep Mirrors `converter::handlers::code_block::longest_consecutive_run`
/// (see the shared-helper note on `MIN_FENCE_LENGTH` above).
fn longest_consecutive_backtick_run(content: &str) -> usize {
    content
        .chars()
        .fold((0usize, 0usize), |(max, current), c| {
            if c == '`' {
                let next = current + 1;
                (max.max(next), next)
            } else {
                (max, 0)
            }
        })
        .0
}

/// Smallest backtick-run length (starting at 1) that does not occur as a run inside `content`.
///
/// ~keep Mirrors `converter::handlers::code_block::min_safe_code_span_delimiter_length`
/// byte-for-byte (see the shared-helper note on `MIN_FENCE_LENGTH` above). CommonMark
/// closes an inline code span at the next backtick string of the *same* length as the
/// opener (6.1), so `longest_run + 1` unconditionally over-escapes: content `` `` `` (a
/// single length-2 run, no length-1 run) is valid with a single backtick delimiter.
fn min_safe_code_span_delimiter_length(content: &str) -> usize {
    let mut run_lengths = std::collections::HashSet::new();
    let mut current = 0usize;
    for c in content.chars() {
        if c == '`' {
            current += 1;
        } else {
            if current > 0 {
                run_lengths.insert(current);
            }
            current = 0;
        }
    }
    if current > 0 {
        run_lengths.insert(current);
    }

    let mut candidate = 1usize;
    while run_lengths.contains(&candidate) {
        candidate += 1;
    }
    candidate
}

/// Returns `true` if every byte of `needle` appears in `haystack`, in order, not
/// necessarily contiguously (a byte-level subsequence test). O(haystack.len()), no
/// allocation.
///
/// ~keep Used by `close_link`'s nested-markup autolink guard: greedy left-to-right
/// matching is correct for subsequence testing regardless of UTF-8 char
/// boundaries — if a char sequence is a subsequence of another, each char's
/// byte run appears intact and in order, so the greedy byte scan below always
/// finds it. A byte-level "match" that happens to straddle char boundaries can
/// only make this return `true` MORE often than a char-aware version would,
/// never less — which only makes the caller's bail more conservative, never
/// less safe.
fn is_byte_subsequence(needle: &str, haystack: &str) -> bool {
    let mut needle_bytes = needle.bytes();
    let Some(mut want) = needle_bytes.next() else {
        return true;
    };
    for byte in haystack.bytes() {
        if byte == want {
            match needle_bytes.next() {
                Some(next_want) => want = next_want,
                None => return true,
            }
        }
    }
    false
}

/// Rewrites the link the scanner has already opened in `dest` into GFM autolink form
/// (`<href>`) when Tier-2 would do the same, returning `Ok(true)` when it did.
///
/// Mirrors Tier-2's predicate at `handlers/link.rs:91-101` exactly: `options.autolinks &&
/// !options.default_title && href non-empty && has_uri_scheme(href) && (label == href ||
/// (mailto: && label == href[7..]))`. `dest[trim_start..]` is Tier-2's `raw_text` for the
/// common flat-text case -- both sides have already collapsed whitespace/NBSP the same way,
/// and neither has run `escape_link_label` or bracket-wrapping yet.
fn try_emit_autolink(
    dest: &mut String,
    trim_start: usize,
    frame: &OpenTag,
    href_str: &str,
    has_nested_tag: bool,
    options: &ConversionOptions,
) -> Result<bool, BailReason> {
    if !options.autolinks || options.default_title || href_str.is_empty() || !has_uri_scheme(href_str) {
        return Ok(false);
    }
    let mailto_suffix = href_str.strip_prefix("mailto:");
    let label = &dest[trim_start..];
    if has_nested_tag {
        // ~keep A nested tag means the buffer is no longer flat text, so a literal
        // `label == href` compare is untrustworthy: `<b>u</b>` renders as `**u**`,
        // which never equals bare `u`, yet Tier-2 -- which compares against the
        // TAG-STRIPPED text -- would autolink it. Bailing on every nested tag is not
        // the fix either: measured against `tools/benchmark-harness/fixtures`,
        // 85-100% of scheme-href `<a>` elements on every fixture that has any are
        // wrapped in at least a `<span>`, so a blanket bail would drop nearly every
        // real page off the Tier-1 fast path.
        // ~keep
        // ~keep Instead, a cheap PROVABLY CONSERVATIVE precheck. Every transformation
        // Tier-1 applies while rendering a label (emphasis/strong/strikethrough and
        // inserted markers, code-span backtick fences, label-bracket escaping,
        // `![alt](src)` for a nested `<img>`) only INSERTS characters; none delete or
        // substitute the underlying text. Tier-2's `raw_text` is that same underlying
        // text with tags stripped and whitespace collapsed, both of which only REMOVE
        // characters. So `raw_text` is always a subsequence of this buffer, and if
        // `raw_text == target` then `target` is a subsequence of the buffer too.
        // Contrapositive: a `target` that is NOT a subsequence proves Tier-2 cannot
        // autolink either, so falling through to the normal link form is safe. Bail
        // only when the precheck cannot rule it out.
        let could_be_autolink = is_byte_subsequence(href_str, label)
            || mailto_suffix.is_some_and(|suffix| is_byte_subsequence(suffix, label));
        if could_be_autolink {
            return Err(BailReason::LinkAutolinkNestedMarkup);
        }
        // ~keep Ruled out above, so the exact `label == target` match below cannot fire
        // either -- equality would imply the subsequence that was just disproved.
    }
    let rendered = if label == href_str {
        href_str
    } else if mailto_suffix == Some(label) {
        // ~keep `mailto_suffix` is `Some` on this arm by construction.
        mailto_suffix.unwrap_or(href_str)
    } else {
        return Ok(false);
    };
    // ~keep An autolink has no bracket wrapping at all, but the scanner already emitted
    // the opening `[` at link-open time, before it could know the label. Remove it,
    // mirroring the href-less branch in `close_link` that does the same cleanup.
    let bracket_search_end = clamp_to_char_boundary(dest, frame.content_start);
    let label_start = if let Some(bracket_pos) = dest[..bracket_search_end].rfind('[') {
        dest.remove(bracket_pos);
        trim_start - 1
    } else {
        trim_start
    };
    let rendered = rendered.to_owned();
    dest.truncate(label_start);
    dest.push('<');
    dest.push_str(&rendered);
    dest.push('>');
    Ok(true)
}

/// Trim the link label Tier-1 has just written in place, keeping a hard line break that sits
/// at either edge of it.
///
/// A `<br>` against the `</a>` is real content: `<a href="H">A<br></a>B` renders as A, a line
/// break, then B, and `[A  \n](H)B` re-parses to exactly that (issue #497). The blanket
/// trailing-whitespace trim this replaced ate the marker's two spaces and its newline, since
/// flattened they are indistinguishable from incidental whitespace before a `</a>`.
///
/// Mirrors Tier-2's `assemble_label` (`utility/content.rs`) including its two edge rules: a
/// run of breaks at one edge collapses to a single break, because two adjacent markers put a
/// blank line in the label and a blank line ends the paragraph the link lives in; and a label
/// holding nothing but breaks collapses to empty, because a break needs a line on both sides
/// to mean anything.
///
/// Only the `"  \n"` marker is matched: `router.rs` bails Tier-1 whenever `newline_style` is
/// not `Spaces`, so it is the only shape Tier-1 can have emitted.
///
/// With `keeps_breaks` false -- a heading or a pipe-table cell, neither of which can carry a
/// hard break at all -- every marker in the label is folded to a space instead, which is what
/// Tier-2 does at emission time in `line_break.rs`.
fn trim_label_preserving_boundary_hard_breaks(dest: &mut String, trim_start: usize, keeps_breaks: bool) {
    const MARKER: &str = "  \n";

    if !keeps_breaks {
        // ~keep Fold the markers away entirely rather than merely declining to keep the ones at
        // the edges. `close_heading` / `close_table_cell` would collapse them to a space
        // anyway, but they run AFTER `close_link` has escaped the label, so a marker left
        // here reaches `escape_link_label` as a real line break and its continuation line
        // gets a #496 block-opener escape that Tier-2 -- which folds at emission time,
        // in `line_break.rs`'s `in_heading` arm -- never applies. That divergence is
        // visible as `# [A \- B](H)` against Tier-2's `# [A - B](H)`.
        let label = &dest[trim_start..];
        if label.contains(MARKER) {
            let folded = label.replace(MARKER, " ");
            dest.truncate(trim_start);
            dest.push_str(&folded);
        }
        // ~keep Trim BOTH ends, not just the trailing one: Tier-2 reaches this label through
        // `normalize_link_label`, which trims both, so a folded leading break that left a
        // space behind shows up as `## [ A](H)` against Tier-2's `## [A](H)`.
        let trimmed = dest[trim_start..].trim_matches(|c: char| c.is_whitespace()).to_owned();
        dest.truncate(trim_start);
        dest.push_str(&trimmed);
        return;
    }

    let label = &dest[trim_start..];
    let without_trailing = label.trim_end_matches(MARKER);
    let has_trailing_break = without_trailing.len() != label.len();
    let body = without_trailing.trim_end_matches(|c: char| c.is_whitespace());
    let without_leading = body.trim_start_matches(MARKER);
    let has_leading_break = without_leading.len() != body.len();

    let mut rebuilt = String::with_capacity(without_leading.len() + 2 * MARKER.len());
    if !without_leading.is_empty() {
        if has_leading_break {
            rebuilt.push_str(MARKER);
        }
        rebuilt.push_str(without_leading);
        if has_trailing_break {
            rebuilt.push_str(MARKER);
        }
    }

    if rebuilt.len() != label.len() {
        dest.truncate(trim_start);
        dest.push_str(&rebuilt);
    }
}

fn close_link(state: &mut Tier1State, frame: &OpenTag, options: &ConversionOptions) -> Result<(), BailReason> {
    // ~keep Close the link: `](href "title")` or `](href)`
    // If no href, just emit the text as-is (Tier-2 behaviour: no link markup).
    // Link state was pushed to state.link_stack at open; pop it now.
    let (href, title, has_nested_tag) = state.link_stack.pop().unwrap_or((None, None, false));
    // ~keep Mirrors the branch ORDER of Tier-2's `line_break.rs`, where `in_heading` and
    // `in_table_cell` are both tested ahead of the link arm: a single-line ATX heading
    // and a pipe-table cell cannot carry a hard break at all, so a `<br>` in either has
    // already been folded to a space regardless of the link, and a marker kept at the
    // label's edge here would only survive as a stray trailing space.
    let keeps_boundary_hard_breaks = !state.escape_ctx.contains(EscapeCtx::HEADING) && !state.in_table_cell();
    let dest = state.cell_or_output_mut();
    // ~keep Trim the whitespace inside the link label so `[text  ](url)` collapses to
    // `[text](url)` — matches Tier-2's `normalize_link_label` (kimbrain.html and similar
    // source HTML with whitespace before `</a>`), while keeping a `<br>` that sits at
    // either edge of the label (issue #497).
    let trim_start = clamp_to_char_boundary(dest, frame.content_start);
    trim_label_preserving_boundary_hard_breaks(dest, trim_start, keeps_boundary_hard_breaks);
    // ~keep Mirror Tier-2's `normalize_whitespace_cow` step inside
    // `normalize_link_label` (utility/content.rs:144): any Unicode whitespace
    // in the link label (notably NBSP `\u{00a0}`) collapses to a single ASCII
    // space.  Tier-1 otherwise emits `[Designed\u{a0}by](url)` where Tier-2
    // emits `[Designed by](url)`.
    if dest[trim_start..].contains('\u{00a0}') {
        let normalised: String = dest[trim_start..]
            .chars()
            .map(|c| if c == '\u{00a0}' { ' ' } else { c })
            .collect();
        dest.truncate(trim_start);
        dest.push_str(&normalised);
    }
    if let Some(href_str) = href.as_deref() {
        if try_emit_autolink(dest, trim_start, frame, href_str, has_nested_tag, options)? {
            return Ok(());
        }
    }
    // ~keep Wikipedia back-reference normalisation (Tier-2 `handlers/link.rs:205`):
    // a label of exactly `^` paired with an `#anchor` href is rewritten to
    // `↑` so it does not look like Markdown's footnote syntax.
    if let Some(href_str) = href.as_deref() {
        if href_str.starts_with('#') && dest.len() == trim_start + 1 && dest.as_bytes()[trim_start] == b'^' {
            dest.truncate(trim_start);
            dest.push('↑');
        }
    }
    if let Some(href) = href {
        // ~keep Security fix mirror (`handlers/link.rs:208`, outside tier1/, via
        // the shared `escape_link_label` helper — same class of bug just
        // fixed for the SVG `<title>` label above): an unescaped `]` in
        // link text lets `<a href="/x">a] (https://evil.example) b</a>`
        // close the label early and open a second, attacker-controlled
        // Markdown link — inert HTML source turned into a live injection
        // by the unescaped label. Only applies when a `[...]` label is
        // actually being emitted (the `href`-less branch below emits the
        // text with no bracket wrapping at all, matching Tier-2's separate
        // no-`escape_link_label` code path for that case). Applied after
        // the caret rewrite above (matching Tier-2's order); `↑` contains
        // no bracket so the rewrite is a no-op for `escape_link_label`
        // either way.
        // `escaped_label` borrows from `dest` when unescaped (the common case), so it
        // cannot outlive the `truncate`/`push_str` below that mutably borrows `dest` --
        // only rewrite `dest` when escaping actually produced an owned copy.
        match crate::converter::utility::escaping::escape_link_label(&dest[trim_start..]) {
            std::borrow::Cow::Borrowed(_) => {}
            std::borrow::Cow::Owned(escaped_label) => {
                dest.truncate(trim_start);
                dest.push_str(&escaped_label);
            }
        }
        if let Some(title) = title {
            // ~keep Tier-2 in production HTML fixtures HTML-encodes a literal `"`
            // in the title attribute to `&quot;` (rather than the
            // `replace('"', "\\\"")` in `escape_markdown_title` in `inline/link.rs`).  The
            // backslash-escape branch of link.rs appears unreachable in
            // practice for the title attribute path on these fixtures.
            // Same escaper as Tier-2's `append_markdown_link`. This used to substitute
            // `&quot;` instead, described as "mirror the observed fixture behaviour" --
            // behaviour observed in a world where attributes were only half-decoded, so
            // a literal `"` in a title was rare enough that the divergence from Tier-2's
            // `\"` went unnoticed. Full decoding (issue #494) makes it reachable.
            let escaped_title = crate::converter::inline::link::escape_markdown_title(&title);
            let title_out: &str = &escaped_title;
            // ~keep Destination written by Tier-2's own `append_url_destination` rather than
            // interpolated (mirrors the image path above): an entity-shaped `&` decoded
            // by #494's full-decode (issue #498), an unbalanced paren, and a
            // whitespace-bearing destination all need the same escaping/wrapping Tier-2
            // applies, and interpolating `href` raw made all three diverge here.
            dest.push_str("](");
            crate::converter::inline::link::append_url_destination(dest, &href, options.url_escape_style, true);
            dest.push_str(" \"");
            dest.push_str(title_out);
            dest.push_str("\")");
        } else {
            dest.push_str("](");
            crate::converter::inline::link::append_url_destination(dest, &href, options.url_escape_style, false);
            dest.push(')');
        }
    } else {
        let bracket_search_end = clamp_to_char_boundary(dest, frame.content_start);
        if let Some(bracket_pos) = dest[..bracket_search_end].rfind('[') {
            dest.remove(bracket_pos);
        }
    }
    Ok(())
}

fn close_list(state: &mut Tier1State, kind: ListKind) {
    state.list_depth = state.list_depth.saturating_sub(1);
    if matches!(kind, ListKind::Unordered) {
        state.ul_depth = state.ul_depth.saturating_sub(1);
    }
    // ~keep When inside a table cell, Tier-2 does NOT add a trailing newline after
    // the list — the cell accumulator handles any separators via the
    // `\n → space` replacement at cell-close time.
    if state.in_table_cell() {
        return;
    }
    let dest = state.cell_or_output_mut();
    if !dest.ends_with('\n') {
        dest.push('\n');
    }
    if kind == ListKind::Ordered {
        let end = dest.trim_end().len();
        state.last_ordered_list_end = Some(end);
    }
}

fn close_list_item(state: &mut Tier1State, frame: &OpenTag) -> Result<(), BailReason> {
    // ~keep When inside a table cell, Tier-2 does NOT add a trailing newline after
    // each list item (see list/item.rs: `if !ctx.in_table_cell { ... \n ... }`).
    // Items are concatenated directly in the cell accumulator.
    if state.in_table_cell() {
        let cell_buf = state.cell_or_output_mut();
        while cell_buf.ends_with(' ') || cell_buf.ends_with('\t') {
            cell_buf.pop();
        }
        return Ok(());
    }
    state.list_item_marker_widths.pop();
    let after_text = state.list_items_after_text.pop().unwrap_or_default();
    trim_trailing_inline_whitespace(state);
    // ~keep A nested item, or an item after text inside its list, with nothing on its marker line
    // ~keep cannot interrupt the text before it (issue #667). Tier 2 decides whether that text is
    // ~keep an open paragraph.
    let follows_text = state.list_depth > 1 || after_text;
    let dest = state.cell_or_output_mut();
    let marker_line = dest
        .get(clamp_to_char_boundary(dest, frame.content_start)..)
        .unwrap_or_default();
    if follows_text && marker_line.split('\n').next().unwrap_or_default().trim().is_empty() {
        return Err(BailReason::EmptyNestedListItem);
    }
    // ~keep Phase EE: loose-list separator.  When this item had block-level
    // children (its content range contains a `\n\n` block separator),
    // mirror Tier-2's `handle_li` ensure_trailing_blank_line behaviour
    // so the next sibling `<li>` starts after a blank line.  Plain text
    // items still get the tight `\n` terminator.
    let had_block_children = {
        let start = clamp_to_char_boundary(dest, frame.content_start);
        dest[start..].contains("\n\n")
    };
    if had_block_children {
        if !dest.ends_with("\n\n") {
            if dest.ends_with('\n') {
                dest.push('\n');
            } else {
                dest.push_str("\n\n");
            }
        }
    } else if !dest.is_empty() && !dest.ends_with('\n') {
        dest.push('\n');
    }
    Ok(())
}

// ~keep ── Definition-list helpers ───────────────────────────────────────────────────
// ~keep
// ~keep Tier-2 reference: crates/html-to-markdown/src/converter/list/definition.rs.
// Tier-2 builds the full <dl> content in a buffer, trims it, then emits with
// "\n\n" boundaries. <dt> emits trimmed term + "\n"; <dd> emits trimmed
// description + "\n\n". Tier-1 streams the same shape by:
//   - open_dl: ensure blank line; record content_start on the frame
//   - close_dt: trim trailing whitespace, push "\n"
//   - close_dd: trim trailing whitespace, push "\n\n"
//   - close_dl: trim leading/trailing whitespace inside the dl range, then
//               normalise the trailing separator to "\n\n"
// ~keep
// ~keep Bails on dl/dt/dd are removed (see bail_unsupported). Implicit close of an
// open dt/dd when a sibling dt/dd opens is wired via OptionalCloseRule::
// CloseSiblingDtDd in spec_rules.rs and runs the same close_dt/close_dd path
// through emit_close_for_implicit.

fn open_dl(state: &mut Tier1State) {
    if state.in_table_cell() {
        return;
    }
    state.ensure_blank_line();
}

fn open_dt(state: &mut Tier1State) {
    mark_definition_in_cell(state);
}

fn open_dd(state: &mut Tier1State) {
    mark_definition_in_cell(state);
}

fn mark_definition_in_cell(state: &mut Tier1State) {
    if let Some(ts) = state.table_stack.last_mut().filter(|ts| ts.in_cell) {
        ts.definition_in_cell = true;
    }
}

fn close_dt(state: &mut Tier1State) {
    if state.in_table_cell() {
        return;
    }
    trim_trailing_inline_whitespace(state);
    let buf = state.cell_or_output_mut();
    if buf.is_empty() || buf.ends_with('\n') {
        return;
    }
    buf.push('\n');
}

fn close_dd(state: &mut Tier1State) {
    if state.in_table_cell() {
        return;
    }
    trim_trailing_inline_whitespace(state);
    let buf = state.cell_or_output_mut();
    if buf.is_empty() {
        return;
    }
    if buf.ends_with("\n\n") {
        return;
    }
    if buf.ends_with('\n') {
        buf.push('\n');
    } else {
        buf.push_str("\n\n");
    }
}

fn close_dl(state: &mut Tier1State, frame: &OpenTag) {
    if state.in_table_cell() {
        return;
    }
    let buf = state.cell_or_output_mut();
    // ~keep Empty dl: emit nothing (matches Tier-2 which skips when trimmed content
    // is empty).
    if buf.len() <= frame.content_start {
        return;
    }
    // ~keep Tier-2 trims the dl's accumulated content, so any trailing whitespace
    // from the last dt/dd close should collapse to a single "\n\n" separator.
    while buf.len() > frame.content_start {
        let last = buf.as_bytes()[buf.len() - 1];
        if matches!(last, b' ' | b'\t' | b'\n' | b'\r') {
            buf.pop();
        } else {
            break;
        }
    }
    if buf.len() == frame.content_start {
        return;
    }
    buf.push_str("\n\n");
}

fn close_table(
    state: &mut Tier1State,
    options: &ConversionOptions,
    table_probes: &mut Vec<TableLayoutProbe>,
) -> Result<(), BailReason> {
    // ~keep Pop the table state and (if safe) emit the GFM table to main output.
    let Some(ts) = state.table_stack.pop() else {
        return Ok(());
    };
    // ~keep Popped together with the `TableState` it belongs to; the truncate re-syncs
    // the two stacks if a malformed document ever pushed one without the other.
    let probe = table_probes.pop().unwrap_or_default();
    table_probes.truncate(state.table_stack.len());

    // ~keep Safety checks: ensure Tier-2 would also use the GFM path.
    // ~keep
    // ~keep Tier-2 uses the layout (non-GFM) path when ALL of these hold:
    //   (a) no <th> anywhere in the table, AND
    //   (b) no <caption>, AND
    //   (c) looks_like_layout || is_blank || (row_count<=2 && link_count>=3)
    // ~keep
    // ~keep where (block/table/builder.rs)
    //   looks_like_layout = nested_table_count > 1 || (has_span && has_border_zero)
    // ~keep
    // ~keep Both disjuncts are checked below — neither is unreachable here.
    // An earlier revision of this comment claimed nested tables and
    // colspan/rowspan had "already bailed"; both claims were false (Phase HH
    // renders a nested table inline into the parent cell, and open_table_cell
    // expands colspan instead of bailing), and the resulting gap let Tier-1
    // emit a GFM table for input Tier-2 renders as a bullet list.
    // ~keep
    // ~keep If those conditions could apply to this table, we bail rather than
    // emit a GFM table that Tier-2 would have rendered differently.
    // ~keep
    // ~keep `inconsistent_cols` below is checked in addition to the above, not because
    // Tier-2 treats ragged rows as layout (it no longer does, issue #500 — the
    // regular renderer pads a short row to the table's column count instead,
    // issue #13), but because Tier-1 has no padding logic of its own: bailing on
    // ragged rows is stricter than Tier-2 needs, which stays parity-safe (it only
    // ever sends more input to the fallback) without teaching Tier-1 to pad.
    // ~keep
    // ~keep When a <caption> is present, Tier-2 always takes the GFM path
    // regardless of <th> presence (has_caption short-circuits the layout check).
    let has_caption = ts.caption_text.is_some();
    // One-cell wrappers are unwrapped by Tier-2 to preserve the nested table's
    // structure. Its DOM walker also handles the traversal-depth boundary.
    if !ts.has_th
        && !has_caption
        && !probe.has_span
        && probe.nested_table_count > 0
        && ts.rows.len() == 1
        && ts.first_row_col_count == Some(1)
    {
        return Err(BailReason::TableNestedTable);
    }
    if !ts.has_th && !has_caption {
        // ~keep No <th> and no <caption>: check if Tier-2 would take the layout path.
        let row_count = ts.rows.len();

        // ~keep Inconsistent column counts → Tier-1-only bail (issue #500; see the module
        // comment above `TableLayoutProbe` and the block comment above this function).
        // Compare colspan-expanded column counts (sum of cell colspans per row)
        // because Tier-2 computes column counts post-colspan expansion.
        let expanded_cols = |row: &Vec<(String, u16)>| -> usize { row.iter().map(|(_, c)| usize::from(*c)).sum() };
        let inconsistent_cols = {
            let first = ts.first_row_col_count.unwrap_or(0);
            ts.rows.iter().any(|r| expanded_cols(r) != first)
        };

        // ~keep Link-heavy with few rows → layout table in Tier-2.
        let link_heavy = row_count <= 2 && ts.link_count >= 3;

        // ~keep Blank table → Tier-2 emits nothing (not a bail case).
        let is_blank = ts.rows.is_empty() || ts.rows.iter().all(|r| r.iter().all(|(c, _)| c.trim().is_empty()));

        // ~keep Two or more directly-nested tables → layout table in Tier-2.  Tier-2
        // counts one nesting level only, which is what the probe accumulates.
        let multiple_nested_tables = probe.nested_table_count > 1;

        // ~keep A spanning cell in a `border="0"` table → layout table in Tier-2.  Both
        // halves are mirrored exactly: span = attribute presence, border = the
        // literal value "0" (see open_table_cell / open_table).
        let spanning_borderless = probe.has_span && probe.border_zero;

        if inconsistent_cols || link_heavy || is_blank || multiple_nested_tables || spanning_borderless {
            // ~keep Tier-2 would not emit a GFM table here.  Bail so the fallback
            // produces the correct layout output.  Phase L's full layout
            // emit deferred — needs more careful per-cell content tracking
            // to mirror Tier-2's walker exactly.
            return Err(BailReason::Classifier);
        }
    }
    // ~keep Issue #484: some row in this table (checked only once the whole table is known,
    // see `TableState::had_single_cell_nested_table_row`) closed with exactly one cell
    // holding a nested table, and the table did not already match the more specific
    // one-cell-*wrapper* bail above. Tier-2 defers that row's nested table to a
    // separate GFM table after this one; this scanner has no equivalent deferred-output
    // buffer, so it bails and lets Tier-2 (authoritative) render it.
    if ts.had_single_cell_nested_table_row {
        return Err(BailReason::TableNestedTableInSingleCellRow);
    }
    // ~keep Phase HH: a nested table writes its GFM rendering into the parent
    // cell buffer; the parent's `close_table_cell` then collapses the
    // resulting newlines to spaces.  An outer table writes to the main
    // output buffer as before.
    if ts.inline_mode {
        if let Some(outer) = state.table_stack.last_mut() {
            outer.had_nested_table = true;
        }
        // ~keep Mirrors Tier-2's `nested_table_count`: the enclosing table counts this
        // one, and stops there — tables nested deeper already counted against
        // their own immediate parent when they closed.
        if let Some(outer_probe) = table_probes.last_mut() {
            outer_probe.nested_table_count += 1;
        }
        // ~keep Tier-2's `render_cell_text` (block/table/cell.rs, commit ee77eb2a18)
        // now escapes the bare `|` a nested table's own row/separator syntax
        // leaves behind, rendering the nested table into a scratch buffer and
        // escaping just that fragment before appending it to the outer cell.
        // Left unescaped, those pipes read as *outer-row* cell boundaries on
        // reparse and GFM truncates the row, silently dropping the inner
        // cells — genuine content loss, not a cosmetic difference. Mirror the
        // same scratch-buffer-then-escape shape here rather than escaping the
        // whole outer cell buffer, so any literal text already accumulated
        // alongside the nested table in the same cell is left untouched.
        let mut nested = String::new();
        emit_gfm_table(&mut nested, ts);
        if nested.contains('|') {
            nested = crate::converter::utility::escaping::escape_bare_pipes_outside_code_spans(&nested);
        }
        // ~keep Mirrors Tier-2's `fold_nested_table_rows` (block/table/cell.rs, issue #469):
        // the inner rows are joined with `<br>` under `br_in_tables` and a space
        // otherwise, so `close_table_cell`'s unconditional newline fold has nothing left
        // to flatten and both tiers spell the boundary the same way.
        let nested = crate::converter::block::table::cell::fold_nested_table_rows(&nested, options.br_in_tables);
        let write_nested = |dest: &mut String| {
            if !nested.is_empty() && !dest.trim_end().is_empty() {
                crate::converter::main_helpers::emit_table_cell_break(dest, options.br_in_tables);
            }
            dest.push_str(&nested);
        };
        // ~keep Tier-2 separates the cell's child that holds the table from the whole cell
        // ~keep before it, but a quote, heading or code block around the table separates
        // ~keep itself when it closes, so the table breaks only inside that block.
        let in_block = state
            .stack
            .iter()
            .rev()
            .take_while(|frame| !matches!(frame.spec.kind, TagKind::TableCell { .. }))
            .any(|frame| {
                matches!(
                    frame.spec.kind,
                    TagKind::Blockquote | TagKind::Heading(_) | TagKind::Pre
                )
            });
        if in_block {
            with_cell_scratch(state, write_nested);
        } else {
            write_nested(state.cell_or_output_mut());
        }
    } else {
        emit_gfm_table(&mut state.output, ts);
    }
    Ok(())
}

fn close_table_head(state: &mut Tier1State) {
    if let Some(ts) = state.table_stack.last_mut() {
        ts.in_thead = false;
    }
}

fn close_table_body(state: &mut Tier1State) {
    if let Some(ts) = state.table_stack.last_mut() {
        ts.seen_tbody_close = true;
    }
}

/// Finalise a `<caption>` element.
///
/// Mirrors Tier-2's `builder.rs` caption handling: trim the collected text,
/// replace `-` with `\-` to prevent Markdown table-separator interpretation,
/// and store the result in `ts.caption_text` for emission before the table body.
fn close_table_caption(state: &mut Tier1State) {
    let Some(ts) = state.table_stack.last_mut() else {
        return;
    };
    ts.in_caption = false;
    let raw = std::mem::take(&mut ts.caption_buf);
    let trimmed = raw.trim();
    if !trimmed.is_empty() {
        ts.caption_text = Some(trimmed.replace('-', r"\-"));
    }
}

fn close_table_row(state: &mut Tier1State) {
    let Some(ts) = state.table_stack.last_mut() else {
        return;
    };
    if ts.current_row.is_empty() {
        return;
    }
    // ~keep Issue #484: record (rather than bail immediately) that this row's sole cell
    // held a nested table — `close_table` has seen every row and decides whether
    // the more specific one-cell-*wrapper* bail applies first. See
    // `TableState::had_single_cell_nested_table_row`.
    if ts.pending_single_cell_nested_table && ts.current_row.len() == 1 {
        ts.had_single_cell_nested_table_row = true;
    }
    ts.pending_single_cell_nested_table = false;
    // ~keep Track first-row column count for consistency checking — use the
    // colspan-expanded count so Tier-2's heuristic compares the same numbers.
    let col_count: usize = ts.current_row.iter().map(|(_, c)| usize::from(*c)).sum();
    if ts.first_row_col_count.is_none() {
        ts.first_row_col_count = Some(col_count);
    }
    let row = std::mem::take(&mut ts.current_row);
    ts.rows.push(row);
}

/// Close a table cell (`<td>` or `<th>`).
///
/// `is_implicit` skips the pipe-escape bail that only applies when the cell
/// was explicitly closed (implicit closes happen during row/table teardown
/// where we've already committed to the data we have).
fn close_table_cell(state: &mut Tier1State, is_implicit: bool) -> Result<(), BailReason> {
    let Some(ts) = state.table_stack.last_mut() else {
        return Ok(());
    };
    ts.in_cell = false;
    // ~keep Trim the accumulated cell text (matches Tier-2 `text.trim()`).
    let cell_text_raw = ts.current_cell.trim().to_owned();
    // ~keep Replace newlines with spaces — mirrors Tier-2's `cell_text_content`
    // which calls `text.replace('\n', " ")` when `br_in_tables` is false.
    // `<br>` itself is handled at emission time (see `TagKind::LineBreak`
    // in `emit_void`), so no sentinel expansion is needed here.
    let cell_text = if cell_text_raw.contains('\n') {
        cell_text_raw.replace('\n', " ")
    } else {
        cell_text_raw
    };
    let cell_text = cell_text.trim().to_owned();
    // ~keep Bail if the cell contains a pipe: Tier-2 escapes `|` → `\|`
    // which changes the cell width computation; Tier-1 does not
    // implement pipe escaping.  Implicit closes skip this check because
    // they are triggered during structural teardown, not fresh cell data.
    // ~keep
    // ~keep Phase HH exception: when a nested table emitted GFM markdown into this
    // cell, the pipes were already escaped (`|` -> `\|`) by the nested-table
    // close path above -- see `escape_bare_pipes_outside_code_spans` -- so
    // `cell_text` still literally contains `|` bytes (an escaped pipe is still
    // two bytes, one of them `|`) even though Tier-2 no longer emits a bare
    // one here either (commit ee77eb2a18). `had_nested_table` gates the skip;
    // reset it so subsequent cells in the same row are still pipe-checked.
    let allow_pipes = ts.had_nested_table;
    ts.had_nested_table = false;
    if !is_implicit && !allow_pipes && cell_text.contains('|') {
        return Err(BailReason::TableBlockChildInCell);
    }
    // ~keep Track whether this row is (so far) a single cell that held a nested table —
    // see `TableState::pending_single_cell_nested_table`. Only the row's FIRST cell
    // can set it; any later cell proves the row has a sibling and clears it,
    // regardless of whether that later cell itself had a nested table.
    ts.pending_single_cell_nested_table = allow_pipes && ts.current_row.is_empty();
    // ~keep Phase L-prep: store (text, colspan) so emit_gfm_table can mirror
    // Tier-2's `for _ in 0..colspan { output.push_str(" |") }` (cell.rs:248)
    // and the layout-heuristic uses the colspan-expanded column count.
    let colspan = ts.current_cell_colspan;
    ts.current_row.push((cell_text, colspan));
    ts.current_cell.clear();
    ts.current_cell_colspan = 1;
    Ok(())
}

/// Flush a raw HTML text segment into the output (or current cell buffer),
/// decoding entities and collapsing whitespace (unless inside `<pre>`).
///
/// `base_offset` is the byte offset of `raw` within the original HTML input;
/// it is forwarded to the entity decoder so that `BailReason::UnknownEntity`
/// carries an accurate position.
///
/// Returns `Err(BailReason::UnknownEntity)` if an unrecognised entity is found.
/// True when `s` ends with an ordered-list marker (`<digit(s)>. ` or `<digit(s)>) `).
///
/// Used by the inter-block whitespace strip to recognise that the scanner just
/// emitted a list-item marker and the next text would be the item content;
/// leading whitespace from the source HTML indentation should be dropped.
fn ends_with_ordered_marker(s: &str) -> bool {
    let bytes = s.as_bytes();
    let len = bytes.len();
    if len < 3 || bytes[len - 1] != b' ' {
        return false;
    }
    let punct = bytes[len - 2];
    if punct != b'.' && punct != b')' {
        return false;
    }
    let mut i = len - 2;
    while i > 0 && bytes[i - 1].is_ascii_digit() {
        i -= 1;
    }
    i < len - 2 && (i == 0 || !bytes[i - 1].is_ascii_digit())
}

/// Returns `true` when the output tail is an explicit inline-element close
/// marker emitted by Tier-1.  These markers signal that the next whitespace
/// text node is between two inline siblings and should collapse to a single
/// space — even when the whitespace run contains a newline (Phase U-2).
///
/// Recognised markers:
/// - `**` — `</strong>` / `</b>` close
/// - `*` — `</em>` / `</i>` close (only a lone `*`, not part of `**`)
/// - `` ` `` — `</code>` close
/// - `)` — `</a>` (link) close, e.g. `](href)`
///
/// Block edges (`\n`, empty output, trailing space) are explicitly excluded.
fn output_ends_with_inline_close_marker(output: &str) -> bool {
    if output.is_empty() || output.ends_with('\n') || output.ends_with(' ') || output.ends_with('\t') {
        return false;
    }
    if output.ends_with("**") || output.ends_with('`') || output.ends_with(')') {
        return true;
    }
    output.ends_with('*') && !output.ends_with("**")
}

/// Returns `true` when the output tail is a non-marker text character —
/// e.g. ending in a letter, digit, or punctuation other than the inline-
/// close markers.  Text-tail preservation only fires for *horizontal*
/// whitespace runs (no `\n`/`\r`) because we cannot tell at flush time
/// whether the next tag is inline or block; preserving a space across a
/// newline-bearing run risks `text \n\n<list>` regressions.
fn output_ends_with_inline_text(output: &str) -> bool {
    if output.is_empty() || output.ends_with('\n') || output.ends_with(' ') || output.ends_with('\t') {
        return false;
    }
    !output_ends_with_inline_close_marker(output)
}

/// Start a new paragraph for inline content that directly follows a block whose output ends with
/// a single line break (a list, a table, `<hr>`), so it does not continue the block's last line
/// (issues #570, #571). In a table cell the cell break separates it instead (issue #645).
/// Mirrors Tier-2's `separate_from_block` in `walk_node`.
fn separate_inline_after_block(state: &mut Tier1State, br_in_tables: bool) -> Result<(), BailReason> {
    // ~keep `<pre>` sets the CODE bit too, so one test covers code spans and code blocks.
    if state.escape_ctx.contains(EscapeCtx::CODE) {
        return Ok(());
    }
    // ~keep A block in a cell ends with no line end: the cell break separates (issue #645).
    if state.in_table_cell() {
        let at = state.cell_or_output_mut().len();
        separate_block_in_cell_at(state, at, br_in_tables);
        return Ok(());
    }
    // ~keep Inside a list item Tier-2 starts it at the item's content column after a blank
    // ~keep line (issue #583); see `BailReason::ListItemUnsupportedBlockChild`.
    if state.list_continuation_indent_width() > 0 && !inside_stray_definition(state) {
        return Err(BailReason::ListItemUnsupportedBlockChild);
    }
    if state.list_depth > 0 {
        return Ok(());
    }
    let dest = state.cell_or_output_mut();
    if dest.len() > 1 && dest.ends_with('\n') && !dest.ends_with("\n\n") {
        dest.push('\n');
    }
    Ok(())
}

/// Whether a heading is open inside the current table cell.
fn in_heading(state: &Tier1State) -> bool {
    state
        .stack
        .iter()
        .rev()
        .take_while(|frame| !matches!(frame.spec.kind, TagKind::TableCell { .. }))
        .any(|frame| matches!(frame.spec.kind, TagKind::Heading(_)))
}

/// Tier-2's inline-element test, which decides what counts as inline content after a block.
fn is_inline_tag(name_lower: &[u8]) -> bool {
    std::str::from_utf8(name_lower).is_ok_and(crate::converter::main_helpers::is_inline_element)
}

/// Tier-2's block-level test, which decides what counts as the block before inline content.
fn is_block_tag(name_lower: &[u8]) -> bool {
    std::str::from_utf8(name_lower).is_ok_and(crate::converter::utility::content::is_block_level_element)
}

fn flush_text(
    state: &mut Tier1State,
    raw: &str,
    base_offset: usize,
    next_tag_is_list: bool,
    next_tag_is_img: bool,
    next_tag_is_span: bool,
    br_in_tables: bool,
) -> Result<(), BailReason> {
    if raw.is_empty() {
        return Ok(());
    }

    // ~keep Read-then-clear: this text flush is the only event that can be the
    // "next scanner event" after a custom-element close for the purposes
    // of the boundary check below (see the field's doc comment).
    let after_custom_element_close = state.last_closed_custom_element;
    state.last_closed_custom_element = false;
    // ~keep Same read-then-clear convention, for the "previous direct sibling
    // was an <img>" half of the adjacent-images check below.
    let after_img = state.last_emitted_was_img;
    state.last_emitted_was_img = false;

    // ~keep Inside a table but outside a cell or caption: whitespace between
    // structural tags (`<table>...<tr>`, `<tr>...<td>`) is insignificant and
    // silently dropped here, matching Tier-2 (which processes only tag
    // children of a table and never walks a stray whitespace text node).
    // Caption content is the exception — Tier-2 walks caption children and
    // accumulates their text into the caption output.
    //
    // ~keep Non-whitespace text at this position is HTML5 "foster parented"
    // content: the real parsing algorithm relocates it to just before the
    // `<table>` element rather than dropping it. Tier-2's own DOM (built by
    // `tl`, not a full HTML5 tree-construction implementation) only
    // sometimes surfaces it there — empirically, it depends on adjacency to
    // a `<!--comment-->` in a way this single-pass byte scanner cannot
    // reproduce byte-for-byte without a second pass over the table's
    // contents. Bail instead of silently discarding real content (the
    // original defect here): Tier-2's fallback renders whatever the true
    // answer is. `raw.trim().is_empty()` is the same "is this
    // insignificant" test already used everywhere else in this function,
    // so a decoded whitespace-only entity run (e.g. `&nbsp;` alone) is
    // treated as non-whitespace and bails too — overly conservative, but
    // never wrong, and rare enough in practice to not matter.
    if !state.table_stack.is_empty() && !state.in_table_cell() && !state.in_table_caption() {
        if raw.trim().is_empty() {
            return Ok(());
        }
        return Err(BailReason::Classifier);
    }

    // ~keep Whitespace-only text between a block and the content after it keeps the window open.
    // ~keep In a cell without `br_in_tables` a text's leading space is the break (issue #645).
    // ~keep Tier-2 breaks the cell line before text after a block in a heading; this scanner does not.
    if !raw.trim().is_empty() && state.last_closed_block && state.in_table_cell() && in_heading(state) {
        return Err(BailReason::TableBlockChildInCell);
    }
    if !raw.trim().is_empty()
        && std::mem::take(&mut state.last_closed_block)
        && (br_in_tables || !state.in_table_cell() || !raw.as_bytes().first().is_some_and(u8::is_ascii_whitespace))
    {
        separate_inline_after_block(state, br_in_tables)?;
    }

    let in_pre = state.escape_ctx.contains(EscapeCtx::PRE);
    // ~keep Phase EE: inside `<code>` text is verbatim — Tier-2's handle_code
    // walks children and pushes their text without normalize_whitespace,
    // so `\n` and runs of spaces inside `<code>` survive into the
    // wrapped span.  Treat as `in_pre` for the no-collapse path.
    let in_code = state.escape_ctx.contains(EscapeCtx::CODE);

    // ~keep Phase NN: text containing Unicode whitespace (NBSP `\u{00A0}`, hair
    // space `\u{200A}`, etc., or their entity forms) folds those to ASCII
    // space — but only when the chunk has non-whitespace content.
    // Mirrors Tier-2 `text_node.rs:124` and `:154` which run
    // `normalize_whitespace_cow` on text outside `<code>`/`<pre>` (folding
    // Unicode space chars).  The whitespace-only branch at `:80-112`
    // preserves a pure-NBSP text node between inline siblings as-is (e.g.
    // `<a>X</a>&nbsp;<a>Y</a>` keeps the NBSP).  Without this rule,
    // `First<NBSP>appeared` reaches the buffer verbatim where Tier-2 outputs
    // `First appeared`.
    // Common Unicode-whitespace entity forms: named + numeric (decimal +
    // hex).  Tier-2's `normalize_whitespace_cow` folds the decoded chars;
    // Tier-1's flush_text runs BEFORE entity decode, so the patterns must
    // be listed explicitly.
    const UNICODE_WS_ENTITIES: &[&str] = &[
        "&nbsp;", "&#160;", "&#xa0;", "&#xA0;", "&ensp;", "&#8194;", "&#x2002;", "&emsp;", "&#8195;", "&#x2003;",
        "&thinsp;", "&#8201;", "&#x2009;", "&hairsp;", "&#8202;", "&#x200a;", "&#x200A;",
    ];
    let raw_owned_nbsp;
    let raw: &str = if !in_pre && !in_code {
        let has_ws_entity = UNICODE_WS_ENTITIES.iter().any(|p| raw.contains(p));
        let has_unicode_ws_literal = raw.bytes().any(|b| b >= 0x80)
            && raw
                .chars()
                .any(|c| c.is_whitespace() && c != ' ' && c != '\t' && c != '\n' && c != '\r');
        if has_ws_entity || has_unicode_ws_literal {
            let mut stripped = raw.to_owned();
            for p in UNICODE_WS_ENTITIES {
                if stripped.contains(p) {
                    stripped = stripped.replace(p, "");
                }
            }
            let is_logically_whitespace = stripped.chars().all(char::is_whitespace);
            if is_logically_whitespace {
                raw
            } else {
                let mut after_entities = raw.to_owned();
                for p in UNICODE_WS_ENTITIES {
                    if after_entities.contains(p) {
                        after_entities = after_entities.replace(p, " ");
                    }
                }
                let mut tmp = String::with_capacity(after_entities.len());
                for c in after_entities.chars() {
                    if c.is_whitespace() && c != ' ' && c != '\t' && c != '\n' && c != '\r' {
                        tmp.push(' ');
                    } else {
                        tmp.push(c);
                    }
                }
                raw_owned_nbsp = tmp;
                raw_owned_nbsp.as_str()
            }
        } else {
            raw
        }
    } else {
        raw
    };

    // ~keep Inter-block whitespace strip: in a block-edge context (output empty,
    // ends with a newline, or ends with a list-item marker like "- " /
    // "1. "), whitespace-only text between adjacent elements (the
    // indentation in pretty-printed HTML) is not meaningful and must be
    // discarded.  Tier-2's DOM walker gets this for free because the
    // parser yields text nodes separately from tag nodes and the walker
    // skips whitespace-only text at block-level boundaries.  Skipped when
    // inside `<pre>` (verbatim) or inside a table cell (caller is
    // accumulating cell text).
    // ~keep
    // ~keep We also treat "the current open frame is a link/emphasis frame whose
    // body is still empty" as a block-edge: text appearing immediately
    // after `<a>` → `[`, `<strong>` → `**`, etc. inherits leading
    // whitespace from the source HTML's indentation and Tier-2 trims it
    // when building the inline label.  This catches cases like
    // `<a href>\n   <span>EN</span>\n</a>` where the whitespace after
    // `<a>` would otherwise leak into the link label as `[ EN]`.
    // ~keep
    // ~keep Plain `<p>`/`<div>`/`<h1>` frames are NOT in this set — Tier-2 keeps
    // the leading whitespace inside the very first paragraph of a document
    // (it becomes the single space after `normalize_whitespace`).  Only
    // post-content paragraphs see "\n\n" before them, which the
    // `output.ends_with('\n')` check above already handles.
    // Phase R-3: inside `<summary>`, any tag's body-start is also an inline
    // frame edge.  Tier-2's handle_summary collects all children with
    // text-normalization in effect; leading whitespace inside `<span>`,
    // `<div>`, `<p>` (etc.) bodies gets stripped just like inside `<a>`.
    let in_summary_snapshot = state.in_summary();
    let at_inline_frame_start = match state.stack.last() {
        Some(frame) => {
            let cs = frame.content_start;
            let kind = frame.spec.kind;
            let buf_len = state.cell_or_output_mut().len();
            cs >= buf_len
                && (matches!(
                    kind,
                    TagKind::Link | TagKind::Strong | TagKind::Emphasis | TagKind::Code
                ) || (in_summary_snapshot
                    && matches!(
                        kind,
                        TagKind::Inline | TagKind::Block | TagKind::Paragraph | TagKind::Heading(_)
                    )))
        }
        None => false,
    };
    // ~keep Determine whether the current active output position is at a "block
    // edge" (empty or after a newline / list marker).  When inside a summary
    // accumulation buffer, consult that buffer rather than state.output so
    // that inter-element spaces inside the summary are preserved correctly.
    // Snap the relevant properties to local booleans before releasing the
    // borrow to avoid conflicts with subsequent state reads.
    let (active_empty, active_ends_newline, active_ends_list_marker, active_ends_ordered) = {
        let buf: &str = state.cell_or_output_mut();
        (
            buf.is_empty(),
            buf.ends_with('\n'),
            buf.ends_with("- ") || buf.ends_with("* ") || buf.ends_with("+ "),
            ends_with_ordered_marker(buf),
        )
    };
    let is_block_edge =
        active_empty || active_ends_newline || active_ends_list_marker || active_ends_ordered || at_inline_frame_start;
    let raw_is_whitespace = raw.bytes().all(|b| b == b' ' || b == b'\t' || b == b'\n' || b == b'\r');
    // ~keep Tier-2's `was_fresh_block_start` check (text_node.rs:99) runs BEFORE
    // any other whitespace-only-node disposition and takes absolute
    // priority: at document start, a whitespace-only text node is DROPPED
    // outright, even when the surrounding context (e.g. between two
    // `<img>` tags' emitted Markdown and a following inline element) would
    // otherwise call for a single separating space. This matters because
    // `<img>` — like any non-text content — never flips
    // `Tier1State::at_document_start`, so it stays true across leading
    // images the way Tier-2's flag stays true across a leading `<img>`
    // (image handling never touches `at_fresh_block_start` either).
    // Excluded from table cells and list items, matching Tier-2's
    // `!ctx.in_table_cell && !ctx.in_list_item` guard — those have their
    // own dedicated whitespace handling below. Also excluded inside a
    // heading: Tier-2's heading handler is a separate, allow-listed
    // divergence (flattens a heading's `<img>` to bare alt text instead
    // of Markdown image syntax) that assembles its line outside the
    // generic text-node/`at_fresh_block_start` pipeline this mirrors, so
    // it always keeps a real separating space after that alt text —
    // applying this rule there would additionally drop that space and
    // compound one known divergence with a new one.
    let in_list_item_frame_for_ws = state
        .stack
        .iter()
        .any(|frame| matches!(frame.spec.kind, TagKind::ListItem));
    let document_start_drops_ws = state.at_document_start
        && !state.in_table_cell()
        && !in_list_item_frame_for_ws
        && !state.escape_ctx.contains(EscapeCtx::HEADING);
    if !in_pre && (is_block_edge || document_start_drops_ws) && raw_is_whitespace {
        // ~keep issue #481: record that a whitespace-only text node was dropped right at
        // this Strong/Emphasis frame's own content start, BEFORE it disappears —
        // `close_inline_marker` cannot tell a genuinely empty `<em></em>` apart from
        // a whitespace-only `<em> </em>` from buffer bytes alone once this drop has
        // already erased them (see `OpenTag::dropped_whitespace_only_text`'s doc
        // comment). Harmless when more real content follows this same drop (e.g.
        // `<em> <b>x</b></em>`): the frame's body ends up non-empty regardless, so
        // `close_inline_marker` never consults the flag in that case.
        if at_inline_frame_start {
            if let Some(frame) = state.stack.last_mut() {
                // ~keep Strikethrough/Inserted/Code joined Strong/Emphasis here once Tier-2's
                // shared `emit_wrapped_inline` started preserving the separator (and, for
                // Code, the span) that a whitespace-only body stands for.
                if matches!(
                    frame.spec.kind,
                    TagKind::Strong | TagKind::Emphasis | TagKind::Strikethrough | TagKind::Inserted | TagKind::Code
                ) {
                    frame.dropped_whitespace_only_text = true;
                }
            }
        }
        // ~keep Drop block-edge whitespace anywhere — including inside table cells.
        // A cell-open `<td>`/`<th>` produces a fresh empty buffer; the
        // pretty-printer's inter-tag whitespace before the first child would
        // otherwise leak as a leading space into the cell, breaking the
        // 3-space gap heuristic (`  \n` from `<div>` open becomes 4 spaces
        // instead of 3 after `replace('\n', ' ')`).
        return Ok(());
    }
    // ~keep Tier-2 text_node.rs:100-113 collapses whitespace-only text nodes
    // between adjacent inline siblings to a single space — including
    // inside table cells where the surrounding `<a>`/`<span>` siblings are
    // inline.  Mirror that here so `<a>x</a>\n  <a>y</a>` inside a `<td>`
    // emits `[x] [y]` (single space) instead of `[x]\n [y]` which the
    // cell-close `replace('\n', ' ')` would turn into two spaces.  Skip
    // when at a block edge (cell just opened) so the cell doesn't start
    // with a stray space.
    if !in_pre && state.in_table_cell() && raw_is_whitespace && !is_block_edge {
        // ~keep Tier-2's text_node.rs:80-98 drops whitespace text between non-inline
        // siblings: when the parent is a list (`<ul>`/`<ol>`/`<dl>`), the
        // inter-`<li>` whitespace returns without pushing because the next
        // sibling `<li>` is a block, not inline.  Mirror that here so adjacent
        // `<li>` siblings in a cell concatenate without separation
        // (`[v](u1)[t](u2)` not `[v](u1) [t](u2)`).  For inline parents
        // (`<span>`/`<a>`/`<td>` direct inline-sibling case), keep the
        // single-space fold.
        if matches!(state.stack.last().map(|f| f.spec.kind), Some(TagKind::List(_))) {
            return Ok(());
        }
        // ~keep Tier-2 keeps whitespace at the start of the own buffer of a quote or heading. Mark
        // ~keep the element, so its close leaves the cell to Tier-2 if content follows.
        let cell_len = state.cell_or_output_mut().len();
        if let Some(frame) = state
            .stack
            .iter_mut()
            .rev()
            .take_while(|frame| !matches!(frame.spec.kind, TagKind::TableCell { .. } | TagKind::Summary))
            .find(|frame| frame.own_buffer)
            .filter(|frame| matches!(frame.spec.kind, TagKind::Blockquote | TagKind::Heading(_)))
            .filter(|frame| frame.content_start == cell_len)
        {
            frame.starts_with_whitespace = true;
        }
        let dest = state.cell_or_output_mut();
        // ~keep `after_custom_element_close` overrides the usual "already ends
        // with a space, skip" dedup — see `Tier1State::last_closed_custom_element`.
        if !dest.is_empty() && !dest.ends_with('\n') && (after_custom_element_close || !dest.ends_with(' ')) {
            dest.push(' ');
        }
        return Ok(());
    }
    // ~keep Whitespace-only text outside any inline element (link / strong / em /
    // code) and outside `<pre>` / table cells is structural indentation
    // between block siblings (e.g. between `</div>` and the next `<div>`).
    // Tier-2 emits a single ASCII space here when the surrounding context
    // is inline, but otherwise the DOM walker treats it as a no-op.  For
    // Tier-1's heuristic we collapse it to nothing — matches Tier-2 for
    // the common block-between-blocks case and the inline cases are caught
    // by the inline-frame check above.
    // ~keep
    // ~keep Exception (Phase U + U-2): when the output tail is inline content
    // (text or `**`/`*`/`` ` ``/`)` close markers) AND we're NOT at a
    // block edge, a whitespace-only text node between siblings must
    // become a single space.  Without this `</strong> <em>` would emit
    // `**a***b*` and `<span>Open Search Bar</span>\n<button>` would lose
    // the space before the button's content.
    // ~keep
    // ~keep Phase U-2 dropped the original "horizontal whitespace only" guard:
    // a newline-bearing whitespace run between two inline siblings still
    // collapses to a single space in Tier-2.  The "what if next tag is a
    // block?" regression is now handled later in `ensure_blank_line` and
    // `close_block_container`, which trim trailing horizontal whitespace
    // before emitting `\n\n`.
    if !in_pre && !state.in_table_cell() && raw_is_whitespace {
        // ~keep When inside a <summary> accumulation buffer, treat the context as
        // inline (like strong/emphasis): inter-element spaces must be
        // preserved so `<span>a</span> <span>b</span>` collects "a b" not "ab".
        let inside_inline = state.in_summary()
            || state.stack.iter().any(|frame| {
                matches!(
                    frame.spec.kind,
                    TagKind::Link | TagKind::Strong | TagKind::Emphasis | TagKind::Code
                )
            });
        if !inside_inline {
            // ~keep Tier-2's `paragraph.rs` skips a whitespace-only text node
            // OUTRIGHT (not deduped to a space, DROPPED) when it sits directly
            // between two "empty inline" siblings that are both direct
            // children of the same `<p>` — scoped here to the `<img>`/`<img>`
            // case the allow-listed divergence was keyed on (`is_empty_inline_element`
            // also covers `br`/`hr`/`input`, but those combinations are
            // unverified and out of scope). `state.stack.last()` being
            // `Paragraph` mirrors walking the `<p>`'s OWN direct children —
            // an intervening wrapper tag would put something else on top.
            let in_direct_paragraph = matches!(
                state.stack.last().map(|frame| frame.spec.kind),
                Some(TagKind::Paragraph)
            );
            if in_direct_paragraph && after_img && next_tag_is_img {
                return Ok(());
            }
            // ~keep Use the active buffer (summary buf or main output) for the
            // tail check so spaces between adjacent inline elements inside
            // a summary are preserved correctly.
            let active_tail: &str = state.cell_or_output_mut();
            // ~keep `after_custom_element_close` overrides the tail-already-has-
            // content requirement below — see
            // `Tier1State::last_closed_custom_element`.
            if output_ends_with_inline_close_marker(active_tail)
                || output_ends_with_inline_text(active_tail)
                || (after_custom_element_close && !active_tail.is_empty() && !active_tail.ends_with('\n'))
            {
                let dest = state.cell_or_output_mut();
                if next_tag_is_list && raw.contains('\n') {
                    // ~keep Tier-2's text_node.rs branches BEFORE the previous/next-
                    // sibling check above when the whitespace run itself
                    // contains a newline (`had_newlines`): with a non-inline
                    // next sibling (`<ul>`/`<ol>`), that branch drops the run
                    // entirely rather than collapsing or preserving it. Push
                    // nothing here to match.
                } else if next_tag_is_list {
                    // ~keep Tier-2's text_node.rs pushes a whitespace-only text node
                    // VERBATIM (not collapsed) whenever the next sibling isn't
                    // inline — see `previous_sibling_is_inline_tag(...) &&
                    // next_sibling_is_inline_tag(...)`, false here since `<ul>`/
                    // `<ol>` are block. That raw tail then feeds
                    // `add_list_leading_separator`'s literal `ends_with("* "|
                    // "- "|". ")` check (list/utils.rs), which only
                    // false-negatives (collides with a bullet marker, skipping
                    // the separator) when the run is EXACTLY one space —
                    // collapsing here to a single space unconditionally would
                    // manufacture that collision for runs that never had it.
                    dest.push_str(raw);
                } else {
                    dest.push(' ');
                }
            }
            return Ok(());
        }
        // ~keep Inside an inline frame (`<a>`/`<strong>`/`<em>`/`<code>`) or summary
        // accumulation: a whitespace-only text node (often the indent run
        // between two inline siblings like `</span>\n  <a>`) must collapse to
        // a single ASCII space — Tier-2's text-node normalize_whitespace folds
        // any `\n` + spaces run into one space.  Without this, Tier-1 falls
        // through to `decode_and_collapse_into` which preserves the `\n` and
        // emits `*[a](x)\n [b](y)*` where Tier-2 has `*[a](x) [b](y)*`.
        let active_tail: &str = state.cell_or_output_mut();
        if !active_tail.is_empty() && !active_tail.ends_with(' ') && !active_tail.ends_with('\n') {
            let dest = state.cell_or_output_mut();
            dest.push(' ');
        }
        return Ok(());
    }
    // ~keep Snapshot-then-flip: reached only once `raw` is known to carry real
    // (non-whitespace) content — every earlier branch above either
    // returns early or is gated on `raw_is_whitespace`. This is the one
    // true "does real content already precede this text node, anywhere
    // in the document" signal, mirroring Tier-2's
    // `Context::at_fresh_block_start` (see `Tier1State::at_document_start`'s
    // doc comment for why buffer emptiness can't stand in for it).
    let was_at_document_start = state.at_document_start;
    state.at_document_start = false;
    // ~keep CommonMark 4.8: leading whitespace at the very start of the
    // document is insignificant — mirrors Tier-2's `was_fresh_block_start`
    // exclusion of table cells and list items (which have their own
    // dedicated whitespace handling reached via `block_separator_after`
    // and the table-cell gate below). Also excluded inside a heading:
    // Tier-2's heading handler is a separate, allow-listed divergence
    // (flattens a heading's `<img>` to bare alt text instead of
    // Markdown image syntax) that assembles its line outside the
    // generic text-node/`at_fresh_block_start` pipeline this mirrors, so
    // it always keeps the real space between that alt text and
    // following prose — stripping it here would additionally drop that
    // space and compound one known divergence with a new one.
    let in_list_item_frame = state
        .stack
        .iter()
        .any(|frame| matches!(frame.spec.kind, TagKind::ListItem));
    let document_start_strip = was_at_document_start
        && !state.in_table_cell()
        && !in_list_item_frame
        && !state.escape_ctx.contains(EscapeCtx::HEADING);
    // ~keep Even when the text is not entirely whitespace, strip its LEADING
    // whitespace when:
    //   - we're at the start of an open inline element's body (`<a>`,
    //     `<strong>`, etc.), OR
    //   - the output ends with a block separator (`\n\n`) or a list-item
    //     marker — Tier-2's text-node `skip_prefix` logic does the same, OR
    //   - we're at the very start of the document (see
    //     `document_start_strip` above).
    let block_separator_after = {
        let active: &str = state.cell_or_output_mut();
        active.ends_with("\n\n")
            || active.ends_with("- ")
            || active.ends_with("* ")
            || active.ends_with("+ ")
            || ends_with_ordered_marker(active)
    };
    // ~keep When the leading run being stripped below sits at the very start of a
    // `<strong>`/`<em>` body specifically (not `<a>`/`<code>`, and not the
    // summary-accumulation kinds handled by `at_inline_frame_start`'s other
    // arm), Tier-2's `chomp_inline` (utility/content.rs) does not delete
    // that whitespace: it collapses the run to a single ASCII space that
    // `close_inline_marker` then migrates outside the opening marker.
    // Deleting it outright — correct for `<a>` (`normalize_link_label`
    // really does trim) and left as-is for `<code>` (fully verbatim,
    // handled separately) — would make `<em>&nbsp;x</em>` render `*x*`
    // instead of Tier-2's ` *x*`. Push one space into the buffer here so
    // `close_inline_marker`'s existing leading-migration block (added
    // alongside its trailing counterpart) has something to move.
    // At document start there is nothing to migrate the space onto —
    // Tier-2's `skip_prefix` drops the prefix outright rather than
    // collapsing it to a space (`<em>&nbsp;x</em>` alone renders `*x*`,
    // not ` *x*`), so `document_start_strip` suppresses the migration.
    let leading_ws_migrates_out = at_inline_frame_start
        && !document_start_strip
        && matches!(
            state.stack.last().map(|frame| frame.spec.kind),
            Some(TagKind::Strong | TagKind::Emphasis)
        );
    // ~keep The `!state.in_table_cell()` gate below exists for the general
    // block_separator_after case (a cell has no block separators to
    // speak of). But Tier-2's `normalize_link_label` trims a link label's
    // leading whitespace unconditionally, in a cell or not — so an `<a>`
    // frame must bypass the gate, or `<td><a> x</a></td>` keeps the space
    // Tier-2 trims (`[ x](...)` instead of `[x](...)`).
    let in_link_frame = matches!(state.stack.last().map(|frame| frame.spec.kind), Some(TagKind::Link));
    // ~keep Tier-2's `process_text_node` (`text_node.rs`) drops a text node's leading
    // whitespace run whenever `output.ends_with('\n') && prefix == " "` — one of
    // several `skip_prefix` conditions, and unlike the others it is not limited
    // to a double newline. The usual source of that bare `\n` is a hard break, inside
    // a link (`<a>foo<br> bar</a>`) or not (`a<br> b`): right after it, the next
    // line's leading space must not survive, or Tier-1 emits `[foo  \n bar]` and
    // `a  \n b` where Tier-2 emits `[foo  \nbar]` and `a  \nb`. Tier-2's `output` is the
    // element's own buffer when the text is the first content of an element Tier-2 renders
    // into a fresh buffer (`a<br><sup> 1</sup>` keeps ` 1`), so the line end does not count
    // there -- the same "nothing written into the frame yet" test as the bare-inline rule below.
    let active_len = state.cell_or_output_mut().len();
    let opens_own_buffer = state
        .stack
        .iter()
        .rev()
        .take_while(|frame| frame.content_start >= active_len)
        .any(|frame| frame.children_in_own_buffer);
    let after_line_end = !opens_own_buffer && state.cell_or_output_mut().ends_with('\n');
    // ~keep Distinct from `at_inline_frame_start` above (whose unconditional strip is reserved
    // for Link/Strong/Emphasis/Code -- kinds with their own always-on trim wrapper in
    // Tier-2: link-label normalization, `chomp_inline`'s marker migration, code's verbatim
    // path). A bare inline element (`<span>`, `<u>`, `<mark>`, ... -- `TagKind::Inline`) has
    // none of those; its children flow through the exact same generic per-text-node path as
    // top-level prose, so Tier-2's `skip_prefix` (text_node.rs) only drops THIS text node's
    // leading whitespace when its own specific condition holds: `output.ends_with(' ') &&
    // prefix == " " && !previous_sibling_is_inline_tag(...)`. This text node is the very
    // first content written into the current frame (the same "nothing emitted yet" proxy
    // `at_inline_frame_start` uses for "no previous sibling"), so that last clause is
    // trivially true here; only `output.ends_with(' ')` needs checking. `prefix == " "` is
    // implicit in the trim below only firing when `raw` actually starts with ASCII
    // whitespace, which is exactly when Tier-2's `chomp` produces `prefix == " "`.
    // Confirmed empirically against Tier-2: `<span>with </span>\n  <span> more</span>` (a
    // whitespace-only sibling between the spans already pushed a separating space) collapses
    // the second span's own leading space away, but `<span>a</span><span> baz</span>` (no
    // separating whitespace, so `output` does not already end in a space) keeps it verbatim
    // (Google Docs' pretty-printed multi-`<span>` export hits the first shape: issue found
    // via `test_documents/html/office-gdocs/gdocs-web-page-export.html`). `<del>`/`<ins>`
    // (Strikethrough/Inserted) do NOT get this treatment -- Tier-2's dedicated strike/ins
    // wrapper leaves a genuine double space in the equivalent shape (verified) -- so they
    // are deliberately excluded here.
    let bare_inline_frame_start_after_space = {
        let buf_len = state.cell_or_output_mut().len();
        let is_bare_inline_start = matches!(
            state.stack.last(),
            Some(frame) if frame.content_start >= buf_len && matches!(frame.spec.kind, TagKind::Inline)
        );
        is_bare_inline_start && state.cell_or_output_mut().ends_with(' ')
    };
    // ~keep Tier-2's `handle_code` renders `<code>` content fully verbatim — no
    // trimming, no whitespace normalization at all. `in_code` (already
    // computed above) covers both bare `<code>` and `<pre><code>`; the
    // `<pre>` case is already excluded via `!in_pre`, so this only adds
    // the bare-`<code>` exclusion needed to stop a leading plain ASCII
    // space/tab/newline run from being deleted (`<code> x</code>` must
    // stay "` x`", not become "`x`").
    let raw = if !in_pre
        && !in_code
        && (!state.in_table_cell() || in_link_frame)
        && (at_inline_frame_start
            || block_separator_after
            || document_start_strip
            || after_line_end
            || bare_inline_frame_start_after_space)
    {
        let trimmed = trim_leading_text_whitespace(raw);
        if leading_ws_migrates_out && trimmed.len() < raw.len() {
            state.cell_or_output_mut().push(' ');
        }
        trimmed
    } else {
        raw
    };
    if raw.is_empty() {
        return Ok(());
    }

    let has_entities = raw.contains('&');

    if in_pre {
        if has_entities {
            let dest = state.cell_or_output_mut();
            decode_entities_into(dest, raw, base_offset, ReferenceContext::Text)?;
        } else {
            state.cell_or_output_mut().push_str(raw);
        }
        return Ok(());
    }

    if in_code {
        // ~keep Tier-2 parity (`text_node.rs`'s `in_code && !in_code_block` branch): a
        // code SPAN folds any raw line ending -- CR, LF, or CRLF -- in its own text
        // content to a single space; only a `<br>` element (handled separately by
        // `emit_void`'s `TagKind::LineBreak` arm) produces the literal '\n'
        // `close_code` treats as a split point between segments. A text node's own
        // line ending is never that marker, so folding it here can never collide
        // with a real `<br>` (issue #487).
        let decoded: std::borrow::Cow<'_, str> = if has_entities {
            let mut buf = String::with_capacity(raw.len());
            decode_entities_into(&mut buf, raw, base_offset, ReferenceContext::Text)?;
            std::borrow::Cow::Owned(buf)
        } else {
            std::borrow::Cow::Borrowed(raw)
        };
        let folded = crate::text::fold_cell_line_breaks_verbatim_cow(decoded.as_ref());
        state.cell_or_output_mut().push_str(folded.as_ref());
        return Ok(());
    }

    // ~keep Inside an `<a>` link frame, Tier-2's `normalize_link_label` replaces
    // newlines with spaces before whitespace collapsing.  Mirror that here so
    // text spanning `\n` inside an `<a>` (e.g. `<a>Skip to main\n  content</a>`)
    // collapses to `[Skip to main content]` instead of leaking the newline.
    // `<strong>`/`<em>` do NOT normalize newlines in Tier-2 — only links do.
    // ~keep
    // ~keep `<summary>` is treated the same as `<a>` here (Phase R-3): Tier-2's
    // handle_summary collects children into a local content buffer and
    // wraps in `**...**\n\n`; the surrounding text-normalization layer
    // collapses internal newline runs to single spaces before emission.
    // Without this, summary content with multi-line inline children leaks
    // `\n  \n  ` between text runs.
    // Table cells fold newlines the same way: Tier-2's `process_text_node`
    // has a dedicated `ctx.in_table_cell` branch (text_node.rs) that runs
    // `normalize_cell_whitespace_cow` per text node — folding `\n`/`\r` into
    // the whitespace run before collapsing to a single space — rather than
    // the generic non-cell chomp path.  Without this, a text node whose
    // trailing run is `\n` + indentation (pretty-printed HTML, e.g. a
    // multi-line `<td>` around an `<ins>`/`<span>`) leaves the `\n` byte
    // un-collapsed here; `close_table_cell`'s later blanket
    // `replace('\n', " ")` then turns that leftover `\n` into a SECOND
    // space next to the one already collapsed from the trailing run,
    // double-spacing the cell relative to Tier-2.
    let inside_inline = state.in_table_cell()
        || state.in_summary()
        || state.stack.iter().any(|frame| matches!(frame.spec.kind, TagKind::Link));

    // ~keep Phase Y: text-node chomp.  Tier-2's text_node.rs runs `chomp()` on
    // every text node and substitutes the leading and trailing whitespace
    // runs with simpler stand-ins:
    //   prefix → `" "` if the run had any leading whitespace, else `""`
    //   suffix → `"\n\n"` if trailing run contained `\n\n`,
    //          → `" "`   if trailing run had space/tab (folding any `\n`),
    //          → `trailing_single_newline_join(...)` if trailing run was `\n` only.
    // Without this, Tier-1 keeps the literal `\n  ` in text like
    // "The number of\n  " and emits `of\n ` while Tier-2 emits `of `,
    // and likewise the leading whitespace case `</em>\n  baz` produces
    // `*bar*\n baz` instead of `*bar* baz`.
    // ~keep
    // ~keep Applied only outside inline frames (which call
    // `decode_and_collapse_into_inline` and handle `\n` collapse already),
    // outside `<pre>` (verbatim), and outside table cells (which run
    // `normalize_whitespace_cow` directly).
    let mut ends_in_newline_join = false;
    let raw_owned;
    let raw = if !inside_inline && !state.in_table_cell() {
        let trim_chars: &[char] = &['\n', '\r', ' ', '\t'];
        let after_lead = raw.trim_start_matches(trim_chars);
        let leading_len = raw.len() - after_lead.len();
        let lead_has_nl = leading_len > 0 && raw.as_bytes()[..leading_len].iter().any(|&b| b == b'\n' || b == b'\r');
        let trimmed_len = raw.trim_end_matches(trim_chars).len();
        let trailing_len = raw.len() - trimmed_len;
        let trail_has_nl = trailing_len > 0 && raw.as_bytes()[trimmed_len..].iter().any(|&b| b == b'\n' || b == b'\r');
        if lead_has_nl || trail_has_nl {
            let core_start = leading_len;
            let core_end = trimmed_len;
            if core_start >= core_end {
                // ~keep Whitespace-only text node — already handled by the
                // earlier whitespace-only branches; skip Phase Y here.
                raw
            } else {
                let core = &raw[core_start..core_end];
                let trailing = &raw[core_end..];
                let prefix = if leading_len > 0 { " " } else { "" };
                let suffix = if trailing.contains("\n\n") {
                    "\n\n"
                } else if trailing.bytes().any(|b| b == b' ' || b == b'\t') {
                    " "
                } else if trail_has_nl {
                    let join = trailing_single_newline_join(state, next_tag_is_span);
                    ends_in_newline_join = join == "\n";
                    join
                } else {
                    trailing
                };
                raw_owned = format!("{prefix}{core}{suffix}");
                raw_owned.as_str()
            }
        } else {
            raw
        }
    } else {
        raw
    };
    if raw.is_empty() {
        return Ok(());
    }
    let has_entities = raw.contains('&');

    // ~keep Issue #458: Tier-2 escapes a literal `\` in prose whether or not any
    // `escape_*` flag is set (`text::backslash_needs_escape`), so Tier-1 has to
    // apply the same rule or the two tiers disagree on every document containing
    // one.  The rule runs over the bytes this call appends rather than over `raw`,
    // because its target must be the *decoded* text with whitespace already
    // collapsed — exactly what Tier-2 hands to `text::escape`.
    let in_cell = state.in_table_cell();
    // ~keep Mirror Tier-2 (text_node.rs, issue #651). A heading and a table cell fold their line
    // ~keep breaks into spaces, as Tier-2 writes them, so no line in them starts a block.
    let folds_lines = in_cell
        || state
            .stack
            .iter()
            .any(|frame| matches!(frame.spec.kind, TagKind::Heading(_)));

    indent_fresh_list_item_text_line(state);

    // ~keep A link label and a `<summary>` body are the exception: Tier-1 folds their
    // newlines into spaces while collapsing, but Tier-2 escapes the text node
    // first and only then folds (`normalize_link_label` / the summary
    // accumulator).  A `\` that sat before a newline in the source is escaped by
    // Tier-2 and would not be by a pass reading the already-folded text, so escape
    // the decoded-but-unfolded text and let the collapse run over the result.
    // Entities are resolved up front, hence `has_entities: false` below — the
    // collapse pass must not decode a second time.
    if inside_inline && !in_cell && raw.contains('\\') {
        let mut staged = String::with_capacity(raw.len() + 8);
        if has_entities {
            decode_entities_into(&mut staged, raw, base_offset, ReferenceContext::Text)?;
        } else {
            staged.push_str(raw);
        }
        escape_backslash_run(&mut staged, 0, false);
        let dest = state.cell_or_output_mut();
        let emitted_from = dest.len();
        decode_and_collapse_into_inline(dest, &staged, false, base_offset)?;
        if !folds_lines {
            crate::converter::utility::escaping::escape_continuation_line_start(dest, emitted_from);
        }
        return Ok(());
    }

    let dest = state.cell_or_output_mut();
    let emitted_from = dest.len();

    if !has_entities {
        let needle_present = if inside_inline {
            memchr3(b' ', b'\t', b'\n', raw.as_bytes()).is_some()
        } else {
            memchr::memchr2(b' ', b'\t', raw.as_bytes()).is_some()
        };
        if !needle_present {
            dest.push_str(raw);
        } else if inside_inline {
            decode_and_collapse_into_inline(dest, raw, false, base_offset)?;
        } else {
            decode_and_collapse_into(dest, raw, false, base_offset)?;
        }
    } else if inside_inline {
        decode_and_collapse_into_inline(dest, raw, has_entities, base_offset)?;
    } else {
        decode_and_collapse_into(dest, raw, has_entities, base_offset)?;
    }

    escape_backslash_run(dest, emitted_from, in_cell);
    if !folds_lines {
        crate::converter::utility::escaping::escape_continuation_line_start(dest, emitted_from);
    }
    if ends_in_newline_join {
        let join_end = dest.len();
        state.pending_newline_join = Some(join_end);
    }
    Ok(())
}

/// Apply `text::backslash_needs_escape` to the run `buffer[from..]`.
///
/// `run_ends_at_last_byte` selects where the run ends, which genuinely differs between
/// the two Tier-2 call sites this mirrors:
///
/// - Prose (`text_node.rs`'s normalized branch) escapes `chomp()`'s *core*, the text
///   node with its boundary whitespace stripped — so a trailing `\` counts as
///   end-of-run even when spaces or a newline follow it in the emitted bytes. Pass
///   `false`.
/// - A table cell (`text_node.rs`'s `in_table_cell` branch) escapes the whole
///   normalized text node with no chomp, so the run ends at the last byte whatever it
///   is. Pass `true`.
///
/// Getting this backwards flips `<p>a\ </p>` or `<td>a\ </td>` by one byte against
/// Tier-2. ~keep
fn escape_backslash_run(buffer: &mut String, from: usize, run_ends_at_last_byte: bool) {
    if memchr::memchr(b'\\', &buffer.as_bytes()[from..]).is_none() {
        return;
    }
    let run = buffer[from..].to_owned();
    let run_end = if run_ends_at_last_byte {
        run.len()
    } else {
        run.trim_end().len()
    };
    let bytes = &run.as_bytes()[..run_end];

    let mut rewritten = String::with_capacity(run.len() + 4);
    let mut copied_to = 0usize;
    for i in memchr::memchr_iter(b'\\', bytes) {
        if crate::text::backslash_needs_escape(bytes, i) {
            rewritten.push_str(&run[copied_to..i]);
            rewritten.push_str(r"\\");
            copied_to = i + 1;
        }
    }
    rewritten.push_str(&run[copied_to..]);

    buffer.truncate(from);
    buffer.push_str(&rewritten);
}

/// Decode HTML entities directly into `out` (no intermediate allocation).
///
/// `base_offset` is the byte offset of `s` within the original HTML input and
/// is used to report the position of any unrecognised entity in the bail reason.
///
/// Uses memchr to quickly find the next `&` and bulk-copies non-entity runs.
///
/// Returns `Err(BailReason::UnknownEntity)` when an entity cannot be decoded.
fn decode_entities_into(
    out: &mut String,
    s: &str,
    base_offset: usize,
    context: ReferenceContext,
) -> Result<(), BailReason> {
    let bytes = s.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if let Some(pos) = memchr::memchr(b'&', &bytes[i..]) {
            let amp_pos = i + pos;
            if amp_pos > i {
                out.push_str(&s[i..amp_pos]);
            }
            i = decode_entity_at(bytes, s, amp_pos, out, base_offset, context)?;
        } else {
            if i < bytes.len() {
                out.push_str(&s[i..]);
            }
            break;
        }
    }
    Ok(())
}

/// Decode entities AND collapse spaces/tabs in one pass, directly into `out`.
///
/// `base_offset` is the byte offset of `s` within the original HTML input and
/// is used to report the position of any unrecognised entity in the bail reason.
///
/// Uses memchr3 to quickly find the next special byte (space/tab/&), then
/// bulk-copies the run in one `push_str` to avoid per-byte overhead.
///
/// Returns `Err(BailReason::UnknownEntity)` when an entity cannot be decoded.
fn decode_and_collapse_into(
    out: &mut String,
    s: &str,
    has_entities: bool,
    base_offset: usize,
) -> Result<(), BailReason> {
    decode_and_collapse_into_inner(out, s, has_entities, base_offset, false)
}

/// Collapse like `decode_and_collapse_into` but treat `\n`/`\r` as collapsible
/// whitespace too.  Used for text inside `<a>`/`<strong>`/`<em>` frames where
/// Tier-2's `normalize_link_label` first replaces newlines with spaces, then
/// runs whitespace normalization.
fn decode_and_collapse_into_inline(
    out: &mut String,
    s: &str,
    has_entities: bool,
    base_offset: usize,
) -> Result<(), BailReason> {
    decode_and_collapse_into_inner(out, s, has_entities, base_offset, true)
}

fn decode_and_collapse_into_inner(
    out: &mut String,
    s: &str,
    has_entities: bool,
    base_offset: usize,
    collapse_newlines: bool,
) -> Result<(), BailReason> {
    let bytes = s.as_bytes();
    let mut i = 0;
    let mut prev_was_space = false;
    // ~keep Mirrors Tier-2's `normalize_block_whitespace_cow` (text.rs): when a literal
    // `\n` survives into the output (only possible here when `collapse_newlines`
    // is false -- the `true` variant folds `\n` straight into a space below and
    // never leaves one in `out`), a run of spaces/tabs immediately after it is a
    // Markdown continuation line's leading indentation. A compliant parser drops
    // that entirely on reparse regardless of width (CommonMark spec 4.9), so
    // collapsing it to one space here was not a fixed point -- see the CommonMark
    // spec fixpoint oracle, example 182. Zero is. `s` has already had its own
    // leading/trailing whitespace resolved into a synthetic prefix/suffix by the
    // caller's Phase Y step, so every `\n` this sees with more content after it is
    // a genuine mid-text line break, never the text node's own edge.
    let mut at_line_start = false;
    while i < bytes.len() {
        let next_special = match (has_entities, collapse_newlines) {
            (true, true) => {
                let s_pos = memchr3(b' ', b'\t', b'\n', &bytes[i..]).map(|pos| i + pos);
                let e_pos = memchr::memchr(b'&', &bytes[i..]).map(|pos| i + pos);
                match (s_pos, e_pos) {
                    (Some(a), Some(b)) => Some(a.min(b)),
                    (Some(a), None) | (None, Some(a)) => Some(a),
                    (None, None) => None,
                }
            }
            (true, false) => memchr3(b' ', b'\t', b'&', &bytes[i..]).map(|pos| i + pos),
            (false, true) => memchr3(b' ', b'\t', b'\n', &bytes[i..]).map(|pos| i + pos),
            (false, false) => memchr::memchr2(b' ', b'\t', &bytes[i..]).map(|pos| i + pos),
        };

        if let Some(pos) = next_special {
            if pos > i {
                out.push_str(&s[i..pos]);
                prev_was_space = false;
                at_line_start = !collapse_newlines && bytes[pos - 1] == b'\n';
            }
            match bytes[pos] {
                b' ' | b'\t' if at_line_start => {
                    i = pos + 1;
                }
                b' ' | b'\t' => {
                    if !prev_was_space {
                        out.push(' ');
                    }
                    prev_was_space = true;
                    i = pos + 1;
                }
                b'\n' if collapse_newlines => {
                    if !prev_was_space {
                        out.push(' ');
                    }
                    prev_was_space = true;
                    i = pos + 1;
                }
                b'&' => {
                    prev_was_space = false;
                    at_line_start = false;
                    i = decode_entity_at(bytes, s, pos, out, base_offset, ReferenceContext::Text)?;
                }
                _ => unreachable!(),
            }
        } else {
            if i < bytes.len() {
                out.push_str(&s[i..]);
            }
            break;
        }
    }
    Ok(())
}

/// `raw` without its leading whitespace, where a character reference that decodes to whitespace
/// (`&#10;`, `&#32;`, `&Tab;`) counts as whitespace too.
///
/// ~keep Tier-2 decodes a text node before it trims the node's leading whitespace, so a newline
/// ~keep written as `&#10;` after a hard break is dropped there; trimmed before decoding, it
/// ~keep survived here as a second line end and made a blank line.
fn trim_leading_text_whitespace(raw: &str) -> &str {
    const WHITESPACE: [char; 4] = [' ', '\t', '\n', '\r'];
    let mut rest = raw.trim_start_matches(WHITESPACE);
    while rest.starts_with('&') {
        match crate::text::decode_character_reference(rest, 0, ReferenceContext::Text) {
            Some((end, first, None)) if rest.as_bytes()[end - 1] == b';' && WHITESPACE.contains(&first) => {
                rest = rest[end..].trim_start_matches(WHITESPACE);
            }
            _ => break,
        }
    }
    rest
}

/// Scan and decode a single HTML entity starting at `amp_pos` (the `&` byte).
///
/// Tries the hot subset in `decode_entity_into` for an alphanumeric name closed by `;`; every
/// other reference goes through Tier-2's decoder, `text::decode_character_reference`, so both
/// tiers read one table. When nothing decodes, writes the `&` alone and resumes at the next byte,
/// as Tier-2 does, so a reference after an unknown name still decodes (#554).
///
/// Returns the position immediately after the reference, or after the `&`.
///
/// Emits `Err(BailReason::UnknownEntity)` when Tier-2's decoder would decode a
/// reference this function does not: one without its `;`.
fn decode_entity_at(
    bytes: &[u8],
    s: &str,
    amp_pos: usize,
    out: &mut String,
    base_offset: usize,
    context: ReferenceContext,
) -> Result<usize, BailReason> {
    let amp = amp_pos;
    let name_len = bytes[amp + 1..]
        .iter()
        .take_while(|b| b.is_ascii_alphanumeric())
        .count();
    let name_end = amp + 1 + name_len;
    if bytes.get(name_end) == Some(&b';') && decode_entity_into(out, &s[amp + 1..name_end]) {
        return Ok(name_end + 1);
    }
    match crate::text::decode_character_reference(s, amp, context) {
        Some((reference_end, first, second)) if bytes[reference_end - 1] == b';' => {
            out.push(first);
            if let Some(second) = second {
                out.push(second);
            }
            Ok(reference_end)
        }
        // ~keep A legacy named reference (#545) or a numeric one (#553) without its `;` is
        // ~keep rare; Tier-2 owns the longest-name rule and the attribute exception.
        Some((reference_end, ..)) => Err(BailReason::UnknownEntity {
            name: s[amp + 1..reference_end].into(),
            offset: base_offset + amp,
        }),
        None => {
            out.push('&');
            Ok(amp + 1)
        }
    }
}

/// Apply the escape-context bits for an opening tag.
///
/// The close path restores `state.escape_ctx` directly from `frame.prev_escape_ctx`
/// so a symmetric `remove_open_escape_ctx` is not needed.
#[inline]
fn apply_open_escape_ctx(state: &mut Tier1State, spec: &TagSpec) {
    if spec.kind == TagKind::Pre {
        state.escape_ctx |= EscapeCtx::PRE | EscapeCtx::CODE;
        return;
    }

    let bit = match spec.kind {
        TagKind::Code => EscapeCtx::CODE,
        TagKind::Link => EscapeCtx::LINK,
        TagKind::Blockquote => EscapeCtx::BLOCKQUOTE,
        TagKind::Heading(_) => EscapeCtx::HEADING,
        TagKind::Strong => EscapeCtx::STRONG,
        _ => return,
    };

    state.escape_ctx |= bit;
}

/// Report whether an attribute is present, with or without a value.
///
/// [`find_attr`] returns the attribute's *value* and so cannot tell an absent
/// attribute from a valueless one (`<td colspan>`).  Tier-2's spanning-cell test
/// (`block/table/scanner.rs`: `attrs.get("colspan").is_some()`) keys off presence
/// alone, so mirroring it needs this distinction.
fn has_attr(attrs: &[(&[u8], Option<&[u8]>)], key: &[u8]) -> bool {
    attrs.iter().any(|(k, _)| k.eq_ignore_ascii_case(key))
}

/// Find an attribute value by (lowercase) key name.
fn find_attr<'a>(attrs: &[(&'a [u8], Option<&'a [u8]>)], key: &[u8]) -> Option<&'a [u8]> {
    for (k, v) in attrs {
        if k.eq_ignore_ascii_case(key) {
            return *v;
        }
    }
    None
}

/// Returns true when `name_lower` is a tag that *may* need preprocessing-skip
/// evaluation.  All other tags skip the more expensive `should_skip_preprocessing`
/// check entirely.
fn is_preprocessing_skip_candidate(name_lower: &[u8]) -> bool {
    matches!(name_lower, b"nav" | b"header" | b"footer" | b"aside" | b"form")
}

/// Mirrors `should_drop_for_preprocessing` (preprocessing_helpers.rs) for
/// the Tier-1 byte scanner.
///
/// Called only for tags that passed [`is_preprocessing_skip_candidate`].
/// Uses the raw attribute byte slices collected by [`parse::collect_attrs`]
/// instead of the Tier-2 `tl::HTMLTag` DOM node.
fn should_skip_preprocessing(name_lower: &[u8], attrs: &[(&[u8], Option<&[u8]>)], options: &ConversionOptions) -> bool {
    use crate::options::PreprocessingPreset;

    if !options.preprocessing.enabled {
        return false;
    }

    if options.preprocessing.preset == PreprocessingPreset::Minimal {
        return false;
    }

    if options.preprocessing.remove_forms && name_lower == b"form" {
        return true;
    }

    if !options.preprocessing.remove_navigation {
        return false;
    }

    if name_lower == b"nav" {
        return true;
    }

    // ~keep <header> / <footer> / <aside> — drop only when navigation hints present.
    // (Aggressive would drop footer/aside unconditionally, but Aggressive routes
    // through Tier-2 via the existing router gate so Tier-1 only needs the
    // Standard-preset behaviour: nav-hint check.)
    if matches!(name_lower, b"header" | b"footer" | b"aside") {
        return byte_attrs_have_navigation_hint(attrs);
    }

    false
}

/// Byte-level equivalent of `element_has_navigation_hint` for use in the
/// Tier-1 scanner where attributes are raw `&[u8]` slices rather than a
/// parsed `tl::HTMLTag`.
fn byte_attrs_have_navigation_hint(attrs: &[(&[u8], Option<&[u8]>)]) -> bool {
    if let Some(role) = find_attr(attrs, b"role") {
        let role_lc = role.to_ascii_lowercase();
        if matches!(role_lc.as_slice(), b"navigation" | b"menubar" | b"tablist" | b"toolbar") {
            return true;
        }
    }

    if let Some(label) = find_attr(attrs, b"aria-label") {
        let label_lc = label.to_ascii_lowercase();
        const ARIA_SUBSTRINGS: &[&[u8]] = &[b"navigation", b"menu", b"contents", b"table of contents", b"toc"];
        if ARIA_SUBSTRINGS
            .iter()
            .any(|sub| label_lc.windows(sub.len()).any(|w| w == *sub))
        {
            return true;
        }
    }

    for attr_name in [b"class".as_slice(), b"id".as_slice()] {
        if let Some(value) = find_attr(attrs, attr_name) {
            if byte_value_has_nav_keyword(value) {
                return true;
            }
        }
    }

    false
}

/// Tokenize a raw attribute byte value and return true when any token matches
/// a keyword in [`NAV_KEYWORDS`].
///
/// Tokens are split on ASCII whitespace.  Each token is normalised by
/// replacing `_`, `:`, `.`, `/` with `-` and lowercasing before comparison.
fn byte_value_has_nav_keyword(value: &[u8]) -> bool {
    let mut start = 0;
    let len = value.len();
    loop {
        while start < len && value[start].is_ascii_whitespace() {
            start += 1;
        }
        if start >= len {
            break;
        }
        let mut end = start;
        while end < len && !value[end].is_ascii_whitespace() {
            end += 1;
        }
        let token_bytes = &value[start..end];
        let mut buf = [0u8; 64];
        let normalised: &[u8] = if token_bytes.len() <= buf.len() {
            let n = token_bytes.len();
            for (i, &b) in token_bytes.iter().enumerate() {
                buf[i] = match b {
                    b'_' | b':' | b'.' | b'/' => b'-',
                    _ => b.to_ascii_lowercase(),
                };
            }
            &buf[..n]
        } else {
            start = end;
            continue;
        };

        if NAV_KEYWORDS.iter().any(|kw| kw.as_bytes() == normalised) {
            return true;
        }

        start = end;
    }
    false
}

/// Extract `href` and `title` from the attribute list for a link.
fn extract_link_attrs(attrs: &[(&[u8], Option<&[u8]>)]) -> Result<(Option<String>, Option<String>), BailReason> {
    let href = find_attr(attrs, b"href").map(decode_attr).transpose()?;
    // ~keep Full decode, matching Tier-2's `decoded_attribute` (issue #494). This used to be
    // a deliberate half-decode that mirrored Tier-2 leaving named entities intact, so a
    // `title="A&amp;B"` reached the output as the literal text `A&amp;B` in both tiers.
    let title = find_attr(attrs, b"title").map(decode_attr).transpose()?;
    Ok((href, title))
}

/// Extract `start` attribute from `<ol>` (defaults to 1).
fn extract_ol_start(attrs: &[(&[u8], Option<&[u8]>)]) -> u16 {
    find_attr(attrs, b"start")
        .and_then(|b| std::str::from_utf8(b).ok())
        .and_then(|s| s.parse::<u16>().ok())
        .unwrap_or(1)
}

/// Decode an attribute value: entity-decode and convert to a String.
///
/// Returns `Err(BailReason::Classifier)` when the value is not valid UTF-8
/// (malformed bytes in attributes cannot be decoded faithfully).
/// Returns `Err(BailReason::UnknownEntity)` when the value contains an entity
/// that Tier-1 cannot decode (Tier-2 would decode it differently).
fn decode_attr(bytes: &[u8]) -> Result<String, BailReason> {
    let s = std::str::from_utf8(bytes).map_err(|_| BailReason::Classifier)?;
    if !s.contains('&') {
        return Ok(s.to_owned());
    }
    let mut out = String::with_capacity(s.len());
    decode_entities_into(&mut out, s, 0, ReferenceContext::Attribute)?;
    Ok(out)
}

/// Pop the topmost frame whose spec matches `spec`.
/// Tier-2 is lenient about close tags; we are strict in M3c: only pop the
/// Pop the topmost frame whose spec matches `spec`.
///
/// We compare by checking if the `TagKind` on the top frame maps to the same
/// "semantic group" as the spec being closed.  We are strict in M3c: only the
/// top frame is checked to avoid mismatched-close-tag complexity.
fn pop_matching_frame(stack: &mut Vec<OpenTag>, spec: &'static TagSpec) -> Option<OpenTag> {
    let top = stack.last()?;
    if kinds_match(&top.spec.kind, &spec.kind) {
        stack.pop()
    } else {
        None
    }
}

/// Return `true` if two `TagKind` values are the "same" for close-tag matching.
///
/// Uses pointer equality on the `&'static TagSpec` where possible for speed.
/// For kinds with inner data (`List`, `Heading`, `TableCell`) we use a
/// coarser match that still prevents cross-kind confusion:
/// - `List(Ordered)` only matches `List(Ordered)`, etc.
/// - `Heading(n)` matches `Heading(m)` for any n, m (HTML allows `</h3>` to
///   close `<h2>` in some parsers; we are lenient for headings since they
///   do not nest in practice).
fn kinds_match(a: &TagKind, b: &TagKind) -> bool {
    match (a, b) {
        (TagKind::List(la), TagKind::List(lb)) => la == lb,
        (TagKind::Heading(_), TagKind::Heading(_)) => true,
        (TagKind::TableCell { is_header: a_h }, TagKind::TableCell { is_header: b_h }) => a_h == b_h,
        _ => std::mem::discriminant(a) == std::mem::discriminant(b),
    }
}

/// Find the nearest enclosing list kind by walking the stack top-to-bottom.
fn find_parent_list_kind(stack: &[OpenTag]) -> Option<ListKind> {
    for frame in stack.iter().rev() {
        if let TagKind::List(kind) = frame.spec.kind {
            return Some(kind);
        }
    }
    None
}

/// Increment the ordered-list counter on the nearest `List(Ordered)` frame.
/// Returns the new counter value (1-based).
fn increment_ol_counter(stack: &mut [OpenTag]) -> u16 {
    for frame in stack.iter_mut().rev() {
        if frame.spec.kind == TagKind::List(ListKind::Ordered) {
            frame.list_index = frame.list_index.saturating_add(1);
            return frame.list_index;
        }
    }
    1
}

/// Get the `ol_start` value from the nearest `List(Ordered)` frame.
fn find_ol_start(stack: &[OpenTag]) -> u16 {
    for frame in stack.iter().rev() {
        if frame.spec.kind == TagKind::List(ListKind::Ordered) {
            return frame.ol_start;
        }
    }
    1
}

/// Return the ATX heading prefix for level `n` (1–6).
///
/// Uses the `HEADING_PREFIXES` table — no allocation.
fn heading_prefix(n: u8) -> &'static str {
    let idx = (n as usize).saturating_sub(1).min(5);
    HEADING_PREFIXES[idx]
}

/// Push the list-item indentation for `depth` into `out`.
///
/// Depth 0 → no indent; each level adds two spaces (matches the router's
/// `list_indent_width == 2` gate).  Depths 0–7 use the static `LIST_ITEM_INDENTS`
/// table; deeper nesting (rare) falls back to a runtime loop.
fn push_list_item_indent(out: &mut String, depth: u16) {
    let idx = depth as usize;
    if idx < LIST_ITEM_INDENTS.len() {
        out.push_str(LIST_ITEM_INDENTS[idx]);
    } else {
        out.reserve(idx * 2);
        for _ in 0..idx {
            out.push_str("  ");
        }
    }
}

/// Add `> ` prefix to every non-empty line of `content`, and `>` to empty
/// lines that are between non-empty ones (Tier-2 behaviour for multi-paragraph
/// blockquotes).
fn prefix_blockquote_lines(content: &str) -> String {
    let content = content.trim_end_matches('\n');
    if content.is_empty() {
        return String::new();
    }

    let lines: Vec<&str> = content.split('\n').collect();
    let mut result = String::with_capacity(content.len() + lines.len() * 2);

    for (i, line) in lines.iter().enumerate() {
        if line.is_empty() {
            result.push('>');
        } else {
            result.push_str("> ");
            result.push_str(line);
        }
        if i < lines.len() - 1 {
            result.push('\n');
        }
    }
    result.push('\n');
    result
}

/// Indent each line of a pre block by 4 spaces, after dedenting common leading whitespace.
///
/// Mirrors Tier-2's `dedent_code_block` + 4-space indent logic.
fn indent_pre_lines(raw: &str) -> String {
    let raw = raw.strip_prefix('\n').unwrap_or(raw);
    let raw = raw.trim_end_matches('\n');
    if raw.is_empty() {
        return String::new();
    }

    let min_indent = raw
        .lines()
        .filter(|line| !line.trim().is_empty())
        .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
        .min()
        .unwrap_or(0);

    let mut result = String::with_capacity(raw.len() + raw.lines().count() * 4);
    for line in raw.lines() {
        if line.trim().is_empty() {
            // ~keep Empty / whitespace-only line: emit as a bare `\n` (no 4-space
            // indent prefix).  Tier-2's `block/code.rs` also skips the indent
            // for blank lines inside indented code blocks — without this,
            // round-tripped CommonMark `    code\n    \n    code` would
            // render with stray trailing spaces in the blank gap.
        } else {
            result.push_str("    ");
            // ~keep Convert char-count `min_indent` into a byte offset by walking
            // `char_indices`.  Indexing `line[min_indent..]` directly panics
            // when the leading whitespace contains multibyte characters such
            // as `\u{a0}` (NBSP).  Mirrors Tier-2's `dedent_code_block`
            // (text/processing.rs:38-50).
            let mut remaining = min_indent;
            let mut cut = 0;
            for (idx, ch) in line.char_indices() {
                if remaining == 0 {
                    break;
                }
                if ch.is_whitespace() {
                    remaining -= 1;
                    cut = idx + ch.len_utf8();
                } else {
                    break;
                }
            }
            result.push_str(&line[cut..]);
        }
        result.push('\n');
    }
    result
}

// ~keep ── GFM table emission ────────────────────────────────────────────────────────

/// Emit a completed table as GFM markdown, appending to `state.output`.
///
/// Format must match Tier-2 `convert_table_row` byte-for-byte:
/// - Each row: `|` + ` cell |` per cell → `| c1 | c2 |`
/// - After row 0: separator `| --- | --- |` (one `---` per column)
///
/// # Panics
///
/// Never — empty-table guard returns early.
fn emit_gfm_table(target: &mut String, ts: crate::converter::tier1::state::TableState) {
    // ~keep Emit caption (if any) BEFORE the table body.
    // ~keep
    // ~keep Mirrors Tier-2 builder.rs caption handling: `*escaped_text*\n\n`.
    // Tier-2 emits the caption as part of the table child loop, which runs
    // before the rows are rendered, so the caption appears even when there
    // are no table rows.  The caption text has already been trimmed and
    // hyphen-escaped when `</caption>` was processed.
    if let Some(ref caption) = ts.caption_text {
        if !caption.is_empty() {
            if !target.is_empty() && !target.ends_with("\n\n") {
                if target.ends_with('\n') {
                    target.push('\n');
                } else {
                    target.push_str("\n\n");
                }
            }
            target.push('*');
            target.push_str(caption);
            target.push_str("*\n\n");
        }
    }

    if ts.rows.is_empty() {
        return;
    }

    // ~keep Pre-table separator: mirrors Tier-2's `convert_table` logic exactly.
    // Tier-2 (block/table/mod.rs): `if !output.is_empty() && !output.ends_with("\n\n")`
    // — only adds separator when there is existing output (no leading blank lines).
    if !target.is_empty() && !target.ends_with("\n\n") {
        if target.ends_with('\n') {
            target.push('\n');
        } else {
            target.push_str("\n\n");
        }
    }

    // ~keep Pre-compute max column widths across ALL rows (mirrors Tier-2's pre-pass).
    // Tier-2: separator dashes = max(col_content_char_count_across_all_rows, 3).
    // col_count is the colspan-expanded column count (sum of colspans per row).
    let col_count = ts
        .rows
        .iter()
        .map(|r| r.iter().map(|(_, c)| usize::from(*c)).sum::<usize>())
        .max()
        .unwrap_or(0);
    let mut col_widths: Vec<usize> = vec![0; col_count];
    for row in &ts.rows {
        let mut col = 0usize;
        for (cell, span) in row {
            let w = cell.chars().count();
            // ~keep Only the cell's anchor column owns the width — spanned columns
            // contribute zero (matches Tier-2's per-cell pad calculation).
            if col < col_widths.len() && w > col_widths[col] {
                col_widths[col] = w;
            }
            col += usize::from(*span);
        }
    }

    for (row_index, row) in ts.rows.iter().enumerate() {
        // ~keep Row: `|` then each cell as ` text |` (padded to col_width like Tier-2).
        target.push('|');
        let mut col = 0usize;
        for (cell, span) in row {
            target.push(' ');
            target.push_str(cell);
            // ~keep Pad to column width (mirrors Tier-2 cell.rs padding logic).
            let cell_len = cell.chars().count();
            let col_w = col_widths.get(col).copied().unwrap_or(0);
            for _ in cell_len..col_w {
                target.push(' ');
            }
            // ~keep Tier-2 (cell.rs:248): `for _ in 0..colspan { output.push_str(" |") }`.
            // colspan trailing ` |` separators per cell — produces `| Header | | |`
            // for `<th colspan="3">Header</th>` instead of `| Header |  |  |`.
            for _ in 0..*span {
                target.push_str(" |");
            }
            col += usize::from(*span);
        }
        target.push('\n');

        // ~keep After row 0 (the header row), emit the separator row.
        // Tier-2: col_widths.get(i).unwrap_or(0).max(MIN_SEPARATOR_DASHES).
        if row_index == 0 {
            target.push_str("| ");
            for i in 0..col_count.max(1) {
                if i > 0 {
                    target.push_str(" | ");
                }
                let dash_count = col_widths.get(i).copied().unwrap_or(0).max(MIN_SEPARATOR_DASHES);
                for _ in 0..dash_count {
                    target.push('-');
                }
            }
            target.push_str(" |\n");
        }
    }
}

/// Trim trailing spaces and tabs from the end of the output (used before
/// closing block elements that trim trailing whitespace in Tier-2).
fn trim_trailing_inline_whitespace(state: &mut Tier1State) {
    let buf = state.cell_or_output_mut();
    while buf.ends_with(' ') || buf.ends_with('\t') {
        buf.pop();
    }
}

/// Collapse runs of 3+ consecutive newlines down to 2, matching Tier-2's
/// `collapse_excess_blank_lines` post-processing step.
fn collapse_excess_blank_lines(output: &mut String) {
    let mut consecutive = 0usize;
    output.retain(|c| {
        if c == '\n' {
            consecutive += 1;
            consecutive <= 2
        } else {
            consecutive = 0;
            true
        }
    });
}

/// Decode a single HTML entity name (without `&` or `;`) from Tier-1's hot subset
/// directly into `out`.
///
/// Returns `true` when the entity was recognized and written; `false` for any
/// other name or a numeric reference, which the caller hands to Tier-2's decoder.
/// No `String` is allocated.
fn decode_entity_into(out: &mut String, name: &str) -> bool {
    let s: &str = match name {
        "amp" => "&",
        "lt" => "<",
        "gt" => ">",
        "quot" => "\"",
        "apos" => "'",
        "nbsp" => "\u{00A0}",
        "copy" => "\u{00A9}",
        "reg" => "\u{00AE}",
        "trade" => "\u{2122}",
        "mdash" => "\u{2014}",
        "ndash" => "\u{2013}",
        "hellip" => "\u{2026}",
        "laquo" => "\u{00AB}",
        "raquo" => "\u{00BB}",
        "lsquo" => "\u{2018}",
        "rsquo" => "\u{2019}",
        "ldquo" => "\u{201C}",
        "rdquo" => "\u{201D}",
        "prime" => "\u{2032}",
        "Prime" => "\u{2033}",
        "bull" => "\u{2022}",
        "middot" => "\u{00B7}",
        "deg" => "\u{00B0}",
        "plusmn" => "\u{00B1}",
        "times" => "\u{00D7}",
        "divide" => "\u{00F7}",
        "frac12" => "\u{00BD}",
        "frac14" => "\u{00BC}",
        "frac34" => "\u{00BE}",
        "euro" => "\u{20AC}",
        "pound" => "\u{00A3}",
        "yen" => "\u{00A5}",
        "cent" => "\u{00A2}",
        "larr" => "\u{2190}",
        "rarr" => "\u{2192}",
        "uarr" => "\u{2191}",
        "darr" => "\u{2193}",
        "harr" => "\u{2194}",
        "infin" => "\u{221E}",
        "alpha" => "\u{03B1}",
        "beta" => "\u{03B2}",
        "gamma" => "\u{03B3}",
        "delta" => "\u{03B4}",
        "pi" => "\u{03C0}",
        "sigma" => "\u{03C3}",
        "omega" => "\u{03C9}",
        // ~keep Latin-1 Supplement (U+00A0–U+00FF) — html5ever's Tier-2 backend
        // decodes the full HTML5 named entity table; mirror the Latin-1
        // block here so Tier-1 byte-equality holds for accented Western
        // text without bailing.  Entries already defined above (`nbsp`,
        // `copy`, `reg`, `laquo`, `raquo`, `frac12`, etc.) are not repeated.
        "iexcl" => "\u{00A1}",
        "brvbar" => "\u{00A6}",
        "sect" => "\u{00A7}",
        "uml" => "\u{00A8}",
        "ordf" => "\u{00AA}",
        "not" => "\u{00AC}",
        "shy" => "\u{00AD}",
        "macr" => "\u{00AF}",
        "sup2" => "\u{00B2}",
        "sup3" => "\u{00B3}",
        "acute" => "\u{00B4}",
        "micro" => "\u{00B5}",
        "para" => "\u{00B6}",
        "cedil" => "\u{00B8}",
        "sup1" => "\u{00B9}",
        "ordm" => "º",
        "iquest" => "\u{00BF}",
        "Agrave" => "\u{00C0}",
        "Aacute" => "\u{00C1}",
        "Acirc" => "\u{00C2}",
        "Atilde" => "\u{00C3}",
        "Auml" => "\u{00C4}",
        "Aring" => "\u{00C5}",
        "AElig" => "\u{00C6}",
        "Ccedil" => "\u{00C7}",
        "Egrave" => "\u{00C8}",
        "Eacute" => "\u{00C9}",
        "Ecirc" => "\u{00CA}",
        "Euml" => "\u{00CB}",
        "Igrave" => "\u{00CC}",
        "Iacute" => "\u{00CD}",
        "Icirc" => "\u{00CE}",
        "Iuml" => "\u{00CF}",
        "ETH" => "\u{00D0}",
        "Ntilde" => "\u{00D1}",
        "Ograve" => "\u{00D2}",
        "Oacute" => "\u{00D3}",
        "Ocirc" => "\u{00D4}",
        "Otilde" => "\u{00D5}",
        "Ouml" => "\u{00D6}",
        "Oslash" => "\u{00D8}",
        "Ugrave" => "\u{00D9}",
        "Uacute" => "\u{00DA}",
        "Ucirc" => "\u{00DB}",
        "Uuml" => "\u{00DC}",
        "Yacute" => "\u{00DD}",
        "THORN" => "\u{00DE}",
        "szlig" => "\u{00DF}",
        "agrave" => "\u{00E0}",
        "aacute" => "\u{00E1}",
        "acirc" => "\u{00E2}",
        "atilde" => "\u{00E3}",
        "auml" => "\u{00E4}",
        "aring" => "\u{00E5}",
        "aelig" => "\u{00E6}",
        "ccedil" => "\u{00E7}",
        "egrave" => "\u{00E8}",
        "eacute" => "\u{00E9}",
        "ecirc" => "\u{00EA}",
        "euml" => "\u{00EB}",
        "igrave" => "\u{00EC}",
        "iacute" => "\u{00ED}",
        "icirc" => "\u{00EE}",
        "iuml" => "\u{00EF}",
        "eth" => "\u{00F0}",
        "ntilde" => "\u{00F1}",
        "ograve" => "\u{00F2}",
        "oacute" => "\u{00F3}",
        "ocirc" => "\u{00F4}",
        "otilde" => "\u{00F5}",
        "ouml" => "\u{00F6}",
        "oslash" => "\u{00F8}",
        "ugrave" => "\u{00F9}",
        "uacute" => "\u{00FA}",
        "ucirc" => "\u{00FB}",
        "uuml" => "\u{00FC}",
        "yacute" => "\u{00FD}",
        "thorn" => "\u{00FE}",
        "yuml" => "\u{00FF}",
        _ => return false,
    };
    out.push_str(s);
    true
}

/// Skip `<!--...-->`, `<!DOCTYPE...>`, or any `<!...>` construct.
/// Returns the position immediately after the closing `>`.
///
/// On failure returns `Err(BailReason::LiteralLt)`.
fn skip_bang(bytes: &[u8], pos: usize) -> Result<usize, BailReason> {
    let start = pos + 2;

    if bytes.get(start) == Some(&b'-') && bytes.get(start + 1) == Some(&b'-') {
        let comment_start = start + 2;
        let mut i = comment_start;
        while i + 2 < bytes.len() {
            if bytes[i] == b'-' && bytes[i + 1] == b'-' && bytes[i + 2] == b'>' {
                return Ok(i + 3);
            }
            i += 1;
        }
        // ~keep Unclosed comment — bail
        return Err(BailReason::LiteralLt { offset: pos });
    }

    let mut i = start;
    while i < bytes.len() {
        if bytes[i] == b'>' {
            return Ok(i + 1);
        }
        i += 1;
    }
    Err(BailReason::LiteralLt { offset: pos })
}

/// Convert tag name bytes to lowercase in a fixed-size stack buffer.
/// Returns a slice into `buf`.  If the name is longer than `buf`, it is
/// truncated (names > `MAX_TAG_NAME_BYTES` won't appear in the spec table and
/// will be rejected as unknown).
fn lowercase_into<'b>(bytes: &[u8], buf: &'b mut [u8; MAX_TAG_NAME_BYTES]) -> &'b [u8] {
    let len = bytes.len().min(MAX_TAG_NAME_BYTES);
    for (i, &b) in bytes[..len].iter().enumerate() {
        buf[i] = b.to_ascii_lowercase();
    }
    &buf[..len]
}

/// Convert a byte slice to an owned `String` (lossy UTF-8).
fn bytes_to_string(b: &[u8]) -> String {
    String::from_utf8_lossy(b).into_owned()
}

/// Peek the lowercased tag name of the upcoming OPEN tag at `bytes[lt_pos]`
/// (expected to be `<`), if there is one — `None` for a close tag (`</...`),
/// a non-tag `<` (comment, bang, literal), or EOF. Shared by
/// `upcoming_tag_is_list_open` and `upcoming_tag_is_named` so the main scan
/// loop can peek ahead, BEFORE the tag itself is parsed, to tell `flush_text`
/// what kind of tag the text about to be flushed sits directly in front of.
fn upcoming_open_tag_name<'b>(bytes: &[u8], lt_pos: usize, buf: &'b mut [u8; MAX_TAG_NAME_BYTES]) -> Option<&'b [u8]> {
    if bytes.get(lt_pos) != Some(&b'<') {
        return None;
    }
    let &next = bytes.get(lt_pos + 1)?;
    if !parse::is_tag_name_start(next) {
        return None;
    }
    let name_start = lt_pos + 1;
    let name_end = parse::scan_tag_name(bytes, name_start);
    Some(lowercase_into(&bytes[name_start..name_end], buf))
}

/// Decide what a text node's trailing *bare* `\n` (no accompanying space/tab,
/// not part of a `\n\n` run) collapses to.
///
/// Mirrors Tier-2's `has_trailing_single_newline` follow-up step
/// (`text_node.rs`, the `else if has_trailing_single_newline` arm): `chomp()`
/// itself reduces that trailing run to nothing, but a supplementary check then
/// puts a joining character back unless the block already ends in a blank
/// line. Only reachable from the non-inline, non-table-cell Phase Y branch in
/// `flush_text`, so `state.output` — not `cell_or_output_mut()` — is always
/// the right buffer to inspect here (mirrors Tier-2's `ctx.block_content_start`
/// slice of the real `output`, which the same non-inline/non-cell precondition
/// guarantees is `state.output` too).
///
/// - `<span>` is a hardcoded exception in Tier-2's source: no join at all.
/// - Otherwise: a blank-line break already in place needs nothing either. The
///   "already" is scoped to the enclosing `<p>`/`<div>`'s OWN content (Tier-2's
///   `ctx.block_content_start`, i.e. `nearest_block_content_start` here) —
///   never the whole document buffer. A paragraph that just opened right
///   after a preceding one leaves the DOCUMENT ending in "\n\n" (its own
///   leading separator) while its OWN content is still empty; scoping the
///   check avoids reading that separator as "this text node already touches a
///   blank line" and wrongly swallowing the join.
/// - Otherwise: a paragraph ancestor, or a `<strong>`/`<em>` (Tier-2's
///   `inline_depth`-incrementing wrappers) ancestor, joins with a single
///   space; anything else (e.g. a bare `<div>`) joins with a literal newline,
///   which a `<br>` that follows removes again (`Tier1State::pending_newline_join`).
fn trailing_single_newline_join(state: &Tier1State, next_tag_is_span: bool) -> &'static str {
    if next_tag_is_span {
        return "";
    }
    let block_start = clamp_to_char_boundary(&state.output, nearest_block_content_start(state));
    if state.output[block_start..].ends_with("\n\n") {
        return "";
    }
    let in_paragraph_or_inline_wrapper = state.stack.iter().any(|frame| {
        matches!(
            frame.spec.kind,
            TagKind::Paragraph | TagKind::Strong | TagKind::Emphasis
        )
    });
    if in_paragraph_or_inline_wrapper { " " } else { "\n" }
}

/// Position where the innermost enclosing `<p>`/`<div>` frame's OWN content
/// starts in `state.output` — Tier-1's equivalent of Tier-2's
/// `ctx.block_content_start` (set in `block/paragraph.rs`, which handles both
/// tags). Falls back to `0` (the whole buffer) when no such ancestor is open,
/// matching `Context::default`'s `block_content_start: 0`.
fn nearest_block_content_start(state: &Tier1State) -> usize {
    state
        .stack
        .iter()
        .rev()
        .find(|frame| matches!(frame.spec.kind, TagKind::Paragraph | TagKind::Block))
        .map_or(0, |frame| frame.content_start)
}

/// Peek whether the upcoming tag at `bytes[lt_pos]` is an opening `<ul>`/`<ol>`.
/// See `flush_text`'s `next_tag_is_list` parameter for why that distinction
/// matters.
fn upcoming_tag_is_list_open(bytes: &[u8], lt_pos: usize) -> bool {
    let mut name_buf = [0u8; MAX_TAG_NAME_BYTES];
    matches!(
        upcoming_open_tag_name(bytes, lt_pos, &mut name_buf),
        Some(b"ul" | b"ol")
    )
}

/// Peek whether the upcoming tag at `bytes[lt_pos]` is an opening tag named
/// exactly `name` (already lowercase). See `flush_text`'s `next_tag_is_img`
/// parameter for why that distinction matters.
fn upcoming_tag_is_named(bytes: &[u8], lt_pos: usize, name: &[u8]) -> bool {
    let mut name_buf = [0u8; MAX_TAG_NAME_BYTES];
    upcoming_open_tag_name(bytes, lt_pos, &mut name_buf) == Some(name)
}