edamame 0.1.6

A Terminal Markdown editor that stays rendered while you edit
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
pub mod list;
pub mod table;
pub mod util;

use std::borrow::Cow;
use std::cell::Cell;

use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Widget;
use tui_big_text::{BigText, PixelSize};

use crate::config::Theme;

use self::util::{link_fallback, link_style_for, nbsps, spaces};
use super::ast::{inlines_to_plain, to_u32, Block, Inline, LineSpan, MetadataKind, SrcLines};
use super::highlight::{self, Token};
use super::render_cache::{is_cache_worthy, BlockMap, CachedRows, RenderCache, RenderSettings};
use super::row_origin::{ContentKind, RowOrigin, RowSink};
use super::segment_break;
use super::table_layout::{self, str_cells};

const IMAGE_PREFIX: &str = "Image: ";

/// Cells the renderer puts to the left of a code body line's first character — the leading
/// space in `format!(" {:<width$}", …)`.  Recorded as the row's `rendered_col`, which is how the
/// cursor indicator, the overlays and the mouse hit-test learn it.
pub const CODE_PAD_COLS: usize = 1;

/// Aspect-aware row count for an image block, keyed by URL and by **ordinal**
/// — the 0-based index of the block among the document's image blocks, in
/// document order.  See `Renderer::with_image_row_override`.
///
/// The ordinal is what separates two blocks carrying the same URL (one image
/// repeated in a header and a footer).  It matches the index into
/// `ParsedDoc::image_blocks`: both count `Block::ImageBlock`s in document order
/// over the same block list, and the promotions that create one act on
/// top-level blocks only, so no nested image block can shift the count.
pub type ImageRowOverride<'t> = &'t dyn Fn(&str, usize) -> Option<usize>;

/// Converts a `Vec<Block>` AST into a `Vec<Line<'static>>` ready for ratatui.
pub struct Renderer<'t> {
    pub(super) theme: &'t Theme,
    /// Viewport width in terminal columns.  Width-sized output reads [`width`](Self::width)
    /// instead, which subtracts the enclosing containers' prefixes.
    viewport_width: usize,
    /// Cells the enclosing containers prefix to every row of the block being rendered: two per
    /// blockquote level for the `▎ ` bar, a footnote definition's leader width.  A `Cell`, like
    /// `image_block_seq`, because the render walk takes `&self`; set only by
    /// [`inset_by`](Self::inset_by), which restores it.
    ///
    /// The render cache needs no key for it: only top-level blocks are cached, and they render at
    /// inset 0, so a nested block's inset is a function of its top-level ancestor's value.
    inset: Cell<usize>,
    /// The background the enclosing containers paint under the block being rendered: a quote's
    /// wash, or `None` for the page.  What a list item gives the indent it prefixes to a block
    /// with a surface of its own (`render_under_indent`), so that surface stays off the indent.
    /// Set only by [`on_surface`](Self::on_surface), which restores it; uncached for the same
    /// reason as `inset`.
    surface: Cell<Option<Color>>,
    /// Whether code block lines should wrap at [`width`](Self::width).
    code_wrap: bool,
    /// Rows reserved per `Block::ImageBlock` absent a row override; from
    /// `ImagesConfig::max_height`, so editor and renderer agree.
    image_max_height: usize,
    /// Per-image row override; `None` from it (pending / failed / uncached
    /// image) falls back to `image_max_height`, so pre-decode layout is stable.
    image_row_override: Option<ImageRowOverride<'t>>,
    /// Ordinal handed to `image_row_override`.  A `Cell` because the render
    /// walk takes `&self`; a `Renderer` is built fresh per `ParsedDoc` build,
    /// so it always starts at 0.  Counted in `render_image_block` rather than
    /// in the render loops so it stays exact under
    /// `render_with_counts_cached`, which skips `render_block` on cache hits.
    image_block_seq: Cell<usize>,
    /// Alternating `Theme::table_row_even` / `table_row_odd` fill for table
    /// data rows; `config.table.row_striping`.
    pub(super) row_striping: bool,
    /// Render H1 headings as big text, falling back to the one-line rendering
    /// when the title is too wide or non-ASCII; `config.editor.big_h1`.
    big_h1: bool,
    /// Per-token colors for fenced code blocks naming a grammar we ship;
    /// `config.editor.syntax_highlighting`.  When false the highlighter is
    /// never called and body rows are single-span lines.
    syntax_highlighting: bool,
    /// Reflow prose paragraphs: a soft break becomes a space and the paragraph
    /// wraps to the viewport as one flow, instead of each source line getting
    /// its own rendered row.  A hard break still forces a row split.  See
    /// `docs/dev/plans/paragraph-reflow.md`.
    reflow_paragraphs: bool,
}

impl<'t> Renderer<'t> {
    pub fn new(theme: &'t Theme) -> Self {
        Self {
            theme,
            viewport_width: 80,
            inset: Cell::new(0),
            surface: Cell::new(None),
            code_wrap: false,
            image_max_height: 24,
            image_row_override: None,
            image_block_seq: Cell::new(0),
            row_striping: false,
            big_h1: false,
            syntax_highlighting: false,
            reflow_paragraphs: false,
        }
    }

    pub fn with_viewport_width(mut self, width: usize) -> Self {
        self.viewport_width = width;
        self
    }

    /// Used by tests in this module and `ui::preview`.
    #[allow(dead_code)]
    pub fn with_code_wrap(mut self, wrap: bool) -> Self {
        self.code_wrap = wrap;
        self
    }

    pub fn with_image_max_height(mut self, rows: usize) -> Self {
        self.image_max_height = rows.max(1);
        self
    }

    /// Install a `(URL, ordinal)` → row-count callback that overrides
    /// `image_max_height` per image.  Reserves exactly the rows a decoded
    /// image will occupy, and collapses the block whose raw source the cursor
    /// has revealed.
    pub fn with_image_row_override(mut self, override_fn: ImageRowOverride<'t>) -> Self {
        self.image_row_override = Some(override_fn);
        self
    }

    pub fn with_row_striping(mut self, on: bool) -> Self {
        self.row_striping = on;
        self
    }

    pub fn with_big_h1(mut self, on: bool) -> Self {
        self.big_h1 = on;
        self
    }

    pub fn with_syntax_highlighting(mut self, on: bool) -> Self {
        self.syntax_highlighting = on;
        self
    }

    pub fn with_reflow_paragraphs(mut self, on: bool) -> Self {
        self.reflow_paragraphs = on;
        self
    }

    /// Render a list of top-level blocks to styled lines.  Tests and
    /// `ui::preview` only; production uses `render_with_counts`.
    #[allow(dead_code)]
    pub fn render(&self, blocks: &[Block]) -> Vec<Line<'static>> {
        let mut sink = RowSink::default();
        for block in blocks {
            self.render_block(block, &mut sink, "", true);
        }
        sink.lines
    }

    /// Render blocks and also return the number of rendered lines each block produced.
    ///
    /// Returns `(rows, per_block_counts)` where `per_block_counts[i]` is the number of rows
    /// (lines and their origins, in lockstep) that block `i` appended to `rows`.
    pub fn render_with_counts(&self, blocks: &[Block]) -> (RowSink, Vec<usize>) {
        let mut rows = RowSink::default();
        let mut counts = Vec::with_capacity(blocks.len());

        for block in blocks {
            let before = rows.len();
            self.render_block(block, &mut rows, "", true);
            counts.push(rows.len() - before);
        }

        (rows, counts)
    }

    /// Like [`render_with_counts`](Self::render_with_counts), but memoizes
    /// each block's rendered lines in `cache` so blocks unchanged since the
    /// previous build cost a clone instead of a re-render.  See
    /// [`RenderCache`] for the keying and eviction rules.
    pub fn render_with_counts_cached(
        &self,
        blocks: &[Block],
        cache: &mut RenderCache,
    ) -> (RowSink, Vec<usize>) {
        let mut prev = cache.begin_build(RenderSettings {
            theme_addr: self.theme as *const Theme as usize,
            viewport_width: self.viewport_width,
            code_wrap: self.code_wrap,
            image_max_height: self.image_max_height,
            row_striping: self.row_striping,
            big_h1: self.big_h1,
            syntax_highlighting: self.syntax_highlighting,
            reflow_paragraphs: self.reflow_paragraphs,
            // Read here rather than threaded in from `EditorState`: the
            // renderer consults the warm grammars, so this is the one place
            // that can't fall out of step with them.  Pinned to 0 when off so
            // toggling can't leave a stale generation in the fingerprint.
            highlight_generation: if self.syntax_highlighting {
                highlight::warm_generation()
            } else {
                0
            },
            // A grammar refused for want of budget warms nothing, so the
            // generation above cannot move for it; without this field the
            // retry `App::tick_syntax_warm` drives would reparse into a fully
            // warm cache and never call the highlighter again.
            highlight_retry_epoch: if self.syntax_highlighting {
                highlight::retry_epoch()
            } else {
                0
            },
        });

        let mut rows = RowSink::with_capacity(cache.last_row_count);
        let mut counts = Vec::with_capacity(blocks.len());
        for block in blocks {
            let before = rows.len();
            // ImageBlock row counts track the decode cache, which changes
            // without the AST changing — never cache them.  Cheap-to-render
            // blocks bypass the cache too: a hash + line-clone costs more than
            // re-rendering them (#35 §2, `is_cache_worthy`).
            if matches!(block, Block::ImageBlock { .. }) || !is_cache_worthy(block) {
                self.render_block(block, &mut rows, "", true);
            } else {
                // One hash per block per build: each `Block` hash walks a deep value.
                let hash = BlockMap::hash(block);
                if let Some(hit) = cache.entries.get(hash, block) {
                    // A block repeated earlier in this build, already moved over.
                    rows.extend_from(&hit.lines, &hit.origins);
                } else if let Some((key, hit)) = prev.take(hash, block) {
                    rows.extend_from(&hit.lines, &hit.origins);
                    cache.entries.insert_new(hash, key, hit);
                } else {
                    self.render_block(block, &mut rows, "", true);
                    // Origins are block-relative, so a cached block's rows hold wherever it
                    // moves.
                    cache.entries.insert_new(
                        hash,
                        block.clone(),
                        CachedRows {
                            lines: rows.lines[before..].to_vec(),
                            origins: rows.origins[before..].to_vec(),
                        },
                    );
                }
            }
            counts.push(rows.len() - before);
        }

        cache.last_row_count = rows.len();
        // `prev` drops here, evicting entries whose block is gone.
        (rows, counts)
    }

    // ── Block rendering ───────────────────────────────────────────

    /// Cells available to the block being rendered: the viewport less the prefixes its
    /// containers will add to each row.  What table widths, rules and code surfaces size to, so
    /// a quoted one ends at the viewport edge instead of wrapping past it.
    pub(super) fn width(&self) -> usize {
        self.viewport_width.saturating_sub(self.inset.get())
    }

    /// Run `f` with [`width`](Self::width) narrowed by `cells`, for a container rendering
    /// children it will prefix by that many cells.
    fn inset_by<R>(&self, cells: usize, f: impl FnOnce() -> R) -> R {
        let outer = self.inset.replace(self.inset.get() + cells);
        let r = f();
        self.inset.set(outer);
        r
    }

    /// Run `f` with [`surface`](Self::surface) set to `bg`, for a container painting `bg` under
    /// its children.  A container painting no background leaves the outer one.
    fn on_surface<R>(&self, bg: Option<Color>, f: impl FnOnce() -> R) -> R {
        let outer = self.surface.replace(bg.or(self.surface.get()));
        let r = f();
        self.surface.set(outer);
        r
    }

    /// The background behind the block being rendered, `Color::Reset` (the terminal's own) on
    /// the page.
    pub(super) fn surface_bg(&self) -> Color {
        self.surface.get().unwrap_or(Color::Reset)
    }

    pub(super) fn render_block(
        &self,
        block: &Block,
        out: &mut RowSink,
        indent_prefix: &str,
        // Whether `block` is a top-level document block.  Nested calls (blockquote children,
        // list-item blocks, footnote-definition bodies) pass `false`: a setext H2 gets no rule,
        // and a list renders loose spacing only directly inside a quote (see
        // `render_blockquote`).
        top_level: bool,
    ) {
        match block {
            Block::Heading {
                level,
                inlines,
                src,
            } => {
                self.render_heading(*level, inlines, src, top_level, out);
            }
            Block::Paragraph { inlines, src } => {
                // A `$$...$$`-only paragraph that survived promotion (figures disabled) renders
                // as a fenced-style ` math ` code block — the source counterpart of the
                // display-math reveal — matching how a `` ```mermaid `` fence stays a code block
                // when figures are off.
                if let Some(body) =
                    crate::markdown::parser::post_pass::display_math_block_body(block)
                {
                    self.render_code_block(Some("math"), &body, true, src, CodeCols::Formula, out);
                } else {
                    self.render_paragraph(inlines, src, out, indent_prefix);
                }
            }
            Block::CodeBlock {
                language,
                content,
                fenced,
                src,
            } => {
                self.render_code_block(
                    language.as_deref(),
                    content,
                    *fenced,
                    src,
                    CodeCols::PerLine,
                    out,
                );
            }
            Block::BlockQuote {
                blocks,
                span,
                hidden,
            } => {
                self.render_blockquote(blocks, span, hidden, out);
            }
            Block::List {
                ordered,
                start,
                items,
                ..
            } => {
                self.render_list(*ordered, *start, items, out, indent_prefix);
            }
            Block::HorizontalRule { src } => {
                out.push(
                    Line::styled("─".repeat(self.width().max(1)), self.theme.rule),
                    RowOrigin::chrome(Some(src.first)),
                );
            }
            Block::Table {
                col_count,
                headers,
                rows,
                user_widths,
                src,
            } => {
                self.render_table(*col_count, headers, rows, user_widths.as_deref(), src, out);
            }
            Block::Html(html, src) => {
                let prefix_cells = str_cells(indent_prefix);
                for (k, line) in html.lines().enumerate() {
                    let row =
                        Line::styled(format!("{indent_prefix}{line}"), self.theme.code_block_text);
                    let origin = verbatim_origin(src, k, prefix_cells).hung_under_indent(&row);
                    out.push(row, origin);
                }
            }
            Block::HtmlComment(..) => {
                // Annotation, not content: zero rendered lines (raw mode reads
                // the rope directly, so the source stays visible there).
            }
            Block::ImageBlock { alt, url, src } => {
                self.render_image_block(alt, url, src, out);
            }
            Block::MetadataBlock { kind, content, src } => {
                self.render_metadata_block(*kind, content, src, out);
            }
            Block::FootnoteDefinition {
                label,
                blocks,
                span,
                hidden,
            } => {
                self.render_footnote_definition(label, blocks, span, hidden, out);
            }
        }
        debug_assert_eq!(
            out.lines.len(),
            out.origins.len(),
            "rows and origins drifted"
        );
    }

    // ── Frontmatter ───────────────────────────────────────────────
    //
    // A metadata block renders *verbatim* — one rendered row per source line,
    // every character in its source column — so the raw↔rendered column map
    // stays the identity function and the row count stays 1:1 with the source
    // lines (what the raw reveal requires).  Rendering only adds color.

    fn render_metadata_block(
        &self,
        kind: MetadataKind,
        content: &str,
        src: &SrcLines,
        out: &mut RowSink,
    ) {
        let delim = kind.delimiter();
        out.push(
            Line::styled(delim.to_string(), self.theme.frontmatter_delimiter),
            RowOrigin::chrome(Some(src.first)),
        );
        let mut k = 0;
        for line in content.lines() {
            k += 1;
            let row = self.metadata_line(kind, line);
            let origin = verbatim_origin(src, k, 0).hung_under_indent(&row);
            out.push(row, origin);
        }
        out.push(
            Line::styled(delim.to_string(), self.theme.frontmatter_delimiter),
            RowOrigin::chrome(Some(line_at(src, k + 1))),
        );
    }

    /// Split one frontmatter line into a `key`-styled head and a
    /// `value`-styled tail.  Cosmetic — a shallow separator scan, not a
    /// YAML/TOML parse — so an unreadable line renders whole in the value
    /// style.  The spans concatenate back to `line` byte for byte either way.
    fn metadata_line(&self, kind: MetadataKind, line: &str) -> Line<'static> {
        let sep = match kind {
            MetadataKind::Yaml => ':',
            MetadataKind::Toml => '=',
        };
        if let Some(idx) = metadata_key_end(line, sep) {
            let (key, rest) = line.split_at(idx);
            return Line::from(vec![
                Span::styled(key.to_string(), self.theme.frontmatter_key),
                Span::styled(rest.to_string(), self.theme.frontmatter_value),
            ]);
        }
        Line::styled(line.to_string(), self.theme.frontmatter_value)
    }

    // ── Footnote definition ───────────────────────────────────────
    //
    // Rendered in place as `  <label>.  definition body text… ↩`.
    //
    // The leader is column-width-matched to the raw `[^<label>]: ` it replaces,
    // so the 1:1 rendered↔raw column mapping holds across the body.  The
    // trailing `↩` is appended chrome backed by no raw byte, so the mouse layer
    // hit-tests it on the rendered line
    // (`mouse_ops::footnotes::back_link_glyph_at_click`).

    fn render_footnote_definition(
        &self,
        label: &str,
        blocks: &[Block],
        span: &LineSpan,
        hidden: &[u32],
        out: &mut RowSink,
    ) {
        let leader = format!("  {label}.  ");
        // Every row sits behind the leader or its width of indent, measured once in cells; the
        // `↩` is trailing chrome.
        let shift = str_cells(&leader);
        let mut body = RowSink::default();
        self.inset_by(shift, || {
            render_children(&mut body, blocks, None, hidden, |_, b, body| {
                self.render_block(b, body, "", false);
            });
        });
        let cont_indent = spaces(shift);
        let back = " ↩";

        if body.is_empty() {
            out.push(
                Line::from(vec![
                    Span::styled(leader, self.theme.footnote),
                    Span::styled(back.to_string(), self.theme.footnote),
                ]),
                RowOrigin::chrome(Some(span.start)),
            );
            return;
        }

        let last = body.len() - 1;
        for (i, (line, origin)) in body.into_rows().enumerate() {
            let mut spans: Vec<Span<'static>> = Vec::new();
            if i == 0 {
                spans.push(Span::styled(leader.clone(), self.theme.footnote));
            } else {
                spans.push(Span::styled(cont_indent.clone(), self.theme.footnote));
            }
            spans.extend(line.spans);
            if i == last {
                spans.push(Span::styled(back.to_string(), self.theme.footnote));
            }
            out.push(Line::from(spans), origin.shifted(shift));
        }
    }

    // ── Image block ───────────────────────────────────────────────
    //
    // Emits N rows: an `[Image: alt]` placeholder (what unsupported terminals
    // and raw-reveal show) followed by empty lines reserving space for the
    // overlay `ui::image_view::paint_images` paints afterwards.
    //
    // N comes from `image_row_override` once decoded, else `image_max_height`
    // — which keeps `per_block_own` stable while pending or failed, so
    // navigation doesn't depend on decode order.

    fn render_image_block(&self, alt: &str, url: &str, src: &SrcLines, out: &mut RowSink) {
        let name = if alt.trim().is_empty() {
            link_fallback(url)
        } else {
            alt.to_owned()
        };
        let placeholder = Line::from(vec![
            Span::styled(format!("[{}", IMAGE_PREFIX), self.theme.image_placeholder),
            Span::styled(
                name,
                self.theme
                    .image_placeholder
                    .add_modifier(Modifier::UNDERLINED),
            ),
            Span::styled("]", self.theme.image_placeholder),
        ]);
        // Reserved row `k` shows source line `k`, clamped to the last: a one-line image pins every
        // row to its line, and a diagram's reveal paints its source lines 1:1 onto these rows.
        // The last row also shows every line past it, so each line has a row while a diagram
        // taller in source than its image is collapsed.
        let ordinal = self.image_block_seq.get();
        self.image_block_seq.set(ordinal + 1);
        let rows = self
            .image_row_override
            .and_then(|f| f(url, ordinal))
            .unwrap_or(self.image_max_height)
            .max(1);
        let last_line = src.len().saturating_sub(1);
        let origin = |k: usize| {
            let line = line_at(src, k.min(last_line));
            let end = if k + 1 == rows {
                line_at(src, src.len()).max(line + 1)
            } else {
                line + 1
            };
            RowOrigin {
                lines: Some(line..end),
                cols: super::row_origin::ColOrigin::Chrome,
                hang: 0,
            }
        };
        out.push(placeholder, origin(0));
        for k in 1..rows {
            out.push(Line::raw(""), origin(k));
        }
    }

    // ── Heading ───────────────────────────────────────────────────

    fn render_heading(
        &self,
        level: pulldown_cmark::HeadingLevel,
        inlines: &[Inline],
        src: &SrcLines,
        top_level: bool,
        out: &mut RowSink,
    ) {
        use pulldown_cmark::HeadingLevel::*;

        // A setext heading's last source line is its underline, which holds no content; an
        // ATX heading is one line.
        let setext = src.len() >= 2;
        let text_lines = if setext { src.len() - 1 } else { 1 };
        let underline = setext.then(|| line_at(src, text_lines));
        // The rule under an H1 shows the underline when there is one, else the heading's line.
        let rule_origin = RowOrigin::chrome(Some(underline.unwrap_or(src.first)));

        if level == H1 && self.big_h1 {
            let glyph_origin = RowOrigin {
                lines: Some(src.first..line_at(src, text_lines)),
                cols: super::row_origin::ColOrigin::Chrome,
                hang: 0,
            };
            if self.try_render_h1_big(inlines, &glyph_origin, &rule_origin, out) {
                return;
            }
        }

        let prefix = match level {
            H1 => " ",
            H2 => "  ",
            H3 => "   ",
            H4 => "    ",
            H5 => "     ",
            H6 => "      ",
        };

        let style = self.theme.heading_style(level);
        let prefix_style = style.remove_modifier(Modifier::UNDERLINED | Modifier::CROSSED_OUT);
        let mut spans = vec![Span::styled(prefix, prefix_style)];
        // A multi-line setext heading's text joins onto one row: a flow, whose soft breaks
        // render as a paragraph's do.
        spans.extend(self.render_inlines(&collapse_soft_breaks(inlines), style));

        let kind = if text_lines > 1 {
            ContentKind::Flow
        } else {
            ContentKind::Inline
        };
        let text_origin = match src.col(0) {
            Some(raw_col) => RowOrigin::content(
                src.first..line_at(src, text_lines),
                raw_col,
                to_u32(str_cells(prefix)),
                kind,
            ),
            // An empty heading (`#`) has no content to map.
            None => RowOrigin::chrome(Some(src.first)),
        };
        out.push(Line::from(spans), text_origin);

        if level == H1 {
            out.push(
                Line::styled("─".repeat(self.width().max(1)), self.theme.h1_rule),
                rule_origin,
            );
        } else if level == H2 && top_level && setext {
            // A setext H2's underline renders as a rule of its own the way an H1's does, so
            // the reveal has a row to show it on.
            out.push(
                Line::styled("─".repeat(self.width().max(1)), self.theme.rule),
                rule_origin,
            );
        }
    }

    // ── Big H1 ────────────────────────────────────────────────────
    //
    // Renders an H1's text as one or two rows of `tui_big_text::BigText` at
    // `PixelSize::Octant` (4 × 2 cells per glyph), emitting
    // `2 * chunks.len() + 1` lines.  The temporary buffers are pre-filled with
    // the palette background so the surrounding empty cells carry the real
    // editor background — `Color::Reset` would render as terminal-default.
    //
    // Returns `false`, emitting nothing, when the title is non-ASCII (font8x8
    // covers ASCII only), when one word is wider than the viewport, or when it
    // needs 3+ wrapped lines — past two, an H1 reads as a poster.  The caller
    // then falls back to the one-line styled rendering.
    fn try_render_h1_big(
        &self,
        inlines: &[Inline],
        glyph_origin: &RowOrigin,
        rule_origin: &RowOrigin,
        out: &mut RowSink,
    ) -> bool {
        const GLYPH_W_PER_CHAR: usize = 4;
        const GLYPH_H: u16 = 2;
        const MAX_WRAPPED_LINES: usize = 2;

        let plain = inlines_to_plain(inlines);
        let normalized = normalise_for_big_text(plain.trim());
        if normalized.is_empty() || !normalized.is_ascii() {
            return false;
        }
        let viewport = self.width().max(1);
        let max_chars = viewport / GLYPH_W_PER_CHAR;
        if max_chars == 0 {
            return false;
        }
        let chunks = match word_wrap_for_big_text(&normalized, max_chars) {
            Some(c) if c.len() <= MAX_WRAPPED_LINES => c,
            _ => return false,
        };

        let bg_style = Style::default().bg(self.theme.palette.bg);
        let text_style = self
            .theme
            .h1
            .remove_modifier(Modifier::UNDERLINED)
            .bg(self.theme.palette.bg);
        let shadow_color = self.theme.palette.bg_muted;
        let blank_spacer = Line::styled(" ".repeat(viewport), bg_style);

        for (chunk_idx, chunk) in chunks.iter().enumerate() {
            // Gap between wrapped chunks, so they don't merge into one
            // 4-row block.
            if chunk_idx > 0 {
                out.push(blank_spacer.clone(), glyph_origin.clone());
            }
            let chunk_glyph_w = chunk.len() * GLYPH_W_PER_CHAR;
            let area = Rect::new(0, 0, viewport as u16, GLYPH_H);
            let mut buf = Buffer::empty(area);
            buf.set_style(area, bg_style);
            let big = BigText::builder()
                .pixel_size(PixelSize::Octant)
                .style(text_style)
                .centered()
                .lines(vec![Line::from(chunk.clone())])
                .build();
            big.render(area, &mut buf);
            let bottom = GLYPH_H - 1;
            let glyph_start_x = (viewport.saturating_sub(chunk_glyph_w)) / 2;
            for (i, ch) in chunk.chars().enumerate() {
                if ch == ' ' {
                    continue;
                }
                let cell_start = glyph_start_x + i * GLYPH_W_PER_CHAR;
                for x in cell_start..cell_start + GLYPH_W_PER_CHAR {
                    buf[(x as u16, bottom)].set_bg(shadow_color);
                }
            }
            for y in 0..GLYPH_H {
                out.push(buffer_row_to_line(&buf, y), glyph_origin.clone());
            }
        }
        out.push(
            Line::styled("─".repeat(viewport), self.theme.h1_rule),
            rule_origin.clone(),
        );
        true
    }

    // ── Paragraph ─────────────────────────────────────────────────

    fn render_paragraph(
        &self,
        inlines: &[Inline],
        src: &SrcLines,
        out: &mut RowSink,
        indent_prefix: &str,
    ) {
        let reflow = paragraph_reflows(self.reflow_paragraphs, inlines);
        // Cloned onto every row: borrowed from the static run when it is only spaces (a list
        // item's indent, the usual case), so the clones allocate nothing.
        let prefix = if indent_prefix.bytes().all(|b| b == b' ') {
            spaces(indent_prefix.len())
        } else {
            Cow::Owned(indent_prefix.to_owned())
        };
        let inlines = paragraph_row_inlines(inlines, reflow);
        let mut rows =
            paragraph_rows(&inlines, src, reflow, to_u32(str_cells(indent_prefix))).peekable();
        while let Some((segment, origin)) = rows.next() {
            let mut spans: Vec<Span<'static>> = Vec::new();
            if !prefix.is_empty() {
                spans.push(Span::raw(prefix.clone()));
            }
            spans.extend(self.render_inlines(segment, Style::default()));

            // Every break emits its line, blank ones included; only a trailing
            // segment holding nothing but the indent prefix is suppressed.
            #[allow(clippy::nonminimal_bool)]
            let keep = rows.peek().is_some()
                || (!spans.is_empty() && !(spans.len() == 1 && spans[0].content.trim().is_empty()));
            if keep {
                out.push(Line::from(spans), origin);
            }
        }
    }

    // ── Code block ────────────────────────────────────────────────

    /// Build one code-block body row: the pad cell, the line's text, and the
    /// background fill out to the viewport edge.
    ///
    /// `tokens` are char ranges **into `text`** — already re-based by the
    /// caller for a wrapped segment.  With none, this reproduces the
    /// single-span pre-highlighting line character for character, which is what
    /// lets an unknown language, a switched-off setting and an over-cap block
    /// share the pre-feature snapshots.
    ///
    /// The leading space is [`CODE_PAD_COLS`], which the row's origin records
    /// as its `rendered_col`, so prefix and constant must agree
    /// (`code_block_render_agrees_with_its_row_origins` catches drift).
    /// Extra spans don't disturb the mapping: `line_render` flattens spans to
    /// `(char, style)` pairs.
    fn code_body_row(&self, text: &str, tokens: &[Token], block_width: usize) -> Line<'static> {
        let base = self.theme.code_block_text;
        // The fill is measured in cells, so a line of wide glyphs isn't padded past the edge
        // into a wrapped blank row.
        let fill = block_width
            .saturating_sub(CODE_PAD_COLS)
            .saturating_sub(str_cells(text));
        if tokens.is_empty() {
            return Line::styled(format!(" {text}{}", " ".repeat(fill)), base);
        }

        let chars: Vec<char> = text.chars().collect();
        let mut spans: Vec<Span<'static>> = Vec::with_capacity(tokens.len() * 2 + 2);
        spans.push(Span::styled(spaces(CODE_PAD_COLS), base));

        let run = |from: usize, to: usize| -> String { chars[from..to].iter().collect() };
        let mut col = 0usize;
        for token in tokens {
            // Clamp: a grammar reporting past end of line should mis-color,
            // never panic on a slice.
            let start = token.range.start.min(chars.len()).max(col);
            let end = token.range.end.min(chars.len()).max(start);
            if col < start {
                spans.push(Span::styled(run(col, start), base));
            }
            if start < end {
                let style = base.patch(highlight::style_for(self.theme, token.class));
                spans.push(Span::styled(run(start, end), style));
            }
            col = end;
        }
        if col < chars.len() {
            spans.push(Span::styled(run(col, chars.len()), base));
        }

        // Fill to the viewport edge, as the unhighlighted row above does.
        if fill > 0 {
            spans.push(Span::styled(spaces(fill), base));
        }
        Line::from(spans).style(base)
    }

    fn render_code_block(
        &self,
        language: Option<&str>,
        content: &str,
        fenced: bool,
        src: &SrcLines,
        cols: CodeCols,
        out: &mut RowSink,
    ) {
        // Strip exactly one trailing empty string (pulldown-cmark always ends
        // code content with '\n'), so a genuine blank line inside the block
        // survives but the final newline adds no spurious row.
        let mut raw_lines: Vec<&str> = content.split('\n').collect();
        if raw_lines.last() == Some(&"") {
            raw_lines.pop();
        }

        // Capped at the viewport so short lines are never over-padded, which
        // would wrap in the terminal and add a blank line after every code row.
        let block_width = self.width().max(1);

        // Body line `i` is the block's source line `i`, or `i + 1` past an opening fence.
        let body_first = usize::from(fenced);
        let first_col = src.col(0);
        let body_origin = |i: usize, chunk_start: usize| -> RowOrigin {
            let k = body_first + i;
            // A body line past the recorded lines can't happen while `display_math_block_body`
            // wants its `$$` on lines of their own; were it to, the row is chrome on the last.
            if k >= src.len() {
                return RowOrigin::chrome(src.span().end.checked_sub(1));
            }
            let col = match cols {
                CodeCols::PerLine => src.col(k),
                CodeCols::Formula => src.col(k).or(first_col),
            };
            let line = line_at(src, k);
            match col {
                Some(c) => RowOrigin::content(
                    line..line.saturating_add(1),
                    c.saturating_add(to_u32(chunk_start)),
                    to_u32(CODE_PAD_COLS),
                    ContentKind::Verbatim,
                ),
                None => RowOrigin::chrome(Some(line)),
            }
        };

        // Opening-fence row: a ` lang ` label when tagged, else an NBSP-padded
        // placeholder.  The ``` glyphs appear only when the cursor enters the
        // row and `RenderedView` reveals its raw source.
        if fenced {
            let fence = RowOrigin::chrome(Some(src.first));
            if let Some(lang) = language {
                out.push(
                    Line::styled(format!(" {} ", lang), self.theme.code_block_lang),
                    fence,
                );
            } else {
                let padded = nbsps(block_width);
                out.push(Line::styled(padded, self.theme.code_block_text), fence);
            }
        }

        // Token runs per body line; empty when the feature is off, no/unknown
        // language, or over `highlight`'s size caps — all of which collapse to
        // `code_body_row` with no tokens.  Asked once for the whole block, not
        // per line: the grammar's parser state runs across lines, which is what
        // classifies a block comment or multi-line string past its first row.
        let tokens = if self.syntax_highlighting {
            highlight::highlight_block(language, &raw_lines)
        } else {
            Vec::new()
        };
        let row_tokens = |i: usize| tokens.get(i).map(Vec::as_slice).unwrap_or(&[]);

        if self.code_wrap {
            // Cells per row: the viewport less the pad cell, and at least one, or a one-cell
            // viewport would never advance.
            let chunk = self.width().saturating_sub(CODE_PAD_COLS).max(1);
            for (i, line) in raw_lines.iter().enumerate() {
                let chars: Vec<char> = line.chars().collect();
                if chars.is_empty() {
                    // NBSP, not spaces: ratatui's WordWrapper treats it as
                    // non-whitespace and so emits no extra blank line.
                    let padded = nbsps(block_width);
                    out.push(
                        Line::styled(padded, self.theme.code_block_text),
                        body_origin(i, 0),
                    );
                    continue;
                }
                // Split by cells, between grapheme clusters: a row of wide glyphs holds half
                // as many chars, and a cluster never straddles two rows.
                for range in table_layout::hard_wrap_ranges(&chars, chunk) {
                    let (start, end) = (range.start, range.end);
                    let slice: String = chars[range].iter().collect();
                    // Tokens address the whole source line, so each segment
                    // takes the overlapping part re-based to its own column 0.
                    let seg = highlight::slice_tokens(row_tokens(i), start, end);
                    let row = self.code_body_row(&slice, &seg, block_width);
                    let origin = body_origin(i, start).hung_under_indent(&row);
                    out.push(row, origin);
                }
            }
        } else {
            // One display line per source line, padded to `block_width` so the
            // surface reaches the viewport edge.  Over-long lines are clipped by
            // the terminal, never truncated here; padding never exceeds the
            // viewport, so short lines do not wrap.
            for (i, line) in raw_lines.iter().enumerate() {
                if line.is_empty() {
                    // NBSP, as in the wrapped path above.
                    let padded = nbsps(block_width);
                    out.push(
                        Line::styled(padded, self.theme.code_block_text),
                        body_origin(i, 0),
                    );
                } else {
                    let row = self.code_body_row(line, row_tokens(i), block_width);
                    let origin = body_origin(i, 0).hung_under_indent(&row);
                    out.push(row, origin);
                }
            }
        }

        // Closing-fence placeholder, revealed the same way as the opening one.  An unclosed
        // fence — every fence while it is being typed — still gets one, which no source line
        // owns.
        if fenced {
            let padded = nbsps(block_width);
            let k = body_first + raw_lines.len();
            let closing = (k < src.len()).then(|| line_at(src, k));
            out.push(
                Line::styled(padded, self.theme.code_block_text),
                RowOrigin::chrome(closing),
            );
        }
    }

    // ── Blockquote ────────────────────────────────────────────────

    fn render_blockquote(
        &self,
        blocks: &[Block],
        span: &LineSpan,
        hidden: &[u32],
        out: &mut RowSink,
    ) {
        // Every bare `>` line renders as a quoted blank row of its own — before, between, or
        // after the children, wherever the source has one — so the quote stays one row per
        // source line.  Those are the lines the children don't cover, less the `hidden` ones.
        // The bar is prefix: content behind it starts two cells later, so the children render
        // two cells narrower.
        let bar_cells = str_cells("▎ ");
        let mut inner = RowSink::default();
        self.on_surface(self.theme.blockquote_text.bg, || {
            self.inset_by(bar_cells, || {
                render_children(&mut inner, blocks, Some(span), hidden, |_, block, inner| {
                    self.render_block(block, inner, "", false);
                });
            })
        });

        for (line, origin) in inner.into_rows() {
            // The quote style is the *base*, not a replacement: each inner span
            // keeps its own resolved style and inherits the wash underneath.
            // Overwriting wholesale silenced every inline style inside a quote
            // (issue #33).  An inner block's line style layers on first, so a
            // nested code block's surface still wins over the wash.
            let base = self.theme.blockquote_text.patch(line.style);
            let bar = Span::styled("▎ ", base.patch(self.theme.blockquote_bar));
            let mut spans = vec![bar];
            for span in line.spans {
                let content = span.content.into_owned();
                spans.push(Span::styled(content, base.patch(span.style)));
            }
            // `line_render` fills trailing cells and wrapped-row indents with
            // the line-level style, so the wash reaches the viewport edge.
            out.push(Line::from(spans).style(base), origin.shifted(bar_cells));
        }
    }

    // ── Inline width helpers ──────────────────────────────────────

    /// Terminal-cell width of a single inline as it would appear when rendered.  Used for table
    /// column width calculation so borders align with content: a CJK glyph is two cells.
    fn rendered_inline_width(&self, inline: &Inline) -> usize {
        match inline {
            Inline::Text(t) | Inline::Html(t) => str_cells(t),
            Inline::Bold(inner)
            | Inline::Italic(inner)
            | Inline::Strikethrough(inner)
            | Inline::Highlight(inner) => self.rendered_inlines_width(inner),
            // Content only; the backticks are dropped, with no pad cells.
            Inline::Code(c) => str_cells(c),
            // The visible text, or a URL/filename fallback when empty.
            Inline::Link { text, url, .. } => {
                let text_width = self.rendered_inlines_width(text);
                if text_width == 0 {
                    str_cells(&link_fallback(url))
                } else {
                    text_width
                }
            }
            // Image renders as "[Image: <alt-or-filename>]".
            Inline::Image { alt, url } => {
                let name_width = if alt.trim().is_empty() {
                    str_cells(&link_fallback(url))
                } else {
                    str_cells(alt)
                };
                str_cells(IMAGE_PREFIX) + name_width + 2
            }
            Inline::HtmlComment(_) => 0,
            // Unreachable: `footnote_run_at` matches a run of one as readily as
            // a run of three, so the only caller measures every reference before
            // this arm is consulted.  Kept for exhaustiveness, and built from
            // `reference_marker` so it can't state a second format.
            Inline::FootnoteReference { label } => {
                let marker = reference_marker(std::iter::once(label.as_str()));
                str_cells(&marker)
            }
            // Math renders as its delimited source — width equals the raw
            // text width, so table borders and cursor columns stay aligned.
            Inline::Math { source, display } => {
                let delim = if *display { "$$" } else { "$" };
                str_cells(delim) + str_cells(source) + str_cells(delim)
            }
            Inline::SoftBreak | Inline::HardBreak => 1,
        }
    }

    pub(super) fn rendered_inlines_width(&self, inlines: &[Inline]) -> usize {
        let mut total = 0;
        let mut i = 0;
        while i < inlines.len() {
            // Adjacent references fuse, so measure the run through the same
            // helper that renders it.
            if let Some((marker, run_len)) = footnote_run_at(inlines, i) {
                total += str_cells(&marker);
                i += run_len;
                continue;
            }
            total += self.rendered_inline_width(&inlines[i]);
            i += 1;
        }
        total
    }

    // ── Inline rendering ──────────────────────────────────────────

    pub(super) fn render_inlines(&self, inlines: &[Inline], base: Style) -> Vec<Span<'static>> {
        let mut out: Vec<Span<'static>> = Vec::new();
        let mut i = 0;
        while i < inlines.len() {
            // Adjacent references collapse into one marker (`[^1][^2]` →
            // `[1,2]`), so the run is consumed as a group.  This is the only
            // rendering entry point, so the fusion can't be bypassed.
            if let Some((marker, run_len)) = footnote_run_at(inlines, i) {
                out.push(Span::styled(marker, base.patch(self.theme.footnote)));
                i += run_len;
                continue;
            }
            // Two links side by side (`[a](x)[b](y)`, or across a vanished break) would read as
            // one run to the hit maps, which find a link by its style (`ui::link_view`,
            // `editor::mouse_ops::links`), so an empty unstyled span ends the first.
            if i > 0 && link_at_edge(&inlines[i - 1], true) && link_at_edge(&inlines[i], false) {
                out.push(Span::raw(""));
            }
            out.extend(self.render_inline(&inlines[i], base));
            i += 1;
        }
        out
    }

    fn render_inline(&self, inline: &Inline, base: Style) -> Vec<Span<'static>> {
        match inline {
            Inline::Text(text) | Inline::Html(text) => vec![Span::styled(text.clone(), base)],

            Inline::Bold(inner) => {
                let style = base.patch(self.theme.bold);
                self.render_inlines(inner, style)
            }

            Inline::Italic(inner) => {
                let style = base.patch(self.theme.italic);
                self.render_inlines(inner, style)
            }

            Inline::Strikethrough(inner) => {
                let style = base.patch(self.theme.strikethrough);
                self.render_inlines(inner, style)
            }

            Inline::Highlight(inner) => {
                let style = base.patch(self.theme.highlight);
                self.render_inlines(inner, style)
            }

            Inline::Code(code) => {
                // Under strikethrough (explicit `~~…~~` or a checked task
                // item), take the dim style and keep CROSSED_OUT so the snippet
                // still reads as struck through.
                let style = if base.add_modifier.contains(Modifier::CROSSED_OUT) {
                    self.theme.code_span_dim.add_modifier(Modifier::CROSSED_OUT)
                } else {
                    self.theme.code_span
                };
                vec![Span::styled(code.clone(), style)]
            }

            Inline::Link { text, url, .. } => {
                // Per-link style by URL kind.
                let style = link_style_for(url, self.theme);
                if shows_fallback(text) {
                    vec![Span::styled(link_fallback(url), style)]
                } else {
                    self.render_inlines(text, style)
                }
            }

            Inline::Image { alt, url } => {
                let name = if alt.trim().is_empty() {
                    link_fallback(url)
                } else {
                    alt.clone()
                };
                vec![
                    Span::styled(format!("[{}", IMAGE_PREFIX), self.theme.image_placeholder),
                    Span::styled(
                        name,
                        self.theme
                            .image_placeholder
                            .add_modifier(Modifier::UNDERLINED),
                    ),
                    Span::styled("]", self.theme.image_placeholder),
                ]
            }

            Inline::HtmlComment(_) => {
                // Annotation, not visible content.
                Vec::new()
            }

            Inline::FootnoteReference { label } => {
                // Unreachable, as in the width arm above: `footnote_run_at`
                // intercepts a lone reference too.  `InlineColMap` accounts for
                // the `[^label]` → `[label]` width difference.
                vec![Span::styled(
                    reference_marker(std::iter::once(label.as_str())),
                    base.patch(self.theme.footnote),
                )]
            }

            // Math renders as its delimited source text in phase 1 —
            // width-equivalent to the raw source, so wrap, cursor columns
            // and the inline column map need no adjustment.  A paragraph
            // holding exactly one display-math inline is promoted to a
            // `Block::ImageBlock` by the post-pass before it ever reaches
            // this arm, so the display form here is the mixed-paragraph
            // fallback only.
            Inline::Math { source, display } => {
                let delim = if *display { "$$" } else { "$" };
                vec![Span::styled(
                    format!("{delim}{source}{delim}"),
                    base.patch(self.theme.code_span),
                )]
            }

            // In its container's style, as a space typed there would be: a reflowed link's
            // break would otherwise cut it into two runs for one link.
            Inline::SoftBreak => vec![Span::styled(" ", base)],

            Inline::HardBreak => {
                // A space here; `render_paragraph` handles the line split.
                vec![Span::styled(" ", base)]
            }
        }
    }
}

/// A paragraph's rows: its inline segments — split at every top-level soft or hard
/// break, unless `join` keeps them one flow — each with the origin of the lines it shows behind
/// `prefix_cells` of prefix.  `inlines` come from [`paragraph_row_inlines`], so every break is
/// top-level and each segment starts on a line of its own.  The caller renders each segment
/// with one `render_inlines` call, so adjacent footnote references still fuse.  Never empty;
/// lazy, so a paragraph allocates nothing here.
pub(super) fn paragraph_rows<'a>(
    inlines: &'a [Inline],
    src: &'a SrcLines,
    join: bool,
    prefix_cells: u32,
) -> impl Iterator<Item = (&'a [Inline], RowOrigin)> + 'a {
    // A segment begins on a line with a content column — the first line, and every line after a
    // break — and runs through the lines after it that have none (the tail of a multi-line code
    // span).
    let len = src.len();
    let next_start = move |from: usize| (from..len).find(|&k| src.col(k).is_some());
    let mut line = 0usize;
    // Joining makes a paragraph's soft breaks one flow that `line_render` wraps to the
    // viewport; without it, each break gets its own row (CommonMark collapses soft breaks to
    // spaces, but the rendered form then mirrors the source line-for-line).
    inlines
        .split(move |i| !join && matches!(i, Inline::HardBreak | Inline::SoftBreak))
        .map(move |segment| {
            if join {
                let raw_col = (0..len).find_map(|k| src.col(k)).unwrap_or(0);
                let origin =
                    RowOrigin::content(src.span(), raw_col, prefix_cells, ContentKind::Flow);
                return (segment, origin);
            }
            let Some(k) = next_start(line) else {
                line = len;
                return (segment, RowOrigin::chrome(src.span().end.checked_sub(1)));
            };
            let end = next_start(k + 1).unwrap_or(len);
            line = end;
            let kind = if end - k > 1 {
                ContentKind::Flow
            } else {
                ContentKind::Inline
            };
            let raw_col = src.col(k).unwrap_or(0);
            let lines = line_at(src, k)..line_at(src, end);
            (
                segment,
                RowOrigin::content(lines, raw_col, prefix_cells, kind),
            )
        })
}

/// One blank row per line of `lines` (a gap in a container), less the `hidden` ones (link
/// reference definitions, which render nothing): a container shows each blank source line inside
/// it, so it stays one row per line.
pub(super) fn push_gap_rows(out: &mut RowSink, lines: std::ops::Range<u32>, hidden: &[u32]) {
    for line in lines.filter(|line| !hidden.contains(line)) {
        out.push(Line::from(""), RowOrigin::chrome(Some(line)));
    }
}

/// Render a container's children with `render(index, block, out)`, each behind the gap rows
/// ([`push_gap_rows`]) for the lines between it and the previous child.  With `outer` (a
/// blockquote's span), the lines before the first child and after the last get rows too.
pub(super) fn render_children(
    out: &mut RowSink,
    blocks: &[Block],
    outer: Option<&LineSpan>,
    hidden: &[u32],
    mut render: impl FnMut(usize, &Block, &mut RowSink),
) {
    let mut next_line = outer.map(|span| span.start);
    for (i, block) in blocks.iter().enumerate() {
        let span = block.span();
        if let Some(line) = next_line {
            push_gap_rows(out, line..span.start, hidden);
        }
        render(i, block, out);
        next_line = Some(next_line.map_or(span.end, |line| line.max(span.end)));
    }
    if let Some(outer) = outer {
        push_gap_rows(out, next_line.unwrap_or(outer.start)..outer.end, hidden);
    }
}

/// Whether a paragraph of `inlines` renders as one reflowed flow, at any depth: `reflow` is on
/// and the paragraph has no hard break, at any depth (`*a\⏎b*` breaks inside the emphasis).  A
/// hard break would make the flow several logical lines, each spanning several source lines,
/// which the stacked reveal (one row expanding to its source lines) can't express, so such a
/// paragraph keeps one row per source line, as with reflow off.  The renderer, the link
/// hit-test (`ui::link_view`) and
/// [`row_map::stacked_lines`](crate::document::row_map::stacked_lines) all ask it.
pub(crate) fn paragraph_reflows(reflow: bool, inlines: &[Inline]) -> bool {
    reflow && !holds(inlines, |i| matches!(i, Inline::HardBreak))
}

/// The inlines a paragraph's rows are cut from: when `join` keeps them one flow, as parsed less
/// the soft breaks that render as nothing ([`collapse_soft_breaks`]), else with every emphasis,
/// link and highlight a break falls inside cut in two at it ([`split_at_breaks`]), so each
/// source line's text is a top-level segment of its own.
pub(crate) fn paragraph_row_inlines(inlines: &[Inline], join: bool) -> Cow<'_, [Inline]> {
    if join {
        collapse_soft_breaks(inlines)
    } else {
        split_at_breaks(inlines)
    }
}

/// `inlines` less every soft break that renders as nothing in a flow: one between two CJK glyphs
/// ([`segment_break::vanishes`]), judged on the chars rendered either side of it, at any depth
/// (`**日本**⏎語`).  The rest still render as a space.  Borrowed when none vanishes, as in
/// every paragraph that isn't CJK.
pub(crate) fn collapse_soft_breaks(inlines: &[Inline]) -> Cow<'_, [Inline]> {
    if !holds(inlines, |i| matches!(i, Inline::SoftBreak)) {
        return Cow::Borrowed(inlines);
    }
    let mut scan = BreakScan::default();
    scan.walk(inlines);
    if !scan.vanishing.contains(&true) {
        return Cow::Borrowed(inlines);
    }
    let mut vanishing = scan.vanishing.into_iter();
    Cow::Owned(drop_vanishing(inlines, &mut vanishing))
}

/// Each soft break's fate, in render order, from the chars rendered around it.
#[derive(Default)]
struct BreakScan {
    /// Per soft break: whether it vanishes.
    vanishing: Vec<bool>,
    /// The last char rendered so far; a break counts as the space it renders until the chars
    /// after it say otherwise, so of two breaks with nothing between them, neither vanishes.
    last: Option<char>,
    /// The break waiting on the char after it: its index and the char before it.
    pending: Option<(usize, char)>,
}

impl BreakScan {
    fn walk(&mut self, inlines: &[Inline]) {
        for inline in inlines {
            match inline {
                Inline::Text(t) | Inline::Html(t) | Inline::Code(t) => self.text(t),
                Inline::Bold(inner)
                | Inline::Italic(inner)
                | Inline::Strikethrough(inner)
                | Inline::Highlight(inner) => self.walk(inner),
                // As `render_inline` shows it: the text, or the URL fallback for a blank one.
                Inline::Link { text, url, .. } => {
                    if shows_fallback(text) {
                        self.text(&link_fallback(url));
                    } else {
                        self.walk(text);
                    }
                }
                // `[Image: …]` and a `[label]` marker.
                Inline::Image { .. } | Inline::FootnoteReference { .. } => self.text("[]"),
                Inline::Math { .. } => self.text("$"),
                Inline::HtmlComment(_) => {}
                Inline::HardBreak => self.text(" "),
                Inline::SoftBreak => {
                    self.pending = self.last.map(|before| (self.vanishing.len(), before));
                    self.vanishing.push(false);
                    self.last = Some(' ');
                }
            }
        }
    }

    /// Rendered text: only its first and last chars matter.
    fn text(&mut self, text: &str) {
        let Some(first) = text.chars().next() else {
            return;
        };
        if let Some((k, before)) = self.pending.take() {
            self.vanishing[k] = segment_break::vanishes(before, first);
        }
        self.last = text.chars().next_back();
    }
}

/// `inlines` with each soft break `vanishing` says vanishes (one entry per break, in order) left
/// out.  A link showing its URL fallback is left whole: [`BreakScan`] reads none of its text,
/// so gives the breaks in it no entry.
fn drop_vanishing(inlines: &[Inline], vanishing: &mut impl Iterator<Item = bool>) -> Vec<Inline> {
    let mut out = Vec::with_capacity(inlines.len());
    for inline in inlines {
        match inline {
            Inline::SoftBreak => {
                if vanishing.next() != Some(true) {
                    out.push(Inline::SoftBreak);
                }
            }
            Inline::Link { text, .. } if shows_fallback(text) => out.push(inline.clone()),
            _ => match children(inline).filter(|c| holds(c, |i| matches!(i, Inline::SoftBreak))) {
                Some(inner) => out.push(with_children(inline, drop_vanishing(inner, vanishing))),
                None => out.push(inline.clone()),
            },
        }
    }
    out
}

/// Whether a link with `text` renders its URL fallback ([`link_fallback`]) instead: its text
/// renders blank — [`inlines_to_plain`] of it trims to nothing.
///
/// Walked rather than built and trimmed: it is asked of every link on every render, and the
/// plain text is blank exactly when every piece of it is (a soft break's space, or its removal
/// between CJK glyphs, is blank either way).
fn shows_fallback(text: &[Inline]) -> bool {
    text.iter().all(|inline| match inline {
        Inline::Text(t) | Inline::Html(t) | Inline::Code(t) => t.trim().is_empty(),
        Inline::Image { alt, .. } => alt.trim().is_empty(),
        Inline::Bold(inner)
        | Inline::Italic(inner)
        | Inline::Strikethrough(inner)
        | Inline::Highlight(inner)
        | Inline::Link { text: inner, .. } => shows_fallback(inner),
        // Rendered with its `$` delimiters, never blank.
        Inline::Math { .. } => false,
        Inline::HtmlComment(_)
        | Inline::FootnoteReference { .. }
        | Inline::SoftBreak
        | Inline::HardBreak => true,
    })
}

/// `inlines` with every soft or hard break lifted to the top level: a container a break falls
/// inside becomes two of the same kind around it (`Italic([a, ⏎, b])` → `Italic([a])`, `⏎`,
/// `Italic([b])`), a link keeping its URL and title on both halves; a half left with nothing in
/// it is dropped.  Borrowed when no container holds a break, as in most paragraphs.
pub(crate) fn split_at_breaks(inlines: &[Inline]) -> Cow<'_, [Inline]> {
    if !inlines
        .iter()
        .any(|i| children(i).is_some_and(|c| holds(c, is_break)))
    {
        return Cow::Borrowed(inlines);
    }
    let mut out = Vec::with_capacity(inlines.len() + 2);
    for inline in inlines {
        push_split(inline, &mut out);
    }
    Cow::Owned(out)
}

/// Push `inline` onto `out`, cut at every break inside it (see [`split_at_breaks`]).  A link
/// showing its URL fallback has no halves to show: its breaks come first, then the link, so the
/// fallback shows once, on its last line, where its destination is.
fn push_split(inline: &Inline, out: &mut Vec<Inline>) {
    let Some(inner) = children(inline).filter(|c| holds(c, is_break)) else {
        out.push(inline.clone());
        return;
    };
    if matches!(inline, Inline::Link { text, .. } if shows_fallback(text)) {
        push_breaks(inner, out);
        out.push(with_children(inline, Vec::new()));
        return;
    }
    let mut flat = Vec::with_capacity(inner.len() + 2);
    for child in inner {
        push_split(child, &mut flat);
    }
    let mut half = Vec::new();
    for child in flat {
        if is_break(&child) {
            if !half.is_empty() {
                out.push(with_children(inline, std::mem::take(&mut half)));
            }
            out.push(child);
        } else {
            half.push(child);
        }
    }
    if !half.is_empty() {
        out.push(with_children(inline, half));
    }
}

/// Push every break in `inlines`, at any depth, onto `out`.
fn push_breaks(inlines: &[Inline], out: &mut Vec<Inline>) {
    for inline in inlines {
        if is_break(inline) {
            out.push(inline.clone());
        } else if let Some(inner) = children(inline) {
            push_breaks(inner, out);
        }
    }
}

fn is_break(inline: &Inline) -> bool {
    matches!(inline, Inline::SoftBreak | Inline::HardBreak)
}

/// Whether any of `inlines`, or anything inside one, satisfies `pred`.
fn holds(inlines: &[Inline], pred: impl Fn(&Inline) -> bool + Copy) -> bool {
    inlines
        .iter()
        .any(|i| pred(i) || children(i).is_some_and(|c| holds(c, pred)))
}

/// Whether `inline` renders a link first (`end` false) or last: it is one, or its first or last
/// child does.
fn link_at_edge(inline: &Inline, end: bool) -> bool {
    match inline {
        Inline::Link { .. } => true,
        _ => children(inline)
            .and_then(|c| if end { c.last() } else { c.first() })
            .is_some_and(|c| link_at_edge(c, end)),
    }
}

/// The inlines inside an emphasis, link or highlight; `None` for a leaf.
fn children(inline: &Inline) -> Option<&[Inline]> {
    match inline {
        Inline::Bold(inner)
        | Inline::Italic(inner)
        | Inline::Strikethrough(inner)
        | Inline::Highlight(inner)
        | Inline::Link { text: inner, .. } => Some(inner),
        _ => None,
    }
}

/// A container of `like`'s kind (and URL, for a link) holding `inner`.  Covers every inline
/// [`children`] answers for, and only those.
fn with_children(like: &Inline, inner: Vec<Inline>) -> Inline {
    match like {
        Inline::Bold(_) => Inline::Bold(inner),
        Inline::Italic(_) => Inline::Italic(inner),
        Inline::Strikethrough(_) => Inline::Strikethrough(inner),
        Inline::Highlight(_) => Inline::Highlight(inner),
        Inline::Link { url, title, .. } => Inline::Link {
            text: inner,
            url: url.clone(),
            title: title.clone(),
        },
        leaf => unreachable!("`children` has no container {leaf:?}"),
    }
}

/// Where a code block's body rows take their raw columns from.
#[derive(Debug, Clone, Copy)]
enum CodeCols {
    /// Each body line's own recorded column: a real code block.
    PerLine,
    /// A figures-off `$$…$$` paragraph's: each body line's column
    /// ([`post_pass::with_formula_cols`]), else the opening line's.
    ///
    /// [`post_pass::with_formula_cols`]: crate::markdown::parser::post_pass::with_formula_cols
    Formula,
}

/// The block-relative line of `src`'s `k`th line.
fn line_at(src: &SrcLines, k: usize) -> u32 {
    src.first.saturating_add(to_u32(k))
}

/// A verbatim row showing `src`'s `k`th line behind `prefix_cells` of prefix; chrome when the
/// line has no content column.
fn verbatim_origin(src: &SrcLines, k: usize, prefix_cells: usize) -> RowOrigin {
    let line = line_at(src, k);
    match src.col(k) {
        Some(c) => RowOrigin::content(
            line..line.saturating_add(1),
            c,
            to_u32(prefix_cells),
            ContentKind::Verbatim,
        ),
        None => RowOrigin::chrome(Some(line)),
    }
}

/// The inline footnote-reference marker: the raw labels of one run of
/// adjacent references, comma-joined inside square brackets (`1` → `[1]`,
/// `note` → `[note]`, `[^1][^2][^3]` → `[1,2,3]`).  Labels are never
/// renumbered for display, so the marker never diverges from the source.
///
/// Matches the `[N]` convention of the bundled export stylesheet
/// (`config/export/default.css`).
///
/// Deliberately plain ASCII: the superscript form (U+207D/U+207E) is absent
/// from most monospace fonts, and a terminal falling back to a proportional
/// face draws it wider than the cell, overlapping the digit.  Do not
/// reintroduce a codepoint outside Basic Latin without re-checking that.
pub(crate) fn reference_marker<'a>(labels: impl IntoIterator<Item = &'a str>) -> String {
    let mut out = String::from("[");
    for (i, label) in labels.into_iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        out.push_str(label);
    }
    out.push(']');
    out
}

/// If a run of adjacent `Inline::FootnoteReference` starts at `start`,
/// return its fused marker and the number of inlines it consumed.
///
/// "Adjacent" means adjacent *inlines* — `[^1][^2]` fuses, `[^1] [^2]` does
/// not, the space being its own `Inline::Text`.  Rendering and width
/// measurement both route through here so their markers can't drift apart.
fn footnote_run_at(inlines: &[Inline], start: usize) -> Option<(String, usize)> {
    if !matches!(inlines.get(start), Some(Inline::FootnoteReference { .. })) {
        return None;
    }
    let labels: Vec<&str> = inlines[start..]
        .iter()
        .map_while(|inline| match inline {
            Inline::FootnoteReference { label } => Some(label.as_str()),
            _ => None,
        })
        .collect();
    let run_len = labels.len();
    Some((reference_marker(labels), run_len))
}

/// Substitute common Unicode typography with ASCII so the big-H1 renderer can
/// show it: font8x8's `basic_latin` table covers exactly U+0020..=U+007E and
/// renders anything else as a blank square.  Rendering-only — the document text
/// is untouched, and whatever is still non-ASCII afterwards makes the caller
/// fall back to the plain render.
fn normalise_for_big_text(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for ch in text.chars() {
        match ch {
            '\u{2014}' | '\u{2013}' => out.push('-'), // em dash, en dash
            '\u{2026}' => out.push_str("..."),        // ellipsis
            '\u{2018}' | '\u{2019}' => out.push('\''), // curly single quotes
            '\u{201C}' | '\u{201D}' => out.push('"'), // curly double quotes
            '\u{00A0}' => out.push(' '),              // non-breaking space
            other => out.push(other),
        }
    }
    out
}

/// Greedy word-wrap for the big-H1 renderer, packing words into lines no wider
/// than `max_chars`.  `None` if any single word exceeds `max_chars`: the caller
/// then falls back to the plain render rather than hard-breaking a word.
fn word_wrap_for_big_text(text: &str, max_chars: usize) -> Option<Vec<String>> {
    let mut lines: Vec<String> = Vec::new();
    let mut current = String::new();
    for word in text.split_whitespace() {
        if word.chars().count() > max_chars {
            return None;
        }
        let needed = if current.is_empty() {
            word.chars().count()
        } else {
            current.chars().count() + 1 + word.chars().count()
        };
        if needed <= max_chars {
            if !current.is_empty() {
                current.push(' ');
            }
            current.push_str(word);
        } else {
            lines.push(std::mem::take(&mut current));
            current.push_str(word);
        }
    }
    if !current.is_empty() {
        lines.push(current);
    }
    if lines.is_empty() {
        None
    } else {
        Some(lines)
    }
}

fn buffer_row_to_line(buf: &Buffer, y: u16) -> Line<'static> {
    let width = buf.area.width;
    let mut spans: Vec<Span<'static>> = Vec::new();
    let mut current = String::new();
    let mut current_style: Option<Style> = None;
    for x in 0..width {
        let cell = &buf[(x, y)];
        let style = Style::default()
            .fg(cell.fg)
            .bg(cell.bg)
            .add_modifier(cell.modifier);
        match current_style {
            Some(prev) if prev == style => current.push_str(cell.symbol()),
            _ => {
                if let Some(prev) = current_style.take() {
                    spans.push(Span::styled(std::mem::take(&mut current), prev));
                }
                current.push_str(cell.symbol());
                current_style = Some(style);
            }
        }
    }
    if let Some(prev) = current_style {
        spans.push(Span::styled(current, prev));
    }
    Line::from(spans)
}

/// Byte index just past the `key` + separator run of a frontmatter line, or
/// `None` when the line has no readable key.
///
/// Deliberately conservative — first `sep` on the line, non-empty key, and the
/// separator followed by a space or end of line — so `url: https://…` splits at
/// the separator rather than the scheme's colon, and `  - tag` doesn't split.
fn metadata_key_end(line: &str, sep: char) -> Option<usize> {
    let idx = line.find(sep)?;
    if line[..idx]
        .trim_start()
        .trim_start_matches("- ")
        .trim()
        .is_empty()
    {
        return None;
    }
    let end = idx + sep.len_utf8();
    let rest = &line[end..];
    if rest.is_empty() || rest.starts_with(' ') {
        Some(end)
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Theme;
    use crate::markdown::parser::parse;

    fn renderer() -> Renderer<'static> {
        // SAFETY: Theme::default() is 'static (no borrows)
        let theme = Box::leak(Box::new(Theme::default()));
        Renderer::new(theme)
    }

    fn render(md: &str) -> Vec<Line<'static>> {
        let blocks = parse(md);
        renderer().render(&blocks)
    }

    /// The walk agrees with the definition it replaced: the link's plain text trims to nothing.
    #[test]
    fn shows_fallback_matches_blank_plain_text() {
        let text = |s: &str| Inline::Text(s.into());
        let cases: Vec<Vec<Inline>> = vec![
            vec![],
            vec![text("")],
            vec![text("  \u{3000}")],
            vec![text("a")],
            vec![text(" "), Inline::SoftBreak, text(" ")],
            vec![Inline::HardBreak],
            vec![Inline::Bold(vec![text(" ")]), Inline::Italic(vec![])],
            vec![Inline::Bold(vec![text(" x ")])],
            vec![Inline::Code(" ".into())],
            vec![Inline::Code("c".into())],
            vec![Inline::Html("<b>".into())],
            vec![Inline::HtmlComment("<!-- c -->".into())],
            vec![Inline::Math {
                source: String::new(),
                display: false,
            }],
        ];
        for inlines in cases {
            assert_eq!(
                shows_fallback(&inlines),
                inlines_to_plain(&inlines).trim().is_empty(),
                "{inlines:?}"
            );
        }
    }

    // ── Display math ─────────────────────────────────────────────────

    /// A ` math ` block's body row maps by its line's own column, and by the `$$` line's where
    /// [`post_pass::with_formula_cols`] recorded none.
    ///
    /// [`post_pass::with_formula_cols`]: crate::markdown::parser::post_pass::with_formula_cols
    #[test]
    fn a_math_block_row_without_a_column_takes_the_opening_lines() {
        let block = Block::Paragraph {
            inlines: vec![Inline::Math {
                source: "\nx\ny\n".into(),
                display: true,
            }],
            src: SrcLines::new(0, &[Some(2), Some(1), None, None]),
        };
        let (rows, _) = renderer().render_with_counts(&[block]);
        let raw_col = |row: usize| match &rows.origins[row].cols {
            crate::markdown::row_origin::ColOrigin::Content { raw_col, .. } => *raw_col,
            other => panic!("row {row} isn't content: {other:?}"),
        };
        assert_eq!((raw_col(1), raw_col(2)), (1, 2), "{:?}", rows.origins);
    }

    // ── Render cache ──────────────────────────────────────────────────

    /// Output-identical to the uncached path on both a cold and a warm cache.
    #[test]
    fn cached_render_matches_uncached() {
        let src = "# Title\n\nSome **bold** prose.\n\n- a\n- b\n\n\
                   | x | y |\n|---|---|\n| 1 | 2 |\n\n```\ncode\n```\n";
        let blocks = parse(src);
        let r = renderer().with_viewport_width(60).with_row_striping(true);
        let (plain_lines, plain_counts) = r.render_with_counts(&blocks);

        let mut cache = RenderCache::default();
        let cold = r.render_with_counts_cached(&blocks, &mut cache);
        let warm = r.render_with_counts_cached(&blocks, &mut cache);
        assert_eq!(cold.0, plain_lines);
        assert_eq!(cold.1, plain_counts);
        assert_eq!(warm.0, plain_lines);
        assert_eq!(warm.1, plain_counts);
    }

    #[test]
    fn cache_evicts_dropped_blocks_and_shares_duplicates() {
        let r = renderer();
        let mut cache = RenderCache::default();

        // Code blocks, not paragraphs: only cache-worthy blocks land in the map
        // now (paragraphs bypass it), so eviction/dedup is only observable on them.
        let first = parse("```\nalpha\n```\n\n```\nbeta\n```\n\n```\nalpha\n```\n");
        assert_eq!(first.len(), 3, "two duplicates plus one distinct block");
        r.render_with_counts_cached(&first, &mut cache);
        assert_eq!(cache.entries.len(), 2, "duplicates share one entry");

        let second = parse("```\nbeta\n```\n\n```\ngamma\n```\n");
        r.render_with_counts_cached(&second, &mut cache);
        assert_eq!(cache.entries.len(), 2);
        assert!(!cache
            .entries
            .keys()
            .any(|b| matches!(b, Block::CodeBlock { content, .. } if content.trim() == "alpha")));
    }

    /// A settings change must invalidate the cache — a stale-width hit would
    /// render tables and code blocks at the wrong width.  Uses a code block: it
    /// is cache-worthy (so the entry actually persists to be invalidated), and
    /// its background fill runs to the viewport edge, so width changes its lines.
    #[test]
    fn cache_cleared_on_settings_change() {
        let blocks = parse("```\ncode\n```\n");
        let mut cache = RenderCache::default();

        let narrow = renderer().with_viewport_width(40);
        let narrow_lines = narrow
            .render_with_counts_cached(&blocks, &mut cache)
            .0
            .lines;

        let wide = renderer().with_viewport_width(120);
        let wide_lines = wide.render_with_counts_cached(&blocks, &mut cache).0.lines;

        assert_ne!(
            narrow_lines, wide_lines,
            "block must re-render at new width"
        );
        assert_eq!(wide_lines, wide.render(&blocks));
    }

    /// The `Block` value is unchanged by the toggle, so without the
    /// `RenderSettings` field a hit would keep painting the old setting.
    #[test]
    fn cache_cleared_when_syntax_highlighting_toggles() {
        let src = "```rust\nfn main() {}\n```\n";
        warm_fence_languages(src);
        let blocks = parse(src);
        let mut cache = RenderCache::default();

        let off = renderer().with_syntax_highlighting(false);
        let off_lines = off.render_with_counts_cached(&blocks, &mut cache).0.lines;

        let on = renderer().with_syntax_highlighting(true);
        let on_lines = on.render_with_counts_cached(&blocks, &mut cache).0.lines;

        assert_ne!(off_lines, on_lines, "the toggle must re-render the block");
        assert_eq!(on_lines, on.render(&blocks));

        // ...and back again, so the invalidation is not one-way.
        let off_again = off.render_with_counts_cached(&blocks, &mut cache).0.lines;
        assert_eq!(off_again, off_lines);
    }

    /// Image row counts track the decode cache, not the AST.
    #[test]
    fn image_blocks_bypass_cache() {
        let blocks = vec![Block::ImageBlock {
            alt: "a".into(),
            url: "img.png".into(),
            src: Default::default(),
        }];
        let mut cache = RenderCache::default();
        renderer().render_with_counts_cached(&blocks, &mut cache);
        assert!(cache.entries.is_empty());
    }

    /// Cheap-to-render blocks bypass the cache (#35 §2): a hash + line-clone
    /// costs more than re-rendering them, so nothing lands in the map.
    #[test]
    fn cheap_blocks_bypass_cache() {
        let blocks = parse("# Heading\n\nplain **prose** here.\n\n- a\n- b\n\n---\n");
        let mut cache = RenderCache::default();
        renderer().render_with_counts_cached(&blocks, &mut cache);
        assert!(
            cache.entries.is_empty(),
            "no Table or CodeBlock present, so nothing is cache-worthy: {:?}",
            cache.entries.keys().collect::<Vec<_>>()
        );
    }

    /// The gate follows nesting: a `List`/`BlockQuote` wrapping a `Table` or
    /// `CodeBlock` stays cache-worthy, or the expensive nested render would run
    /// every keystroke.  A container of only cheap content does not.
    #[test]
    fn is_cache_worthy_follows_nested_expensive_content() {
        use crate::markdown::ast::ListItem;

        let code = || Block::CodeBlock {
            language: None,
            content: "x\n".into(),
            fenced: true,
            src: Default::default(),
        };
        let table = || Block::Table {
            col_count: 1,
            headers: vec![vec![]],
            rows: vec![],
            user_widths: None,
            src: Default::default(),
        };
        let item = |blocks| ListItem {
            blocks,
            task: None,
            span: Default::default(),
            hidden: vec![],
        };
        let list = |items| Block::List {
            ordered: false,
            start: None,
            items,
            span: Default::default(),
        };

        assert!(is_cache_worthy(&code()));
        assert!(is_cache_worthy(&table()));
        assert!(is_cache_worthy(&Block::BlockQuote {
            blocks: vec![table()],
            span: Default::default(),
            hidden: vec![],
        }));
        assert!(is_cache_worthy(&list(vec![item(vec![code()])])));

        assert!(!is_cache_worthy(&Block::Paragraph {
            inlines: vec![],
            src: Default::default(),
        }));
        assert!(!is_cache_worthy(&Block::HorizontalRule {
            src: Default::default()
        }));
        assert!(!is_cache_worthy(&Block::BlockQuote {
            blocks: vec![Block::Paragraph {
                inlines: vec![],
                src: Default::default(),
            }],
            span: Default::default(),
            hidden: vec![],
        }));
        assert!(!is_cache_worthy(&list(vec![item(vec![
            Block::Paragraph {
                inlines: vec![],
                src: Default::default(),
            }
        ])])));
    }

    #[test]
    fn heading_produces_lines() {
        let lines = render("# Hello\n");
        assert!(!lines.is_empty());
        let text: String = lines[0].spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("Hello"));
    }

    // ── Paragraph reflow ──────────────────────────────────────────────

    /// Without reflow (the default), each soft break gets its own rendered row.
    #[test]
    fn soft_breaks_split_rows_by_default() {
        let lines = renderer()
            .with_viewport_width(80)
            .render(&parse("one\ntwo\nthree\n"));
        assert_eq!(lines.len(), 3);
        let texts: Vec<String> = lines
            .iter()
            .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
            .collect();
        assert_eq!(texts, vec!["one", "two", "three"]);
    }

    /// Unreflowed, a link with blank text over a break shows its URL fallback once, on its last
    /// line, where its destination is, however deep it sits and whatever the break; its halves
    /// used to be dropped as empty, so it showed nowhere.
    #[test]
    fn a_blank_link_over_a_break_shows_its_fallback_on_its_last_line() {
        for (src, rows) in [
            ("a [\n](https://x) b\n", &["a ", "https://x b"][..]),
            ("a **[\n](./d/x.md)** b\n", &["a ", "x.md b"]),
            ("a [\\\n](https://x) b\n", &["a ", "https://x b"]),
        ] {
            let lines = renderer().with_viewport_width(80).render(&parse(src));
            let texts: Vec<String> = lines
                .iter()
                .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
                .collect();
            assert_eq!(texts, rows, "{src:?}");
        }
    }

    /// With reflow on, soft breaks become spaces and the paragraph flows to one
    /// row when it fits the viewport.
    #[test]
    fn reflow_joins_soft_breaks_into_one_flow() {
        let lines = renderer()
            .with_viewport_width(80)
            .with_reflow_paragraphs(true)
            .render(&parse("one\ntwo\nthree\n"));
        assert_eq!(lines.len(), 1, "soft-broken lines should reflow to one row");
        let text: String = lines[0].spans.iter().map(|s| s.content.as_ref()).collect();
        assert_eq!(text.trim_end(), "one two three");
    }

    /// A reflowed soft break between CJK glyphs renders as nothing (issue #79), judged on the
    /// chars rendered either side of it at any depth: inside emphasis, beside it, at a link's
    /// edge.  Beside Latin text, Hangul, an image placeholder's bracket or another break it stays
    /// a space.  A link showing its URL fallback has no say over the breaks in its blank text,
    /// nor do they shift any later break's fate.  `inlines_to_plain` drops the same breaks,
    /// wherever it reads the same text (`None`); it reads an image as its alt text, without the
    /// placeholder, and a blank link as its text, not the fallback.
    #[test]
    fn reflow_drops_a_soft_break_between_cjk_glyphs() {
        for (src, flow, plain) in [
            ("日本語の\nリスト\n", "日本語のリスト", None),
            ("日本\n、続き\n", "日本、続き", None),
            ("**日本**\n*語*\n", "日本語", None),
            ("*日\n本*\n", "日本", None),
            ("[日\n本](u)\n語\n", "日本語", None),
            ("日本\nabc\n", "日本 abc", None),
            ("abc\n日本\n", "abc 日本", None),
            ("한국어\n문장\n", "한국어 문장", None),
            (
                "日本\n![画像](x.png)\n",
                "日本 [Image: 画像]",
                Some("日本画像"),
            ),
            ("前`日本\n語`後\n", "前日本 語後", None),
            (
                "日本\n[\n](https://x)\nabc\n語\n本\n",
                "日本 https://x abc 語本",
                Some("日本   abc 語本"),
            ),
        ] {
            let blocks = parse(src);
            let lines = renderer()
                .with_viewport_width(80)
                .with_reflow_paragraphs(true)
                .render(&blocks);
            let text: String = lines[0].spans.iter().map(|s| s.content.as_ref()).collect();
            assert_eq!(text.trim_end(), flow, "{src:?}");
            let Block::Paragraph { inlines, .. } = &blocks[0] else {
                panic!("{blocks:?}");
            };
            assert_eq!(
                inlines_to_plain(inlines),
                plain.unwrap_or(flow),
                "plain text of {src:?}"
            );
        }
    }

    /// Two links side by side end the first with an empty unstyled span, so the hit maps, which
    /// find a link by its style, see two runs: a vanished break joins them (`[日](a)⏎[本](b)`),
    /// as can the source, nested or not.  A link beside text, or a break's space, needs none.
    #[test]
    fn adjacent_links_are_separated_by_an_empty_span() {
        for (src, spans) in [
            ("[日](a)\n[本](b)\n", &["日", "", "本"][..]),
            ("[a](x)[b](y)\n", &["a", "", "b"]),
            ("**[a](x)**[b](y)\n", &["a", "", "b"]),
            ("[a](x)\n[b](y)c\n", &["a", " ", "b", "c"]),
        ] {
            let lines = renderer()
                .with_viewport_width(80)
                .with_reflow_paragraphs(true)
                .render(&parse(src));
            let got: Vec<&str> = lines[0].spans.iter().map(|s| s.content.as_ref()).collect();
            assert_eq!(got, spans, "{src:?}");
        }
    }

    /// A multi-line setext heading's soft break between CJK glyphs renders as nothing, as a
    /// reflowed paragraph's does; beside Latin text it stays a space.
    #[test]
    fn setext_heading_drops_a_soft_break_between_cjk_glyphs() {
        for (src, row) in [
            ("日本\n語\n===\n", " 日本語"),
            ("日本\nabc\n---\n", "  日本 abc"),
        ] {
            let lines = renderer().with_viewport_width(80).render(&parse(src));
            let text: String = lines[0].spans.iter().map(|s| s.content.as_ref()).collect();
            assert_eq!(text.trim_end(), row, "{src:?}");
        }
    }

    /// A paragraph with no vanishing break is borrowed as parsed; one with one loses just that
    /// break.  Without reflow nothing is dropped: each line is a row of its own.
    #[test]
    fn collapse_soft_breaks_borrows_unless_a_break_vanishes() {
        let blocks = parse("one\ntwo *three\nfour*\n");
        let Block::Paragraph { inlines, .. } = &blocks[0] else {
            panic!("{blocks:?}");
        };
        assert!(matches!(collapse_soft_breaks(inlines), Cow::Borrowed(_)));
        let blocks = parse("日本\n語\n");
        let Block::Paragraph { inlines, .. } = &blocks[0] else {
            panic!("{blocks:?}");
        };
        assert_eq!(
            collapse_soft_breaks(inlines).as_ref(),
            [Inline::Text("日本".into()), Inline::Text("語".into())]
        );
        assert!(matches!(
            paragraph_row_inlines(inlines, false),
            Cow::Borrowed(_)
        ));
    }

    /// A paragraph containing a hard break does not reflow at all: it would render as several
    /// logical lines each spanning several source lines, which the reflow-aware consumers can't
    /// map, so it falls back to one row per source line (soft breaks no longer collapse either).
    #[test]
    fn hard_break_paragraph_falls_back_to_one_row_per_line() {
        let lines = renderer()
            .with_viewport_width(80)
            .with_reflow_paragraphs(true)
            .render(&parse("one\ntwo  \nthree\n"));
        let texts: Vec<String> = lines
            .iter()
            .map(|l| {
                l.spans
                    .iter()
                    .map(|s| s.content.as_ref())
                    .collect::<String>()
                    .trim_end()
                    .to_string()
            })
            .collect();
        assert_eq!(texts, vec!["one", "two", "three"]);
    }

    /// Reflow reaches nested paragraphs too: a list item's first and later paragraphs, a
    /// quote's, a footnote's, each one flow behind its prefix, while a hard break keeps its
    /// paragraph one row per source line at any depth.
    #[test]
    fn reflow_joins_nested_paragraphs_into_one_flow_each() {
        let lines = renderer()
            .with_viewport_width(80)
            .with_reflow_paragraphs(true)
            .render(&parse(
                "- a\n  soft\n\n  later\n  para\n- b\\\n  hard\n\n> q\n> more\n\n[^n]: one\n    two\n",
            ));
        let texts: Vec<String> = lines
            .iter()
            .map(|l| {
                l.spans
                    .iter()
                    .map(|s| s.content.as_ref())
                    .collect::<String>()
                    .trim_end()
                    .to_string()
            })
            .collect();
        assert_eq!(
            texts,
            [
                "• a soft",
                "",
                "  later para",
                "• b",
                "  hard",
                "▎ q more",
                "  n.  one two ↩",
            ],
            "{texts:?}"
        );
    }

    /// A block that renders flush (a table, code, a rule, a quote) sits under its item's text
    /// too, at any depth and on a marker line, and sizes to the width left beside the indent.
    #[test]
    fn an_items_flush_blocks_sit_under_its_text() {
        let texts = |src: &str| -> Vec<String> {
            renderer()
                .with_viewport_width(20)
                .render(&parse(src))
                .iter()
                .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
                .collect()
        };
        let table = ["┌─────┐", "│ a   │", "┝━━━━━┥", "│ 1   │", "└─────┘"];
        let indented = |n: usize| table.map(|r| format!("{}{r}", " ".repeat(n)));
        let rows = texts("- x\n\n  | a |\n  |---|\n  | 1 |\n");
        assert_eq!(rows[2..], indented(2), "under `• `");
        let rows = texts("10. | a |\n    |---|\n    | 1 |\n");
        assert_eq!(rows[1..], indented(4), "on a marker line, under `10. `");
        let rows = texts("- x\n  - y\n\n    | a |\n    |---|\n    | 1 |\n");
        assert_eq!(rows[3..], indented(6), "in a nested item");

        let rows = texts("- x\n\n  ---\n\n  > q\n");
        assert_eq!(
            rows[2],
            format!("  {}", "─".repeat(18)),
            "a rule fills what's left"
        );
        assert_eq!(rows[4], "  ▎ q");
        let rows = texts("- x\n\n  ```\n  code\n  ```\n");
        assert!(rows[3].starts_with("   code"), "{:?}", rows[3]);
        assert_eq!(rows[3].chars().count(), 20, "the surface ends at the edge");
    }

    /// A block with a surface keeps it on its line style under an item, so the surface fills
    /// the row's trailing cells, but its indent shows what surrounds the item: the page, or the
    /// wash of a quote holding the list.
    #[test]
    fn an_items_indent_stays_off_a_nested_surface() {
        let theme = Box::leak(Box::new(Theme::default()));
        let wash = theme.blockquote_text.bg;
        assert!(wash.is_some(), "the default theme washes quotes");
        let rows = Renderer::new(theme).render(&parse("- x\n\n  > q\n"));
        assert_eq!(rows[2].style.bg, wash, "the quote's own row");
        assert_eq!(rows[2].spans[0].content, "  ");
        assert_eq!(rows[2].spans[0].style.bg, Some(Color::Reset), "the page");
        let rows = Renderer::new(theme).render(&parse("> - x\n>\n>   ```\n>   c\n>   ```\n"));
        let code = &rows[3];
        assert_eq!(code.style.bg, theme.code_block_text.bg, "{code:?}");
        assert_eq!(code.spans[1].content, "  ", "after the outer bar");
        assert_eq!(code.spans[1].style.bg, wash, "the outer quote");
    }

    /// An item's later blocks align under its text (behind the marker and any task box), and each
    /// blank line between its blocks renders a blank row; a nested list keeps the 4-cell nesting,
    /// and a link reference definition between blocks renders nothing.  A footnote definition
    /// renders the blanks between its blocks too, and a nested loose list those between its
    /// items.
    #[test]
    fn an_items_later_blocks_sit_under_its_text_behind_a_row_per_blank_line() {
        let texts = |src: &str| -> Vec<String> {
            renderer()
                .with_viewport_width(80)
                .render(&parse(src))
                .iter()
                .map(|l| {
                    l.spans
                        .iter()
                        .map(|s| s.content.as_ref())
                        .collect::<String>()
                        .trim_end()
                        .to_string()
                })
                .collect()
        };
        assert_eq!(texts("- a\n\n  b\n"), ["• a", "", "  b"]);
        assert_eq!(texts("1. a\n\n   b\n"), ["1. a", "", "   b"]);
        assert_eq!(texts("- [ ] a\n\n  b\n"), ["• [ ] a", "", "      b"]);
        assert_eq!(texts("- a\n\n\n  b\n"), ["• a", "", "", "  b"]);
        assert_eq!(texts("- a\n\n  - b\n"), ["• a", "", "    • b"]);
        assert_eq!(texts("- a\n\n  [r]: /u\n\n  b\n"), ["• a", "", "", "  b"]);
        assert_eq!(texts("> - a\n>\n>   b\n"), ["▎ • a", "▎", "▎   b"]);
        assert_eq!(texts("[^n]: a\n\n    b\n"), ["  n.  a", "", "      b ↩"]);
        assert_eq!(
            texts("[^n]: a\n\n    [r]: /u\n\n    b\n"),
            ["  n.  a", "", "", "      b ↩"]
        );
        // A loose list keeps its spacing at any depth, between items as within one.
        assert_eq!(
            texts("- x\n  - b\n\n    c\n  - d\n\n  - e\n"),
            ["• x", "    • b", "", "      c", "    • d", "", "    • e"]
        );
    }

    /// Reflow joins soft breaks into one *logical* line; wrapping to the
    /// viewport is `line_render`'s job downstream, so the renderer emits a single
    /// row here even when the flow is wider than the viewport.
    #[test]
    fn reflow_emits_one_logical_line_wider_than_viewport() {
        let lines = renderer()
            .with_viewport_width(10)
            .with_reflow_paragraphs(true)
            .render(&parse("alpha\nbeta\ngamma\ndelta\n"));
        assert_eq!(
            lines.len(),
            1,
            "the renderer joins soft breaks into one line; wrapping is downstream"
        );
        let text: String = lines[0].spans.iter().map(|s| s.content.as_ref()).collect();
        assert_eq!(text.trim_end(), "alpha beta gamma delta");
    }

    #[test]
    fn big_h1_emits_two_glyph_rows_plus_rule() {
        let theme = Box::leak(Box::new(Theme::default()));
        let r = Renderer::new(theme).with_big_h1(true);
        let lines = r.render(&parse("# Hi\n"));
        assert_eq!(
            lines.len(),
            3,
            "expected 2 glyph rows + rule, got {}",
            lines.len()
        );
        for (i, line) in lines.iter().take(2).enumerate() {
            let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
            assert!(
                text.chars().any(|c| !c.is_ascii() && c != ' '),
                "row {i} had no block glyph: {text:?}"
            );
        }
        let rule: String = lines[2].spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(
            rule.contains('─'),
            "expected rule glyph in last line, got {rule:?}"
        );
    }

    #[test]
    fn big_h1_falls_back_for_non_ascii_title() {
        let theme = Box::leak(Box::new(Theme::default()));
        let r = Renderer::new(theme).with_big_h1(true);
        let lines = r.render(&parse("# Héllo\n"));
        assert_eq!(lines.len(), 2, "expected plain 2-line H1 fallback");
    }

    #[test]
    fn big_h1_falls_back_for_unbreakable_word_wider_than_viewport() {
        let theme = Box::leak(Box::new(Theme::default()));
        // 21 chars × 4 = 84 cells, over the 80-col viewport, and unbreakable.
        let r = Renderer::new(theme)
            .with_big_h1(true)
            .with_viewport_width(80);
        let lines = r.render(&parse("# AAAAAAAAAAAAAAAAAAAAA\n"));
        assert_eq!(lines.len(), 2, "expected plain 2-line H1 fallback");
    }

    #[test]
    fn big_h1_falls_back_when_more_than_two_wrapped_lines_needed() {
        let theme = Box::leak(Box::new(Theme::default()));
        // Max 10 chars per line; three 9-char words need 3, over the 2-line cap.
        let r = Renderer::new(theme)
            .with_big_h1(true)
            .with_viewport_width(40);
        let lines = r.render(&parse("# alphabet beanbags carriers\n"));
        assert_eq!(
            lines.len(),
            2,
            "expected plain fallback for 3-line wrap, got {}",
            lines.len()
        );
    }

    #[test]
    fn big_h1_word_wraps_to_two_big_lines_with_blank_spacer() {
        let theme = Box::leak(Box::new(Theme::default()));
        // Max 10 chars per line, so this wraps into two chunks:
        // 2 + 1 spacer + 2 + 1 rule = 6 lines.
        let r = Renderer::new(theme)
            .with_big_h1(true)
            .with_viewport_width(40);
        let lines = r.render(&parse("# hello world!\n"));
        assert_eq!(
            lines.len(),
            6,
            "expected 2 chunks × 2 glyphs + spacer + rule, got {}",
            lines.len()
        );
        for &i in &[0usize, 1, 3, 4] {
            let text: String = lines[i].spans.iter().map(|s| s.content.as_ref()).collect();
            assert!(
                text.chars().any(|c| !c.is_ascii() && c != ' '),
                "glyph row {i} had no block glyph: {text:?}"
            );
        }
        let spacer: String = lines[2].spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(
            !spacer.chars().any(|c| !c.is_ascii() && c != ' '),
            "spacer row should be blank, got {spacer:?}"
        );
        let rule: String = lines[5].spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(rule.contains('─'), "expected rule on last line");
    }

    #[test]
    fn big_h1_renders_em_dash_via_ascii_substitution() {
        let theme = Box::leak(Box::new(Theme::default()));
        let r = Renderer::new(theme).with_big_h1(true);
        // Em dash would fail the ASCII check but is substituted with a hyphen,
        // so this is 2 glyph rows + rule, not the 2-line plain fallback.
        let lines = r.render(&parse("# A — B\n"));
        assert_eq!(
            lines.len(),
            3,
            "em dash should transliterate; got plain fallback ({} lines)",
            lines.len()
        );
    }

    #[test]
    fn normalise_substitutes_common_typography() {
        assert_eq!(normalise_for_big_text("hello — world"), "hello - world");
        assert_eq!(normalise_for_big_text("a–b"), "a-b");
        assert_eq!(normalise_for_big_text("yes…"), "yes...");
        assert_eq!(normalise_for_big_text("‘x’"), "'x'");
        assert_eq!(normalise_for_big_text("“x”"), "\"x\"");
        assert_eq!(normalise_for_big_text("a\u{00A0}b"), "a b");
        // Untabled characters stay put and fail the caller's ASCII check.
        assert_eq!(normalise_for_big_text("café"), "café");
    }

    #[test]
    fn big_h1_off_by_default() {
        let theme = Box::leak(Box::new(Theme::default()));
        let r = Renderer::new(theme);
        let lines = r.render(&parse("# Hi\n"));
        assert_eq!(lines.len(), 2, "default Renderer should not produce big H1");
    }

    #[test]
    fn paragraph_produces_lines() {
        let lines = render("Hello world\n");
        assert!(!lines.is_empty());
    }

    #[test]
    fn horizontal_rule_produces_dashes() {
        let lines = render("---\n");
        let text: String = lines[0].spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains('─'));
    }

    #[test]
    fn code_block_has_content() {
        let lines = render("```\nfoo\n```\n");
        // Line 0 is the opening-fence placeholder.
        let body_text: String = lines[1].spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(body_text.contains("foo"));
    }

    // ── Syntax highlighting ───────────────────────────────────────────

    /// Opt this thread into inline grammar compilation for every language
    /// the source's fences name.
    ///
    /// Compilation is asynchronous in production, so without this a render test
    /// asserts on whichever grammars an unrelated test happened to warm first
    /// and passes or fails by test order.  See `highlight::warm_inline`.
    fn warm_fence_languages(src: &str) {
        for line in src.lines() {
            let Some(info) = line.trim_start().strip_prefix("```") else {
                continue;
            };
            if !info.trim().is_empty() {
                highlight::warm_inline(Some(info.trim()));
            }
        }
    }

    /// Render with highlighting on, which the plain `render` helper leaves off.
    fn render_highlighted(src: &str) -> Vec<Line<'static>> {
        warm_fence_languages(src);
        let blocks = parse(src);
        renderer().with_syntax_highlighting(true).render(&blocks)
    }

    /// The flattened `(text, style)` pairs of one rendered line.
    fn spans_of(line: &Line<'static>) -> Vec<(String, Style)> {
        line.spans
            .iter()
            .map(|s| (s.content.to_string(), s.style))
            .collect()
    }

    fn plain_text(line: &Line<'static>) -> String {
        line.spans.iter().map(|s| s.content.as_ref()).collect()
    }

    #[test]
    fn a_highlighted_code_block_splits_its_body_into_styled_spans() {
        let theme = Theme::default();
        let lines = render_highlighted("```rust\nfn main() {}\n```\n");
        // Line 0 is the ` rust ` label row, line 1 the body.
        let spans = spans_of(&lines[1]);
        assert!(spans.len() > 1, "body should be tokenized, got {spans:?}");
        let keyword = spans.iter().find(|(t, _)| t == "fn").expect("an `fn` span");
        assert_eq!(keyword.1.fg, theme.syntax_keyword.fg);
        let func = spans
            .iter()
            .find(|(t, _)| t == "main")
            .expect("a `main` span");
        assert_eq!(func.1.fg, theme.syntax_function.fg);
    }

    #[test]
    fn token_styles_are_patched_over_the_code_surface() {
        // A token sets a foreground only; the code block's background has
        // to survive, or highlighting punches holes in the surface.
        let theme = Theme::default();
        let lines = render_highlighted("```rust\nfn main() {}\n```\n");
        for (text, style) in spans_of(&lines[1]) {
            assert_eq!(
                style.bg, theme.code_block_text.bg,
                "span {text:?} lost the code surface background"
            );
        }
    }

    #[test]
    fn highlighting_does_not_change_the_text_or_the_row_count() {
        // A code row's column geometry is a property of the characters, not
        // the spans, so text and row count must survive highlighting.
        let src = "```rust\nfn main() {}\nlet x = 1;\n```\n";
        let plain = render(src);
        let lit = render_highlighted(src);
        assert_eq!(plain.len(), lit.len());
        for (a, b) in plain.iter().zip(&lit) {
            assert_eq!(plain_text(a), plain_text(b));
        }
    }

    #[test]
    fn an_unknown_language_renders_exactly_like_highlighting_off() {
        // Unknown language, no language and feature-off are one path.
        for src in [
            "```frobnicate\nfn main() {}\n```\n",
            "```\nfn main() {}\n```\n",
            "    indented code\n",
        ] {
            let plain = render(src);
            let lit = render_highlighted(src);
            assert_eq!(
                plain.iter().map(spans_of).collect::<Vec<_>>(),
                lit.iter().map(spans_of).collect::<Vec<_>>(),
                "{src:?} should be untouched by highlighting"
            );
        }
    }

    #[test]
    fn the_language_label_row_keeps_the_whole_info_string() {
        // Only the grammar lookup takes the first token.
        let lines = render_highlighted("```rust,ignore\nfn main() {}\n```\n");
        assert!(plain_text(&lines[0]).contains("rust,ignore"));
        // ...and the block is still highlighted, via the `rust` prefix.
        let spans = spans_of(&lines[1]);
        assert!(spans.iter().any(|(t, _)| t == "fn"));
    }

    #[test]
    fn a_wrapped_token_keeps_its_style_on_both_rows() {
        // Wrapping splits a source line into rows, so tokens are clipped and
        // re-based per segment.
        let theme = Theme::default();
        let long = format!("let s = \"{}\";", "x".repeat(60));
        let src = format!("```rust\n{long}\n```\n");
        warm_fence_languages(&src);
        let blocks = parse(&src);
        let lines = renderer()
            .with_viewport_width(20)
            .with_code_wrap(true)
            .with_syntax_highlighting(true)
            .render(&blocks);
        let string_rows = lines
            .iter()
            .filter(|l| {
                spans_of(l)
                    .iter()
                    .any(|(t, s)| t.contains('x') && s.fg == theme.syntax_string.fg)
            })
            .count();
        assert!(
            string_rows > 1,
            "the literal should stay styled across every wrapped row"
        );
    }

    /// A code row fills the viewport in cells, not chars: padding a line of wide glyphs by its
    /// char count overran the edge, and the overflow wrapped into a blank row of its own.
    /// Highlighted or not.
    #[test]
    fn a_code_row_of_wide_glyphs_pads_to_the_viewport_edge_in_cells() {
        for src in [
            "```\n日本語のコード\n```\n",
            "```rust\nlet 日本 = 1;\n```\n",
        ] {
            warm_fence_languages(src);
            let blocks = parse(src);
            let lines = renderer()
                .with_viewport_width(20)
                .with_syntax_highlighting(true)
                .render(&blocks);
            let body = lines
                .iter()
                .find(|l| plain_text(l).contains('日'))
                .expect("the code row");
            assert_eq!(str_cells(&plain_text(body)), 20, "in {src:?}");
        }
    }

    /// `code_wrap` splits a line by cells, between grapheme clusters: a row of wide glyphs holds
    /// half as many chars, and a combining mark stays with its base char.
    #[test]
    fn code_wrap_splits_by_cells_between_clusters() {
        let blocks = parse("```\n日本語のコードはとても長い行\n```\n");
        let lines = renderer()
            .with_viewport_width(10)
            .with_code_wrap(true)
            .render(&blocks);
        let body: Vec<String> = lines
            .iter()
            .map(plain_text)
            .filter(|t| t.chars().any(|c| !c.is_whitespace()))
            .collect();
        assert_eq!(body.len(), 4, "{body:?}");
        assert!(body.iter().all(|t| str_cells(t) == 10), "{body:?}");

        let e = "e\u{301}";
        let blocks = parse(&format!("```\n{}\n```\n", e.repeat(12)));
        let lines = renderer()
            .with_viewport_width(10)
            .with_code_wrap(true)
            .render(&blocks);
        assert!(
            lines.iter().all(|l| !plain_text(l).starts_with(" \u{301}")),
            "a row starts with a stranded accent"
        );
    }

    #[test]
    fn a_one_cell_viewport_still_wraps_code_one_char_per_row() {
        let blocks = parse("```\nabc\n```\n");
        let lines = renderer()
            .with_viewport_width(1)
            .with_code_wrap(true)
            .render(&blocks);
        // The label row, three body rows, the closing row.
        assert_eq!(lines.len(), 5);
    }

    #[test]
    fn blockquote_has_bar() {
        let lines = render("> quote\n");
        let first_text: String = lines[0].spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(first_text.contains('▎'));
    }

    /// A bare `>` stays visible as a quoted blank row.
    #[test]
    fn blockquote_blank_line_rendered() {
        let lines = render("> first\n>\n> third\n");
        assert_eq!(lines.len(), 3, "got {} lines", lines.len());
        for line in &lines {
            let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
            assert!(
                text.starts_with("▎"),
                "line did not start with bar: {text:?}"
            );
        }
        let middle: String = lines[1].spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(
            middle.trim_start_matches('▎').trim().is_empty(),
            "middle line not blank: {middle:?}"
        );
    }

    /// Soft breaks produce a new visual line rather than collapsing to spaces.
    #[test]
    fn soft_break_produces_new_line() {
        let lines = render("alpha\nbeta\ngamma\n");
        assert_eq!(lines.len(), 3);
        let texts: Vec<String> = lines
            .iter()
            .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
            .collect();
        assert_eq!(texts, vec!["alpha", "beta", "gamma"]);
    }

    fn line_text(line: &Line<'_>) -> String {
        line.spans.iter().map(|s| s.content.as_ref()).collect()
    }

    #[test]
    fn web_link_shows_only_text() {
        let lines = render("[Google](https://google.com)\n");
        assert_eq!(line_text(&lines[0]), "Google");
    }

    #[test]
    fn file_link_shows_only_text() {
        let lines = render("[Plan](./plan.md)\n");
        assert_eq!(line_text(&lines[0]), "Plan");
    }

    #[test]
    fn web_link_without_text_shows_url() {
        let lines = render("[](https://google.com)\n");
        assert_eq!(line_text(&lines[0]), "https://google.com");
    }

    #[test]
    fn file_link_without_text_shows_filename_only() {
        let lines = render("[](/home/mjw/Work/plan.md)\n");
        assert_eq!(line_text(&lines[0]), "plan.md");
    }

    #[test]
    fn image_with_alt_shows_alt_prefixed() {
        let lines = render("![Cat](/home/mjw/Pictures/me.jpg)\n");
        assert_eq!(line_text(&lines[0]), "[Image: Cat]");
    }

    #[test]
    fn image_without_alt_shows_filename_prefixed() {
        let lines = render("![](/home/mjw/Pictures/me.jpg)\n");
        assert_eq!(line_text(&lines[0]), "[Image: me.jpg]");
    }

    #[test]
    fn inline_code_inside_strikethrough_uses_dim_code_style() {
        let theme = Box::leak(Box::new(Theme::default()));
        let r = Renderer::new(theme);
        let blocks = parse("~~before `snippet` after~~\n");
        let lines = r.render(&blocks);
        let span = lines[0]
            .spans
            .iter()
            .find(|s| s.content.trim() == "snippet")
            .expect("code-span span");
        assert_eq!(span.style.fg, theme.code_span_dim.fg);
        assert!(
            span.style.add_modifier.contains(Modifier::CROSSED_OUT),
            "code span inside strikethrough should still be struck through"
        );
        let plain_lines = r.render(&parse("alpha `snippet` beta\n"));
        let plain_span = plain_lines[0]
            .spans
            .iter()
            .find(|s| s.content.trim() == "snippet")
            .expect("code-span span");
        assert_eq!(plain_span.style.fg, theme.code_span.fg);
    }

    #[test]
    fn inline_code_inside_checked_task_item_uses_dim_code_style() {
        // `task_strikethrough` defaults on, so checked items propagate
        // CROSSED_OUT through `base` into the code span.
        let theme = Box::leak(Box::new(Theme::default()));
        let r = Renderer::new(theme);
        let blocks = parse("- [x] do `thing` now\n");
        let lines = r.render(&blocks);
        let span = lines[0]
            .spans
            .iter()
            .find(|s| s.content.trim() == "thing")
            .expect("code-span span");
        assert_eq!(span.style.fg, theme.code_span_dim.fg);
        assert!(span.style.add_modifier.contains(Modifier::CROSSED_OUT));
    }

    #[test]
    fn link_text_is_underlined() {
        let lines = render("[Google](https://google.com)\n");
        let span = lines[0]
            .spans
            .iter()
            .find(|s| s.content == "Google")
            .expect("link text span");
        assert!(span.style.add_modifier.contains(Modifier::UNDERLINED));
    }

    #[test]
    fn table_has_thick_header_separator_and_inter_row_borders() {
        let src = "| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n";
        let lines = render(src);
        let texts: Vec<String> = lines.iter().map(line_text).collect();
        // Layout: top, header, thick, data1, thin, data2, bottom.
        assert_eq!(texts.len(), 7, "got {texts:#?}");
        assert!(texts[0].starts_with('┌'), "top: {:?}", texts[0]);
        assert!(
            texts[2].starts_with('┝') && texts[2].contains('━') && texts[2].contains('┿'),
            "thick sep: {:?}",
            texts[2]
        );
        assert!(
            texts[4].starts_with('├') && texts[4].contains('┼'),
            "thin sep: {:?}",
            texts[4]
        );
        assert!(texts[6].starts_with('└'), "bottom: {:?}", texts[6]);
    }

    /// Plain-text rendering would drop a wrapped cell's bold/code spans; the
    /// inline-aware wrap keeps them.
    #[test]
    fn table_multirow_cell_preserves_inline_styles() {
        let theme = Box::leak(Box::new(Theme::default()));
        let r = Renderer::new(theme).with_viewport_width(28);

        let blocks = parse(
            "| Name | Notes |\n\
             |---|---|\n\
             | a | This row has a **really** long note |\n",
        );
        let lines = r.render(&blocks);

        let mut found_bold = false;
        for line in &lines {
            for span in &line.spans {
                if span.style.add_modifier.contains(Modifier::BOLD)
                    && span.content.contains("really")
                {
                    found_bold = true;
                }
            }
        }
        assert!(
            found_bold,
            "wrapped cell lost the **really** bold styling — multi-row \
             rendering must preserve inline formatting (lines: {lines:#?})",
        );
    }

    /// A long code span doesn't pin its column wide: the cell's `min` is the
    /// breakable floor, so the table compresses and the span hard-splits.
    #[test]
    fn table_breaks_long_inline_code_to_fit_viewport() {
        let src = "| id | code |\n\
                   |----|------|\n\
                   | 1 | `some_extremely_long_identifier_name` |\n";
        let lines = renderer().with_viewport_width(30).render(&parse(src));
        for line in &lines {
            assert!(
                line.width() <= 30,
                "table must compress to the viewport; overflowing line: {:?}",
                line_text(line)
            );
        }
        let texts: Vec<String> = lines.iter().map(line_text).collect();
        assert!(
            !texts
                .iter()
                .any(|t| t.contains("some_extremely_long_identifier_name")),
            "code span should hard-split across rows: {texts:#?}"
        );
        let squashed: String = texts
            .join("")
            .chars()
            .filter(|c| !c.is_whitespace() && *c != '│')
            .collect();
        assert!(
            squashed.contains("some_extremely_long_identifier_name"),
            "split must preserve every character in order: {texts:#?}"
        );
    }

    #[test]
    fn table_code_span_wraps_without_pads() {
        let src = "| intro `breakable_code_name` | x |\n\
                   |---|---|\n\
                   | a | b |\n";
        let lines = renderer().with_viewport_width(25).render(&parse(src));
        let texts: Vec<String> = lines.iter().map(line_text).collect();
        let joined = texts.join("\n");
        assert!(
            joined.contains("breakable_") && !joined.contains("breakable_code_name"),
            "code span must hard-split across wrap rows: {texts:#?}"
        );
        assert!(
            !joined.contains('\u{00A0}'),
            "code spans render without pad cells: {texts:#?}"
        );
    }

    /// Long link labels are breakable the same way code spans are.
    #[test]
    fn table_breaks_long_link_to_fit_viewport() {
        let src = "| id | link |\n\
                   |----|------|\n\
                   | 1 | [see-the-full-reference-document-here](https://example.com) |\n";
        let lines = renderer().with_viewport_width(30).render(&parse(src));
        for line in &lines {
            assert!(
                line.width() <= 30,
                "table must compress to the viewport; overflowing line: {:?}",
                line_text(line)
            );
        }
    }

    /// A container's prefix comes out of its children's width: a table, rule or code surface
    /// inside a quote (nested or not) or a footnote definition ends at the viewport edge rather
    /// than wrapping past it (#67).
    #[test]
    fn width_sized_blocks_fit_inside_their_containers() {
        let table = "| alpha beta gamma | delta epsilon zeta eta |\n\
                     |---|---|\n\
                     | one two three four | five six seven eight nine |\n";
        // Ends in prose: a footnote's trailing ` ↩` lands on its last row.
        let body = format!("{table}\n---\n\n```\ncode\n```\n\nend\n");
        let quote = |depth: usize| {
            let bar = "> ".repeat(depth);
            body.lines()
                .map(|l| format!("{bar}{l}").trim_end().to_string() + "\n")
                .collect::<String>()
        };
        let footnote = format!(
            "x[^n]\n\n[^n]: lead\n\n{}",
            body.lines()
                .map(|l| format!("    {l}").trim_end().to_string() + "\n")
                .collect::<String>()
        );
        for src in [quote(1), quote(2), footnote] {
            let lines = renderer().with_viewport_width(30).render(&parse(&src));
            for line in &lines {
                assert!(
                    line.width() <= 30,
                    "overflowing line in {src:?}: {:?}",
                    line_text(line)
                );
            }
            let texts: Vec<String> = lines.iter().map(line_text).collect();
            assert!(
                texts.iter().any(|t| t.ends_with('┐') && str_cells(t) == 30),
                "the table should still use the full width available: {texts:#?}"
            );
        }
    }

    /// Prose policy is unchanged: a long plain word is never broken — the
    /// table overflows the viewport horizontally instead.
    #[test]
    fn table_never_breaks_long_prose_word() {
        let src = "| id | word |\n\
                   |----|------|\n\
                   | 1 | someextremelylongunbrokenword |\n";
        let lines = renderer().with_viewport_width(30).render(&parse(src));
        let texts: Vec<String> = lines.iter().map(line_text).collect();
        assert!(
            texts
                .iter()
                .any(|t| t.contains("someextremelylongunbrokenword")),
            "prose word must stay intact on one row: {texts:#?}"
        );
        assert!(
            lines.iter().any(|l| l.width() > 30),
            "table should overflow rather than break prose"
        );
    }

    #[test]
    fn ordered_list_right_aligns_numbers_when_double_digit() {
        let mut src = String::new();
        for i in 1..=12u32 {
            src.push_str(&format!("{i}. item {i}\n"));
        }
        let lines = render(&src);
        // Single-digit items get a leading space to align under two-digit ones.
        assert!(
            line_text(&lines[0]).starts_with(" 1. "),
            "got {:?}",
            line_text(&lines[0])
        );
        assert!(
            line_text(&lines[8]).starts_with(" 9. "),
            "got {:?}",
            line_text(&lines[8])
        );
        assert!(
            line_text(&lines[9]).starts_with("10. "),
            "got {:?}",
            line_text(&lines[9])
        );
    }

    #[test]
    fn nested_ordered_list_aligns_with_source_indent() {
        // Render matches the source's 4-space nesting, so switching to raw view
        // doesn't shift the nested marker.
        let lines = render("1. outer\n    1. inner\n2. next\n");
        assert_eq!(lines.len(), 3);
        assert_eq!(line_text(&lines[0]), "1. outer");
        assert_eq!(line_text(&lines[1]), "    1. inner");
        assert_eq!(line_text(&lines[2]), "2. next");
    }

    #[test]
    fn nested_bullet_list_uses_four_space_indent() {
        // Same `INDENT_WIDTH` as the raw source, so de-rendering doesn't shift.
        let lines = render("- outer\n    - inner\n- next\n");
        assert_eq!(lines.len(), 3);
        assert_eq!(line_text(&lines[0]), "• outer");
        assert_eq!(line_text(&lines[1]), "    • inner");
        assert_eq!(line_text(&lines[2]), "• next");
    }

    #[test]
    fn task_items_render_as_bullet_plus_checkbox() {
        // Tasks are decorated bullets: bullet, then checkbox.
        let lines = render("- [ ] outer\n    - [ ] inner\n- [ ] next\n");
        assert_eq!(lines.len(), 3);
        assert_eq!(line_text(&lines[0]), "• [ ] outer");
        assert_eq!(line_text(&lines[1]), "    • [ ] inner");
        assert_eq!(line_text(&lines[2]), "• [ ] next");
    }

    #[test]
    fn task_and_plain_bullets_coexist_in_one_list() {
        let lines = render("- regular\n- [ ] task\n- [x] done\n");
        assert_eq!(line_text(&lines[0]), "• regular");
        assert_eq!(line_text(&lines[1]), "• [ ] task");
        assert_eq!(line_text(&lines[2]), "• [✓] done");
    }

    /// Regression: a blank-line-separated list is "loose", so pulldown-cmark
    /// wraps each item in a `Paragraph` and the `TaskListMarker` sits inside it
    /// rather than under `Item`.  The parser must find it in both positions.
    #[test]
    fn loose_task_list_still_renders_checkboxes() {
        let lines = render("- [ ] parent\n\n    - [ ] nested\n- [ ] sibling\n");
        assert!(
            line_text(&lines[0]).starts_with("• [ ] parent"),
            "parent should render as a task item with bullet, got {:?}",
            line_text(&lines[0])
        );
        assert!(
            line_text(&lines[lines.len() - 1]).starts_with("• [ ] sibling"),
            "sibling should render as a task item with bullet, got {:?}",
            line_text(&lines[lines.len() - 1])
        );
    }

    #[test]
    fn image_name_is_underlined_but_prefix_is_not() {
        let lines = render("![Cat](/tmp/x.jpg)\n");
        let prefix = lines[0]
            .spans
            .iter()
            .find(|s| s.content == "[Image: ")
            .expect("prefix span");
        let name = lines[0]
            .spans
            .iter()
            .find(|s| s.content == "Cat")
            .expect("name span");
        assert!(!prefix.style.add_modifier.contains(Modifier::UNDERLINED));
        assert!(name.style.add_modifier.contains(Modifier::UNDERLINED));
    }

    // ── HTML comment hiding ───────────────────────────────────────────────

    #[test]
    fn block_level_html_comment_renders_zero_lines() {
        let lines = render("<!-- hidden -->\n");
        assert_eq!(lines.len(), 0, "got {} lines: {lines:?}", lines.len());
    }

    #[test]
    fn block_level_html_comment_between_paragraphs_is_invisible() {
        let lines = render("alpha\n\n<!-- hidden -->\n\nbeta\n");
        let texts: Vec<String> = lines
            .iter()
            .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
            .collect();
        assert!(
            !texts.iter().any(|t| t.contains("<!--")),
            "comment leaked: {texts:?}"
        );
        assert!(texts.iter().any(|t| t.contains("alpha")));
        assert!(texts.iter().any(|t| t.contains("beta")));
    }

    #[test]
    fn inline_html_comment_is_hidden_from_paragraph() {
        let lines = render("before <!-- inline --> after\n");
        assert_eq!(lines.len(), 1);
        let text: String = lines[0].spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(!text.contains("<!--"), "got {text:?}");
        assert!(text.contains("before"));
        assert!(text.contains("after"));
    }

    #[test]
    fn paragraph_containing_only_inline_comments_renders_zero_lines() {
        let lines = render("<!-- only --><!-- comments -->\n");
        assert_eq!(lines.len(), 0, "got {lines:?}");
    }

    /// A setext H2's heading row is an ATX H2's; its underline, a source line of its own,
    /// renders as a rule below it the way an H1's does, so the block stays one row per line.
    #[test]
    fn setext_h2_renders_as_atx_h2_plus_its_underline_rule() {
        let atx_lines = render("## H2 text\n");
        let setext_lines = render("H2 text\n---\n");
        assert_eq!(atx_lines.len(), 1);
        assert_eq!(setext_lines.len(), 2, "{setext_lines:?}");
        assert_eq!(setext_lines[0], atx_lines[0]);
        assert!(line_text(&setext_lines[1]).chars().all(|c| c == '─'));
        // Nested, it renders as before the rule moved here: no rule.
        let nested = render("- a\n\n  H2 text\n  ---\n");
        assert!(
            !nested.iter().map(line_text).any(|t| t.contains('─')),
            "{:?}",
            nested.iter().map(line_text).collect::<Vec<_>>()
        );
    }
}