mdr 0.6.0

A lightweight Markdown viewer with live reload and multiple rendering backends
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
use std::io::{self, IsTerminal, Read};
use std::path::PathBuf;

use crossterm::event::{
    self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyModifiers, MouseEventKind,
};
use crossterm::execute;
use crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use ratatui::prelude::*;
use ratatui::widgets::*;

use ratatui_image::picker::Picker;
use ratatui_image::protocol::StatefulProtocol;
use ratatui_image::{Resize, StatefulImage};

use crate::core::toc::{self, TocEntry};
use crate::core::watcher::Watch;

/// One logical line of text together with its wrapped rendering.
///
/// The unwrapped `source` is kept so the line can be folded again when the
/// terminal is resized, and so search and TOC lookups keep working on the
/// original text rather than on whatever the current width happens to be.
struct WrappedText {
    source: Line<'static>,
    lines: Vec<Line<'static>>,
}

impl WrappedText {
    fn new(source: Line<'static>) -> Self {
        Self {
            lines: vec![source.clone()],
            source,
        }
    }

    fn rewrap(&mut self, width: usize) {
        self.lines = wrap_line(&self.source, width);
    }

    /// Rows this line occupies on screen once wrapped.
    fn height(&self) -> usize {
        self.lines.len().max(1)
    }

    /// The unwrapped text, without styling.
    fn text(&self) -> String {
        self.source
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect()
    }
}

/// Represents a single line element in the rendered content.
/// Lines can be either text (rendered as ratatui Lines) or images (rendered as `StatefulImage`).
enum ContentElement {
    TextLine(WrappedText),
    /// An image element that spans a number of rows in the terminal.
    /// Stores the stateful protocol, alt text (for fallback), and the desired height in rows.
    ///
    /// `StatefulProtocol` is by far the largest variant, so it is boxed to keep
    /// `Vec<ContentElement>` — one entry per rendered line — small.
    Image {
        protocol: Box<StatefulProtocol>,
        _alt: String,
        height: u16,
    },
    /// Fallback placeholder when image loading fails.
    ImagePlaceholder(WrappedText),
}

impl ContentElement {
    /// Returns the number of terminal rows this element occupies.
    /// How many rows this element occupies in the document.
    ///
    /// In `usize`, deliberately: a wrapped paragraph is as tall as its line
    /// count, which nothing bounds to the height of the terminal. Narrowing
    /// here used to wrap around silently past 65535 rows and corrupt the row
    /// arithmetic — the total height, the search offsets and the scrolling all
    /// derive from this. The conversion to `u16` belongs where a value has
    /// already been clipped to the viewport.
    fn row_height(&self) -> usize {
        match self {
            Self::TextLine(text) | Self::ImagePlaceholder(text) => text.height(),
            Self::Image { height, .. } => usize::from(*height),
        }
    }
}

/// Re-fold every text element to `width` columns. Images keep their own height.
fn rewrap_elements(elements: &mut [ContentElement], width: usize) {
    for element in elements.iter_mut() {
        if let ContentElement::TextLine(text) | ContentElement::ImagePlaceholder(text) = element {
            text.rewrap(width);
        }
    }
}

/// Display width of a string, in terminal columns.
fn str_width(s: &str) -> usize {
    Span::raw(s).width()
}

fn char_width(ch: char) -> usize {
    let mut buf = [0u8; 4];
    str_width(ch.encode_utf8(&mut buf))
}

/// Split `s` so that the first part is at most `width` columns wide.
fn split_at_width(s: &str, width: usize) -> (&str, &str) {
    let mut used = 0usize;
    for (idx, ch) in s.char_indices() {
        let cw = char_width(ch);
        if used + cw > width {
            return s.split_at(idx);
        }
        used += cw;
    }
    (s, "")
}

/// The prefix continuation lines get, so wrapped text keeps its visual column.
///
/// A code-block line repeats its `│ ` gutter verbatim, which keeps the drawn box
/// closed; every other marker (bullets, task boxes, blockquote bars, ordered
/// list numbers) is replaced by blanks so the continuation lines up under the
/// text of the first line instead of under its marker.
fn continuation_prefix(line: &Line<'_>) -> Span<'static> {
    let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
    let indent_len = text.chars().take_while(|c| *c == ' ').count();
    let indent = " ".repeat(indent_len);
    let rest = &text[indent_len..];

    const GUTTER: &str = "";
    if rest.starts_with(GUTTER) {
        // Keep the gutter, and its colour, on every folded row.
        let style = line.spans.first().map(|s| s.style).unwrap_or_default();
        return Span::styled(format!("{indent}{GUTTER}"), style);
    }

    const MARKERS: &[&str] = &["", "", "", "", "- ", "* "];
    for marker in MARKERS {
        if rest.starts_with(marker) {
            return Span::raw(format!("{}{}", indent, " ".repeat(str_width(marker))));
        }
    }

    // Ordered lists: "12. "
    if let Some(dot) = rest.find(". ") {
        let num = &rest[..dot];
        if !num.is_empty() && num.chars().all(|c| c.is_ascii_digit()) {
            return Span::raw(format!("{}{}", indent, " ".repeat(dot + 2)));
        }
    }

    Span::raw(indent)
}

/// A run of characters sharing one style, either all blanks or none.
struct WrapToken {
    text: String,
    style: Style,
    is_space: bool,
}

fn tokenize(line: &Line<'_>) -> Vec<WrapToken> {
    let mut tokens = Vec::new();
    for span in &line.spans {
        let mut chunk = String::new();
        let mut chunk_is_space = false;
        for ch in span.content.chars() {
            let is_space = ch == ' ' || ch == '\t';
            if !chunk.is_empty() && is_space != chunk_is_space {
                tokens.push(WrapToken {
                    text: std::mem::take(&mut chunk),
                    style: span.style,
                    is_space: chunk_is_space,
                });
            }
            chunk_is_space = is_space;
            chunk.push(ch);
        }
        if !chunk.is_empty() {
            tokens.push(WrapToken {
                text: chunk,
                style: span.style,
                is_space: chunk_is_space,
            });
        }
    }
    tokens
}

/// Fold a styled line to `width` columns, preserving every span's style (#54).
///
/// Folding happens on blanks where possible; a single word wider than the line
/// is split mid-word rather than dropped. Blanks that land on a fold are
/// discarded so continuation lines start at their indent. A `width` of 0 means
/// "unknown width" and leaves the line untouched.
fn wrap_line(line: &Line<'static>, width: usize) -> Vec<Line<'static>> {
    if width == 0 || line.width() <= width {
        return vec![line.clone()];
    }

    let prefix = continuation_prefix(line);
    let prefix_width = str_width(&prefix.content);
    // A prefix eating half the line would leave no usable room for the text.
    let (prefix, prefix_width) = if prefix_width * 2 >= width {
        (Span::raw(""), 0)
    } else {
        (prefix, prefix_width)
    };

    let mut folded: Vec<Vec<Span<'static>>> = Vec::new();
    let mut current: Vec<Span<'static>> = Vec::new();
    let mut current_width = 0usize;

    for token in tokenize(line) {
        let mut remaining: &str = &token.text;
        loop {
            let limit = if folded.is_empty() {
                width
            } else {
                width - prefix_width
            };

            if token.is_space {
                // Blanks never open a continuation line (the leading indent of
                // the very first line is text, not a fold artefact), and never
                // overflow one.
                let opens_a_fold = current.is_empty() && !folded.is_empty();
                if !opens_a_fold && current_width + str_width(remaining) <= limit {
                    current_width += str_width(remaining);
                    current.push(Span::styled(remaining.to_string(), token.style));
                }
                break;
            }

            let token_width = str_width(remaining);
            if current_width + token_width <= limit {
                current.push(Span::styled(remaining.to_string(), token.style));
                current_width += token_width;
                break;
            }

            if current_width > 0 {
                // Try the word again on a fresh line.
                folded.push(std::mem::take(&mut current));
                current_width = 0;
                continue;
            }

            // The word alone is wider than the line: split it mid-word, taking
            // at least one character so this never spins.
            let (head, tail) = split_at_width(remaining, limit);
            let (head, tail) = if head.is_empty() {
                let idx = remaining
                    .char_indices()
                    .nth(1)
                    .map_or(remaining.len(), |(i, _)| i);
                remaining.split_at(idx)
            } else {
                (head, tail)
            };
            current.push(Span::styled(head.to_string(), token.style));
            folded.push(std::mem::take(&mut current));
            current_width = 0;
            remaining = tail;
            if remaining.is_empty() {
                break;
            }
        }
    }

    if !current.is_empty() || folded.is_empty() {
        folded.push(current);
    }

    folded
        .into_iter()
        .enumerate()
        .map(|(i, spans)| {
            if i == 0 || prefix_width == 0 {
                Line::from(spans)
            } else {
                let mut with_prefix = Vec::with_capacity(spans.len() + 1);
                with_prefix.push(prefix.clone());
                with_prefix.extend(spans);
                Line::from(with_prefix)
            }
        })
        .collect()
}

/// Point stdin back at the terminal when the document arrived through a pipe.
///
/// macOS only, because the defect is: with the document on stdin, crossterm
/// falls back to `/dev/tty` for the keyboard, and `/dev/tty` is a *clone*
/// device the kernel refuses to register with kqueue — `EVFILT_READ` returns
/// `EINVAL`. mio's registration fails, `UnixInternalEventSource::new` returns
/// an error crossterm swallows, and the first key read reports "Failed to
/// initialize input reader", after the document has already been drawn.
/// Opening the real device instead (`/dev/ttys004`) registers fine.
///
/// Linux is deliberately left alone: `/dev/tty` works with epoll there, and
/// this swap would replace the process's *controlling* terminal with whatever
/// terminal stdout happens to point at — not necessarily the same one.
///
/// Scope: this leaks the old descriptor 0 rather than restoring it, which is
/// fine for mdr — the piped document has already been read into a file, one
/// backend runs, and the process exits after it. It is not a routine something
/// else should call.
#[cfg(target_os = "macos")]
fn reattach_stdin_to_terminal() {
    use std::io::IsTerminal;

    if io::stdin().is_terminal() {
        return;
    }

    // `ttyname_r` rather than `ttyname`: POSIX does not require the latter to be
    // thread-safe, and it returns a pointer into a static buffer.
    let mut buffer = [0_i8; libc::PATH_MAX as usize];
    // SAFETY: the buffer is owned here and its real length is passed, so
    // `ttyname_r` cannot write past it.
    let rc = unsafe {
        libc::ttyname_r(
            libc::STDOUT_FILENO,
            buffer.as_mut_ptr().cast(),
            buffer.len(),
        )
    };
    if rc != 0 {
        crate::vlog!("stdin not reattached: no terminal on stdout (ttyname_r: {rc})");
        return;
    }

    // SAFETY: `ttyname_r` returned success, so the buffer holds a NUL-terminated
    // path; the descriptor is closed unless it becomes stdin.
    unsafe {
        let fd = libc::open(buffer.as_ptr().cast(), libc::O_RDWR);
        if fd < 0 {
            crate::vlog!("stdin not reattached: {}", std::io::Error::last_os_error());
            return;
        }
        if libc::dup2(fd, libc::STDIN_FILENO) < 0 {
            crate::vlog!("stdin not reattached: {}", std::io::Error::last_os_error());
        } else {
            crate::vlog!(
                "stdin reattached to {}",
                std::ffi::CStr::from_ptr(buffer.as_ptr().cast()).to_string_lossy()
            );
        }
        if fd != libc::STDIN_FILENO {
            libc::close(fd);
        }
    }
}

pub fn run(file_path: PathBuf) -> Result<(), Box<dyn std::error::Error>> {
    let content = std::fs::read_to_string(&file_path)?;
    let toc_entries = toc::extract_toc(&content);

    // Bail out if stdout is not a TTY. On Unix, enable_raw_mode() errors on a
    // pipe so the loop never starts; on Windows it succeeds and the event poll
    // would spin forever (which previously hung CI for 6h).
    if !io::stdout().is_terminal() {
        return Err("tui backend requires a terminal (stdout is not a TTY)".into());
    }

    // `cat doc.md | mdr --backend tui` leaves stdin on the pipe, and the keys
    // have to come from somewhere else.
    #[cfg(target_os = "macos")]
    reattach_stdin_to_terminal();

    // Setup terminal. Everything past this point runs with the terminal in raw
    // mode and on the alternate screen, so the restore has to happen on every
    // way out — including an early `?` and a panic, which a plain cleanup at the
    // end of the function misses. A failure to read an event used to leave the
    // user's shell raw and stuck on the alternate screen.
    enable_raw_mode()?;
    // Armed here, not after the `execute!` below: that call can fail, and it
    // would leave the terminal raw with nothing to put it back.
    let _restore = TerminalRestore;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    // The picker is deliberately *not* initialized here: detecting the image
    // protocol means writing a query to the terminal and waiting for its answer,
    // which costs a full two-second timeout on terminals that never reply (#58).
    // The document is drawn first, and the query only happens for documents that
    // actually have something to draw.
    let needs_picker = document_needs_picker(&content);
    let rendered = build_content_elements(&content, &file_path, &None);
    let watch = crate::core::watcher::watch_file(&file_path)?;

    let mut app = TuiApp {
        content,
        rendered,
        toc_entries,
        file_path,
        watch,
        picker: None,
        picker_queried: false,
        content_width: 0,
        scroll_offset: 0,
        toc_selected: 0,
        focus_toc: false,
        should_quit: false,
        search_mode: false,
        search_query: String::new(),
        search_matches: Vec::new(),
        current_match_idx: 0,
    };

    // Show the document immediately, then pay for the capability query — and
    // only when the document has an image or a diagram to display.
    terminal.draw(|f| ui(f, &mut app))?;
    if needs_picker {
        ensure_picker(&mut app);
        if app.picker.is_some() {
            // Only worth re-rendering when the terminal can actually draw pixels.
            rebuild_rendered(&mut app);
        }
        // The query talks to the terminal behind ratatui's back; repaint from
        // scratch so a stray reply cannot be left on screen.
        terminal.clear()?;
    }

    // Main loop
    loop {
        terminal.draw(|f| ui(f, &mut app))?;

        // Check for file changes
        if app.watch.changes().try_recv().is_ok() {
            while app.watch.changes().try_recv().is_ok() {}
            if let Ok(new_content) = std::fs::read_to_string(&app.file_path) {
                app.toc_entries = toc::extract_toc(&new_content);
                if document_needs_picker(&new_content) {
                    ensure_picker(&mut app);
                }
                app.content = new_content;
                rebuild_rendered(&mut app);
            }
        }

        // Poll events with 100ms timeout for file watching
        if event::poll(std::time::Duration::from_millis(100))? {
            let ev = event::read()?;
            // Handle mouse scroll
            if let Event::Mouse(mouse) = &ev {
                match mouse.kind {
                    MouseEventKind::ScrollDown => {
                        app.scroll_offset = app.scroll_offset.saturating_add(3);
                    }
                    MouseEventKind::ScrollUp => {
                        app.scroll_offset = app.scroll_offset.saturating_sub(3);
                    }
                    _ => {}
                }
            }
            if let Event::Key(key) = ev {
                if app.search_mode {
                    match key.code {
                        KeyCode::Esc => {
                            app.search_mode = false;
                            app.search_query.clear();
                            app.search_matches.clear();
                            app.current_match_idx = 0;
                        }
                        KeyCode::Enter => {
                            if !app.search_matches.is_empty() {
                                app.current_match_idx =
                                    (app.current_match_idx + 1) % app.search_matches.len();
                                app.scroll_offset = app.search_matches[app.current_match_idx];
                            }
                        }
                        KeyCode::Backspace => {
                            app.search_query.pop();
                            update_search_matches(&mut app);
                        }
                        KeyCode::Char(c) => {
                            app.search_query.push(c);
                            update_search_matches(&mut app);
                        }
                        _ => {}
                    }
                } else {
                    match key.code {
                        KeyCode::Char('q') | KeyCode::Esc => app.should_quit = true,
                        KeyCode::Char('t') if is_theme_toggle(key.code, key.modifiers) => {
                            // The terminal owns its background, so a theme here
                            // is the colours code blocks are highlighted in.
                            // They are baked into the spans when the document
                            // is built, so the flip has to rebuild it.
                            toggle_syntax_theme();
                            rebuild_rendered(&mut app);
                        }
                        KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                            app.should_quit = true;
                        }
                        KeyCode::Char('f') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                            app.search_mode = true;
                        }
                        KeyCode::Char('/') => {
                            app.search_mode = true;
                        }
                        KeyCode::Char('n') => {
                            if !app.search_matches.is_empty() {
                                app.current_match_idx =
                                    (app.current_match_idx + 1) % app.search_matches.len();
                                app.scroll_offset = app.search_matches[app.current_match_idx];
                            }
                        }
                        KeyCode::Char('N') => {
                            if !app.search_matches.is_empty() {
                                app.current_match_idx = if app.current_match_idx == 0 {
                                    app.search_matches.len() - 1
                                } else {
                                    app.current_match_idx - 1
                                };
                                app.scroll_offset = app.search_matches[app.current_match_idx];
                            }
                        }
                        KeyCode::Down | KeyCode::Char('j') => {
                            if app.focus_toc {
                                if app.toc_selected < app.toc_entries.len().saturating_sub(1) {
                                    app.toc_selected += 1;
                                }
                            } else {
                                app.scroll_offset = app.scroll_offset.saturating_add(1);
                            }
                        }
                        KeyCode::Up | KeyCode::Char('k') => {
                            if app.focus_toc {
                                app.toc_selected = app.toc_selected.saturating_sub(1);
                            } else {
                                app.scroll_offset = app.scroll_offset.saturating_sub(1);
                            }
                        }
                        KeyCode::PageDown | KeyCode::Char(' ') => {
                            app.scroll_offset = app.scroll_offset.saturating_add(20);
                        }
                        KeyCode::PageUp => {
                            app.scroll_offset = app.scroll_offset.saturating_sub(20);
                        }
                        KeyCode::Home | KeyCode::Char('g') => {
                            app.scroll_offset = 0;
                        }
                        KeyCode::End | KeyCode::Char('G') => {
                            let total_rows = total_content_rows(&app.rendered);
                            app.scroll_offset = total_rows.saturating_sub(1);
                        }
                        KeyCode::Tab => {
                            app.focus_toc = !app.focus_toc;
                        }
                        KeyCode::Enter if app.focus_toc => {
                            if let Some(offset) =
                                find_heading_row(&app.rendered, &app.toc_entries, app.toc_selected)
                            {
                                app.scroll_offset = offset;
                                app.focus_toc = false;
                            }
                        }
                        _ => {}
                    }
                }
            }
        }

        if app.should_quit {
            break;
        }
    }

    // Restore terminal
    // The terminal is restored by `_restore` going out of scope, here and on
    // every early return above it.
    Ok(())
}

/// Puts the terminal back the way it was found, whatever happens on the way out.
struct TerminalRestore;

impl Drop for TerminalRestore {
    fn drop(&mut self) {
        // Nothing useful can be done about a failure here: the process is on its
        // way out, and the message would land on a terminal that may still be
        // raw. Each step is attempted regardless of the previous one's outcome.
        let _ = disable_raw_mode();
        let _ = execute!(
            io::stdout(),
            LeaveAlternateScreen,
            DisableMouseCapture,
            crossterm::cursor::Show
        );
    }
}

struct TuiApp {
    content: String,
    rendered: Vec<ContentElement>,
    toc_entries: Vec<TocEntry>,
    file_path: PathBuf,
    /// Kept for its lifetime, not only its channel: dropping it stops the watch.
    watch: Watch,
    /// The terminal's image protocol, once it has been asked for. `None` means
    /// either "not asked yet" or "the terminal cannot display images"; the
    /// `picker_queried` flag tells the two apart.
    picker: Option<Picker>,
    picker_queried: bool,
    /// Width the text is currently wrapped to, in columns. 0 until the first
    /// frame tells us how wide the content panel really is.
    content_width: usize,
    scroll_offset: usize,
    toc_selected: usize,
    focus_toc: bool,
    should_quit: bool,
    search_mode: bool,
    search_query: String,
    search_matches: Vec<usize>,
    current_match_idx: usize,
}

/// Ask the terminal which image protocol it speaks, at most once per run.
///
/// `Picker::from_query_stdio()` writes an escape sequence and blocks until the
/// terminal answers — two seconds on terminals that never do. Calling it lazily
/// keeps that cost out of the startup path of text-only documents (#58).
fn ensure_picker(app: &mut TuiApp) {
    if app.picker_queried {
        return;
    }
    app.picker_queried = true;
    app.picker = Picker::from_query_stdio().ok();
}

/// Rebuild the rendered elements from the current document content.
fn rebuild_rendered(app: &mut TuiApp) {
    let content = std::mem::take(&mut app.content);
    app.rendered = build_content_elements(&content, &app.file_path, &app.picker);
    rewrap_elements(&mut app.rendered, app.content_width);
    app.content = content;
}

/// Row offsets of the lines matching `query`, in the current wrapped layout.
///
/// Offsets are counted in *rendered* rows, wrapped height included, so that
/// scrolling to a match lands on it (#54).
fn compute_search_matches(elements: &[ContentElement], query: &str) -> Vec<usize> {
    let mut matches = Vec::new();
    if query.is_empty() {
        return matches;
    }
    let query_lower = query.to_lowercase();
    let mut row_offset: usize = 0;
    for element in elements {
        if let ContentElement::TextLine(text) | ContentElement::ImagePlaceholder(text) = element
            && text.text().to_lowercase().contains(&query_lower)
        {
            matches.push(row_offset);
        }
        row_offset += element.row_height();
    }
    matches
}

fn update_search_matches(app: &mut TuiApp) {
    app.search_matches = compute_search_matches(&app.rendered, &app.search_query);
    app.current_match_idx = 0;
    // Auto-scroll to first match
    if !app.search_matches.is_empty() {
        app.scroll_offset = app.search_matches[0];
    }
}

/// Calculate the total number of terminal rows occupied by all content elements.
fn total_content_rows(elements: &[ContentElement]) -> usize {
    elements.iter().map(ContentElement::row_height).sum()
}

fn ui(f: &mut Frame, app: &mut TuiApp) {
    let chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Length(30), Constraint::Min(1)])
        .split(f.area());

    // TOC sidebar
    let toc_items: Vec<ListItem> = app
        .toc_entries
        .iter()
        .map(|entry| {
            let indent = "  ".repeat((entry.level as usize).saturating_sub(1));
            let style = match entry.level {
                1 => Style::default().fg(Color::Cyan).bold(),
                2 => Style::default().fg(Color::Blue).bold(),
                3 => Style::default().fg(Color::White),
                _ => Style::default().fg(Color::DarkGray),
            };
            ListItem::new(format!("{}{}", indent, entry.text)).style(style)
        })
        .collect();

    let toc_border_style = if app.focus_toc {
        Style::default().fg(Color::Cyan)
    } else {
        Style::default().fg(Color::DarkGray)
    };

    let toc = List::new(toc_items)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(toc_border_style)
                .title(" TOC ")
                .title_style(Style::default().bold()),
        )
        .highlight_style(Style::default().bg(Color::DarkGray).fg(Color::White))
        .highlight_symbol(">> ");

    let mut toc_state = ListState::default();
    if app.focus_toc {
        toc_state.select(Some(app.toc_selected));
    }
    f.render_stateful_widget(toc, chunks[0], &mut toc_state);

    // Main content area
    let content_area = chunks[1];
    let inner_area = Block::default()
        .borders(Borders::ALL)
        .border_style(if !app.focus_toc {
            Style::default().fg(Color::Cyan)
        } else {
            Style::default().fg(Color::DarkGray)
        })
        .title(format!(" {} ", app.file_path.display()))
        .title_style(Style::default().bold())
        .inner(content_area);

    // Fold the text to the panel width, and only when that width changes: the
    // wrapped height feeds every scroll offset below (#54).
    if inner_area.width as usize != app.content_width {
        app.content_width = inner_area.width as usize;
        rewrap_elements(&mut app.rendered, app.content_width);
        app.search_matches = compute_search_matches(&app.rendered, &app.search_query);
        if app.current_match_idx >= app.search_matches.len() {
            app.current_match_idx = 0;
        }
    }

    let content_height = inner_area.height as usize;
    let total_rows = total_content_rows(&app.rendered);
    let max_scroll = total_rows.saturating_sub(content_height);
    let scroll = app.scroll_offset.min(max_scroll);

    // Draw the border block first
    let scroll_info = format!(" {}/{} ", scroll + 1, total_rows.max(1));
    let border_block = Block::default()
        .borders(Borders::ALL)
        .border_style(if !app.focus_toc {
            Style::default().fg(Color::Cyan)
        } else {
            Style::default().fg(Color::DarkGray)
        })
        .title(format!(" {} ", app.file_path.display()))
        .title_style(Style::default().bold())
        .title_bottom(Line::from(scroll_info).right_aligned());
    f.render_widget(border_block, content_area);

    // Now render content elements within the inner area, respecting scroll offset
    render_content_elements(
        f,
        inner_area,
        &mut app.rendered,
        scroll,
        content_height,
        &app.search_matches,
        app.current_match_idx,
    );

    // Bottom bar
    let bar_text = if app.search_mode {
        let match_info = if app.search_matches.is_empty() {
            if app.search_query.is_empty() {
                String::new()
            } else {
                " (no matches)".to_string()
            }
        } else {
            format!(
                " ({}/{})",
                app.current_match_idx + 1,
                app.search_matches.len()
            )
        };
        format!(
            " /{}{}  [Enter: next | Esc: close]",
            app.search_query, match_info
        )
    } else if !app.search_matches.is_empty() {
        format!(
            " Search: '{}' ({}/{})  [n/N: next/prev | /: search]",
            app.search_query,
            app.current_match_idx + 1,
            app.search_matches.len()
        )
    } else {
        help_bar(usize::from(content_area.width.saturating_sub(2)))
    };

    // The bar is one row inside the content area's borders, so it needs both a
    // row to sit on and a column to occupy: `y + height - 1` used to underflow
    // and panic on a terminal reporting a height of zero, and `x + 1` lands
    // outside an area no wider than its own borders.
    //
    // The width is a column count, so the bar is measured in columns rather
    // than in `str::len` bytes, which overstate anything outside ASCII. That is
    // visible, not merely pedantic: an accented search query used to give the
    // bar two cells per character more than it draws, and its background was
    // painted over them.
    let available = content_area.width.saturating_sub(2);
    if content_area.height > 0 && available > 0 {
        // Clipped to the available columns while still `usize`, so the result
        // is known to fit and the conversion cannot fail or saturate.
        let wanted = Line::from(bar_text.as_str()).width();
        let width = u16::try_from(wanted.min(usize::from(available)))
            .expect("clipped to a u16 above, so it fits");
        let help_area = Rect {
            x: content_area.x + 1,
            y: content_area.bottom() - 1,
            width,
            height: 1,
        };

        let bar_style = if app.search_mode {
            Style::default()
                .fg(Color::Yellow)
                .bg(Color::Rgb(40, 40, 40))
        } else {
            Style::default().fg(Color::DarkGray)
        };
        let help_widget = Paragraph::new(bar_text).style(bar_style);
        f.render_widget(help_widget, help_area);
    }
}

/// Render content elements into the given area, handling scroll offset.
/// This function iterates through elements, skipping rows according to the scroll offset,
/// and renders visible text lines and images. Search matches are highlighted.
fn render_content_elements(
    f: &mut Frame,
    area: Rect,
    elements: &mut [ContentElement],
    scroll: usize,
    content_height: usize,
    search_matches: &[usize],
    current_match: usize,
) {
    let mut rows_skipped: usize = 0;
    let mut y_offset: u16 = 0;
    let available_height = content_height as u16;
    // Track absolute row offset for each element (independent of scroll)
    let mut absolute_row: usize = 0;

    for element in elements.iter_mut() {
        if y_offset >= available_height {
            break;
        }

        let elem_height = element.row_height();
        let current_absolute_row = absolute_row;
        absolute_row += elem_height;

        // Check if this element is before the scroll window
        if rows_skipped + elem_height <= scroll {
            rows_skipped += elem_height;
            continue;
        }

        // This element is at least partially visible
        let skip_within = scroll.saturating_sub(rows_skipped);
        rows_skipped += elem_height;

        match element {
            ContentElement::TextLine(text) | ContentElement::ImagePlaceholder(text) => {
                // A search hit is recorded at the first row of the logical line,
                // so every one of its wrapped rows is highlighted together.
                let is_match = search_matches.contains(&current_absolute_row);
                let is_current =
                    is_match && search_matches.get(current_match) == Some(&current_absolute_row);

                for line in text.lines.iter().skip(skip_within) {
                    if y_offset >= available_height {
                        break;
                    }
                    let line_area = Rect {
                        x: area.x,
                        y: area.y + y_offset,
                        width: area.width,
                        height: 1,
                    };
                    let rendered = if is_match {
                        highlight_line(line, is_current)
                    } else {
                        line.clone()
                    };
                    f.render_widget(Paragraph::new(rendered), line_area);
                    y_offset += 1;
                }
            }
            ContentElement::Image {
                protocol, height, ..
            } => {
                // Show the visible portion of the image.
                // When partially scrolled, show only the remaining rows.
                let visible_height = (*height as usize).saturating_sub(skip_within) as u16;
                if visible_height == 0 {
                    continue;
                }
                let remaining = available_height - y_offset;
                let render_height = visible_height.min(remaining);
                if render_height == 0 {
                    continue;
                }
                let img_area = Rect {
                    x: area.x,
                    y: area.y + y_offset,
                    width: area.width,
                    height: render_height,
                };
                let image_widget = StatefulImage::default().resize(Resize::Fit(None));
                f.render_stateful_widget(image_widget, img_area, protocol.as_mut());
                y_offset += render_height;
            }
        }
    }
}

/// Repaint a line with the search highlight, keeping each span's own styling.
fn highlight_line(line: &Line<'static>, is_current: bool) -> Line<'static> {
    Line::from(
        line.spans
            .iter()
            .map(|s| {
                let style = if is_current {
                    s.style.bg(Color::Yellow).fg(Color::Black)
                } else {
                    s.style.bg(Color::Rgb(80, 80, 0))
                };
                Span::styled(s.content.clone(), style)
            })
            .collect::<Vec<_>>(),
    )
}

/// Find the row offset where a heading appears in the rendered output.
fn find_heading_row(
    elements: &[ContentElement],
    toc_entries: &[TocEntry],
    toc_index: usize,
) -> Option<usize> {
    let entry = toc_entries.get(toc_index)?;
    let search_text = &entry.text;
    let mut row_offset: usize = 0;

    for element in elements {
        if let ContentElement::TextLine(text) | ContentElement::ImagePlaceholder(text) = element
            && text.text().contains(search_text)
        {
            return Some(row_offset);
        }
        row_offset += element.row_height();
    }

    None
}

/// Build content elements from markdown, loading images where possible.
fn build_content_elements(
    content: &str,
    file_path: &PathBuf,
    picker: &Option<Picker>,
) -> Vec<ContentElement> {
    let text_lines = markdown_to_lines_with_images(content);
    let canonical_file = std::fs::canonicalize(file_path).unwrap_or_else(|_| {
        std::env::current_dir().map_or_else(|_| file_path.clone(), |cwd| cwd.join(file_path))
    });
    // A piped document lives in a temp file; its images do not.
    let base_dir = crate::core::document_base_dir(&canonical_file);
    let base_dir = base_dir.as_path();

    let mut elements = Vec::new();
    for item in text_lines {
        match item {
            ParsedLine::Text(line) => {
                elements.push(ContentElement::TextLine(WrappedText::new(line)));
            }
            ParsedLine::MermaidRef { source } => {
                // Try to render mermaid diagram as an image
                match crate::core::mermaid::render_mermaid_to_svg(&source) {
                    Ok(svg) => {
                        match rasterize_svg(&svg) {
                            Ok(dyn_img) => {
                                if let Some(picker) = picker {
                                    let (img_w, img_h) = (dyn_img.width(), dyn_img.height());
                                    let aspect = f64::from(img_h) / f64::from(img_w);
                                    let target_cols = 100u16;
                                    let target_rows =
                                        (f64::from(target_cols) * aspect / 2.0).ceil() as u16;
                                    let height = target_rows.clamp(4, 40);

                                    let protocol = Box::new(picker.new_resize_protocol(dyn_img));
                                    elements.push(ContentElement::Image {
                                        protocol,
                                        _alt: "mermaid diagram".to_string(),
                                        height,
                                    });
                                } else {
                                    // No picker: fall back to code block display
                                    push_mermaid_fallback_code(&mut elements, &source);
                                }
                            }
                            Err(_) => {
                                push_mermaid_fallback_code(&mut elements, &source);
                            }
                        }
                    }
                    Err(_) => {
                        push_mermaid_fallback_code(&mut elements, &source);
                    }
                }
            }
            ParsedLine::ImageRef { alt, url } => {
                if let Some(picker) = picker {
                    match load_image(&url, base_dir) {
                        Ok(dyn_img) => {
                            // Calculate image height in rows. Use a reasonable default:
                            // Fill terminal width for readable images.
                            let (img_w, img_h) = (dyn_img.width(), dyn_img.height());
                            let aspect = f64::from(img_h) / f64::from(img_w);
                            let target_cols = 100u16;
                            let target_rows = (f64::from(target_cols) * aspect / 2.0).ceil() as u16;
                            let height = target_rows.clamp(4, 40);

                            let protocol = Box::new(picker.new_resize_protocol(dyn_img));
                            elements.push(ContentElement::Image {
                                protocol,
                                _alt: alt,
                                height,
                            });
                        }
                        Err(_) => {
                            let label = if alt.is_empty() {
                                "image".to_string()
                            } else {
                                alt
                            };
                            elements.push(ContentElement::ImagePlaceholder(WrappedText::new(
                                Line::from(Span::styled(
                                    format!("[Image: {label}]"),
                                    Style::default().fg(Color::Magenta).italic(),
                                )),
                            )));
                        }
                    }
                } else {
                    // No picker available (terminal doesn't support image protocols or detection failed)
                    let label = if alt.is_empty() {
                        "image".to_string()
                    } else {
                        alt
                    };
                    elements.push(ContentElement::ImagePlaceholder(WrappedText::new(
                        Line::from(Span::styled(
                            format!("[Image: {label}]"),
                            Style::default().fg(Color::Magenta).italic(),
                        )),
                    )));
                }
            }
        }
    }

    elements
}

/// Push a mermaid code block as fallback text when rendering fails or no picker is available.
fn push_mermaid_fallback_code(elements: &mut Vec<ContentElement>, source: &str) {
    elements.push(ContentElement::TextLine(WrappedText::new(Line::from(
        Span::styled(
            code_frame_top("mermaid"),
            Style::default().fg(Color::DarkGray),
        ),
    ))));
    for line in source.lines() {
        elements.push(ContentElement::TextLine(WrappedText::new(Line::from(
            Span::styled(format!("{line}"), Style::default().fg(Color::Green)),
        ))));
    }
    elements.push(ContentElement::TextLine(WrappedText::new(Line::from(
        Span::styled(CODE_FRAME_BOTTOM, Style::default().fg(Color::DarkGray)),
    ))));
    elements.push(ContentElement::TextLine(WrappedText::new(Line::from(""))));
}

/// What loading an image yields, however it was reached.
type LoadedImage = Result<image::DynamicImage, Box<dyn std::error::Error>>;

/// Load an image from a URL, data URI, or local file path.
/// SVG files are rasterized via resvg/usvg before returning.
fn load_image(
    url: &str,
    base_dir: &std::path::Path,
) -> Result<image::DynamicImage, Box<dyn std::error::Error>> {
    load_image_with(url, base_dir, crate::core::offline(), &load_image_from_http)
}

/// The body of [`load_image`], with the setting and the fetch passed in.
///
/// `--offline` promises that mdr makes no network access at all, and this
/// backend used to reach for a remote image anyway: `core::offline` was not
/// even compiled for it. Both are parameters so a test can prove the promise by
/// counting calls — rather than by pointing at a URL that happens to fail —
/// without touching the process-wide flag the rest of the suite reads.
fn load_image_with(
    url: &str,
    base_dir: &std::path::Path,
    offline: bool,
    fetch: &dyn Fn(&str) -> LoadedImage,
) -> LoadedImage {
    if url.starts_with("data:") {
        // data: URI - decode base64
        load_image_from_data_uri(url)
    } else if url.starts_with("http://") || url.starts_with("https://") {
        if offline {
            return Err("offline: remote images are not fetched".into());
        }
        fetch(url)
    } else {
        // Local file path (resolve relative to markdown file's directory)
        let path = if std::path::Path::new(url).is_absolute() {
            PathBuf::from(url)
        } else {
            base_dir.join(url)
        };
        // Path traversal protection: the image must stay inside the enclosing
        // project (see core::paths), so `../images/logo.png` from `docs/page.md`
        // works while `../../../etc/passwd` does not.
        if path.exists() && !crate::core::paths::is_within_image_root(&path, base_dir) {
            return Err("path traversal blocked: image path escapes the project directory".into());
        }
        crate::core::image_validation::validate_image_file(&path)
            .map_err(|e| format!("invalid image file: {e}"))?;
        // SVG files need rasterization
        if path.extension().and_then(|e| e.to_str()) == Some("svg") {
            let svg_data = std::fs::read_to_string(&path)?;
            return rasterize_svg(&svg_data);
        }
        let img = image::open(&path)?;
        Ok(img)
    }
}

/// Load an image from a data: URI by decoding the base64 payload.
/// Rejects data URIs larger than 50MB (base64-encoded) to prevent memory exhaustion.
fn load_image_from_data_uri(uri: &str) -> Result<image::DynamicImage, Box<dyn std::error::Error>> {
    const MAX_DATA_URI_LEN: usize = 50 * 1024 * 1024; // 50 MB
    if uri.len() > MAX_DATA_URI_LEN {
        return Err(format!(
            "data URI too large ({} bytes, max {})",
            uri.len(),
            MAX_DATA_URI_LEN
        )
        .into());
    }
    // Format: data:[<mediatype>][;base64],<data>
    let comma_pos = uri.find(',').ok_or("Invalid data URI: no comma found")?;
    let header = &uri[..comma_pos];
    let data_part = &uri[comma_pos + 1..];
    let decoded = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, data_part)?;
    // SVG data URIs need rasterization
    if header.contains("image/svg") {
        let svg_str = String::from_utf8(decoded)?;
        return rasterize_svg(&svg_str);
    }
    let img = image::load_from_memory(&decoded)?;
    Ok(img)
}

/// Rasterize an SVG string to a `DynamicImage` using resvg/usvg.
fn rasterize_svg(svg_data: &str) -> Result<image::DynamicImage, Box<dyn std::error::Error>> {
    // Shared, so the resolver that refuses an SVG's own file
    // references is the one every rasteriser uses.
    let options = crate::core::svg::options();
    let tree = usvg::Tree::from_str(svg_data, &options)?;
    let size = tree.size();
    let (svg_w, svg_h) = (size.width(), size.height());

    // The document being rendered is untrusted, and its declared size decided
    // how large a buffer to allocate: an SVG claiming 100000x100000 asked for
    // forty gigabytes. The three other rasterisation paths already cap a side at
    // MAX_TEXTURE_SIZE; this one did not, and the terminal is the backend most
    // likely to be pointed at a file someone else wrote.
    const MAX_TEXTURE_SIZE: u32 = 8192;
    let scale = if svg_w > MAX_TEXTURE_SIZE as f32 || svg_h > MAX_TEXTURE_SIZE as f32 {
        let scale_w = MAX_TEXTURE_SIZE as f32 / svg_w;
        let scale_h = MAX_TEXTURE_SIZE as f32 / svg_h;
        scale_w.min(scale_h).min(1.0) // never scale up, only down
    } else {
        1.0
    };

    let width = (svg_w * scale) as u32;
    let height = (svg_h * scale) as u32;

    if width == 0 || height == 0 {
        return Err("SVG has zero dimensions".into());
    }

    let mut pixmap = tiny_skia::Pixmap::new(width, height).ok_or("Failed to create pixmap")?;
    resvg::render(
        &tree,
        tiny_skia::Transform::from_scale(scale, scale),
        &mut pixmap.as_mut(),
    );

    // Convert RGBA pixmap to DynamicImage
    let img = image::RgbaImage::from_raw(width, height, pixmap.data().to_vec())
        .ok_or("Failed to create image from pixmap")?;
    Ok(image::DynamicImage::ImageRgba8(img))
}

/// Load an image from an HTTP(S) URL using ureq (30s timeout).
fn load_image_from_http(url: &str) -> Result<image::DynamicImage, Box<dyn std::error::Error>> {
    use std::sync::OnceLock;
    static AGENT: OnceLock<ureq::Agent> = OnceLock::new();
    let agent = AGENT.get_or_init(|| {
        ureq::Agent::config_builder()
            .timeout_global(Some(std::time::Duration::from_secs(30)))
            .build()
            .into()
    });
    let response = agent.get(url).call()?;
    let mut bytes = Vec::new();
    response.into_body().into_reader().read_to_end(&mut bytes)?;
    let img = image::load_from_memory(&bytes)?;
    Ok(img)
}

/// Intermediate representation for parsed markdown lines.
enum ParsedLine {
    Text(Line<'static>),
    ImageRef {
        alt: String,
        url: String,
    },
    /// A mermaid diagram source extracted from a fenced `mermaid` code block.
    MermaidRef {
        source: String,
    },
}

/// Whether this document has anything that has to be drawn as pixels: a
/// standalone image or a mermaid diagram.
///
/// This is the gate for the terminal capability query (#58). It is deliberately
/// built on the very same parser that produces the rendered elements, so the
/// answer can never disagree with what is actually displayed: an image written
/// inside a paragraph or a code block is shown as text and needs no picker.
fn document_needs_picker(content: &str) -> bool {
    markdown_to_lines_with_images(content).iter().any(|item| {
        matches!(
            item,
            ParsedLine::ImageRef { .. } | ParsedLine::MermaidRef { .. }
        )
    })
}

/// Whether a key press is the bare `t` that flips the theme.
///
/// Bare means bare: `Ctrl+T` and `Alt+T` are other people's shortcuts, and the
/// other two backends already refuse them. Shift is not tested because `T` is a
/// different `KeyCode::Char` and never reaches here.
fn is_theme_toggle(code: KeyCode, modifiers: KeyModifiers) -> bool {
    code == KeyCode::Char('t')
        && !modifiers.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER)
}

/// Shortcut hints for the bottom bar, most worth showing first.
///
/// The bar is drawn inside the content area, which the table of contents and
/// the borders leave about 32 columns narrower than the terminal — so on a
/// standard 80-column terminal there is room for four of these, not all six.
const HELP_HINTS: &[&str] = &[
    "q: quit",
    "j/k: scroll",
    "/: search",
    "t: theme",
    "Tab: focus",
    "Space/PgDn: page",
];

/// As many hints as fit in `columns`, joined.
///
/// Whole hints are dropped rather than the line being cut: the bar used to be
/// one fixed string clipped to the available width, which on an 80-column
/// terminal ended mid-item and hid everything after it — the theme toggle
/// included.
fn help_bar(columns: usize) -> String {
    let mut bar = String::new();
    for hint in HELP_HINTS {
        let separator = if bar.is_empty() { 0 } else { 3 };
        // The finished bar is padded with one space at each end.
        if str_width(&bar) + separator + str_width(hint) + 2 > columns {
            break;
        }
        if !bar.is_empty() {
            bar.push_str(" | ");
        }
        bar.push_str(hint);
    }
    if bar.is_empty() {
        bar
    } else {
        format!(" {bar} ")
    }
}

/// The bottom edge of a code block frame.
const CODE_FRAME_BOTTOM: &str = "└─────────────────────────────────────────┘";

/// The top edge, labelled and closed at exactly the width of the bottom one.
/// A named language used to leave the box open on the right.
fn code_frame_top(label: &str) -> String {
    let inner = str_width(CODE_FRAME_BOTTOM).saturating_sub(2);
    let opening = format!("{label} ");
    let fill = inner.saturating_sub(str_width(&opening));
    format!("{}{}", opening, "".repeat(fill))
}

/// Whether the terminal says it has a light background.
///
/// `COLORFGBG` is the only signal available without talking to the terminal and
/// waiting for an answer — which is exactly the two-second stall #58 removed, so
/// it is not an option here. Terminals that do not set the variable simply give
/// no answer, and the caller falls back to dark.
///
/// The value is `fg;bg` or `fg;<something>;bg`; the background is the last
/// field, as an ANSI colour index. 0-6 and 8 are the dark half of the palette,
/// 7 and 9-15 the light half.
fn terminal_background_is_light(colorfgbg: Option<&str>) -> Option<bool> {
    let value = colorfgbg?;
    let bg = value.rsplit(';').next()?.trim();
    let index: u8 = bg.parse().ok()?;
    match index {
        0..=6 | 8 => Some(false),
        7 | 9..=15 => Some(true),
        _ => None,
    }
}

/// The syntect theme to highlight code with.
///
/// An explicit setting always wins; `auto` asks the terminal and falls back to
/// dark, which is what the overwhelming majority of terminals running a pager
/// actually are.
/// Whether code blocks should be highlighted for a light background.
fn syntax_prefers_light(setting: crate::core::Theme, colorfgbg: Option<&str>) -> bool {
    match setting {
        crate::core::Theme::Light => true,
        crate::core::Theme::Dark => false,
        crate::core::Theme::Auto => terminal_background_is_light(colorfgbg).unwrap_or(false),
    }
}

const LIGHT_SYNTAX_THEME: &str = "InspiredGitHub";
const DARK_SYNTAX_THEME: &str = "base16-ocean.dark";

/// Which of the two syntax themes is in use right now.
///
/// Resolved once from `--theme` and the terminal background, then flipped by
/// `t`. It is a global because [`highlight_code`] runs deep inside the document
/// builder, which carries no application state — the same reason the assets
/// below are one.
fn syntax_is_light() -> &'static std::sync::atomic::AtomicBool {
    use std::sync::OnceLock;
    static CURRENT: OnceLock<std::sync::atomic::AtomicBool> = OnceLock::new();
    CURRENT.get_or_init(|| {
        std::sync::atomic::AtomicBool::new(syntax_prefers_light(
            crate::core::theme(),
            std::env::var("COLORFGBG").ok().as_deref(),
        ))
    })
}

/// Flip the syntax theme, and report the one now in use.
///
/// The terminal owns its own background, so this is the whole of what a theme
/// means here: the colours code blocks are highlighted in. The caller has to
/// rebuild the document, because the colours are baked into the spans when it
/// is built.
fn toggle_syntax_theme() -> bool {
    flip(syntax_is_light())
}

/// Flip a flag and return its new value.
///
/// Takes the flag rather than reaching for the global one, so a test can
/// exercise it without changing what every other test in the binary is
/// highlighting with.
fn flip(flag: &std::sync::atomic::AtomicBool) -> bool {
    use std::sync::atomic::Ordering;
    let flipped = !flag.load(Ordering::Relaxed);
    flag.store(flipped, Ordering::Relaxed);
    flipped
}

/// Syntax highlighting assets, built once. `SyntaxSet` parsing is the expensive
/// part, so it is shared across every code block of every reload.
fn syntax_assets() -> &'static SyntaxAssets {
    use std::sync::OnceLock;
    static ASSETS: OnceLock<SyntaxAssets> = OnceLock::new();
    ASSETS.get_or_init(|| {
        let syntaxes = syntect::parsing::SyntaxSet::load_defaults_newlines();
        let mut themes = syntect::highlighting::ThemeSet::load_defaults();
        // Both are kept, not just the one wanted at startup: `t` switches
        // between them, and reloading the set to do that would cost as much as
        // the parse this cache exists to avoid.
        let dark = themes.themes.remove(DARK_SYNTAX_THEME).unwrap_or_default();
        let light = themes
            .themes
            .remove(LIGHT_SYNTAX_THEME)
            .unwrap_or_else(|| dark.clone());
        SyntaxAssets {
            syntaxes,
            light,
            dark,
        }
    })
}

struct SyntaxAssets {
    syntaxes: syntect::parsing::SyntaxSet,
    light: syntect::highlighting::Theme,
    dark: syntect::highlighting::Theme,
}

impl SyntaxAssets {
    /// The theme for the colour scheme currently in use.
    fn theme(&self) -> &syntect::highlighting::Theme {
        if syntax_is_light().load(std::sync::atomic::Ordering::Relaxed) {
            &self.light
        } else {
            &self.dark
        }
    }
}

/// The background a code block paints behind itself.
///
/// A syntect theme picks its foregrounds for its own background, and the
/// terminal's is whatever the reader set. Without this the light theme is dark
/// text on a dark terminal — legible only by accident — and the dark theme has
/// the mirror problem on a light terminal. Painting the theme's own background
/// makes the block self-contained, which is also what `gui` and `web` do with
/// their `code_bg`.
fn syntax_background() -> Option<Color> {
    let bg = syntax_assets().theme().settings.background?;
    Some(Color::Rgb(bg.r, bg.g, bg.b))
}

/// The colour a code block draws text in when syntect has nothing to say about
/// it — an unlabelled fence, an unknown language, a highlighting failure.
fn syntax_foreground() -> Option<Color> {
    let fg = syntax_assets().theme().settings.foreground?;
    Some(Color::Rgb(fg.r, fg.g, fg.b))
}

/// Colour one code block, one `Vec<Span>` per source line (#59).
///
/// Falls back to a single span per line when the language is unknown or
/// highlighting fails, so an exotic fence never costs more than colour. That
/// fallback still takes the theme's own colours: a fence with no language is
/// the ordinary case, not an exotic one, and leaving it on the terminal's
/// colours would put unpainted text inside a painted block.
fn highlight_code(code: &str, lang: &str) -> Vec<Vec<Span<'static>>> {
    let plain = |code: &str| -> Vec<Vec<Span<'static>>> {
        let mut style = Style::default().fg(syntax_foreground().unwrap_or(Color::Green));
        if let Some(bg) = syntax_background() {
            style = style.bg(bg);
        }
        code.lines()
            .map(|l| vec![Span::styled(l.to_string(), style)])
            .collect()
    };

    let assets = syntax_assets();
    let (syntaxes, theme) = (&assets.syntaxes, assets.theme());
    let Some(syntax) = syntaxes
        .find_syntax_by_token(lang)
        .or_else(|| syntaxes.find_syntax_by_extension(lang))
    else {
        return plain(code);
    };

    let background = syntax_background();
    let mut highlighter = syntect::easy::HighlightLines::new(syntax, theme);
    let mut out = Vec::new();
    for line in code.lines() {
        // `load_defaults_newlines` expects the newline to be present.
        let with_newline = format!("{line}\n");
        match highlighter.highlight_line(&with_newline, syntaxes) {
            Ok(ranges) => out.push(
                ranges
                    .into_iter()
                    .map(|(style, text)| {
                        let c = style.foreground;
                        let mut span_style = Style::default().fg(Color::Rgb(c.r, c.g, c.b));
                        if let Some(bg) = background {
                            span_style = span_style.bg(bg);
                        }
                        Span::styled(text.trim_end_matches('\n').to_string(), span_style)
                    })
                    .filter(|s| !s.content.is_empty())
                    .collect(),
            ),
            Err(_) => return plain(code),
        }
    }
    out
}

/// How deep inside lists and block quotes a block sits.
#[derive(Clone, Copy, Default)]
struct BlockCtx {
    indent: usize,
    quote: usize,
    /// Inside a tight list, paragraphs must not be separated by a blank line —
    /// that is what "tight" means in `CommonMark`.
    tight: bool,
}

impl BlockCtx {
    fn indented(self, by: usize) -> Self {
        Self {
            indent: self.indent + by,
            ..self
        }
    }
    fn quoted(self) -> Self {
        Self {
            quote: self.quote + 1,
            ..self
        }
    }
    fn tight(self, tight: bool) -> Self {
        Self { tight, ..self }
    }
    /// The blanks and quote bars every line of this block starts with.
    fn prefix(self) -> Vec<Span<'static>> {
        let mut spans = Vec::new();
        if self.indent > 0 {
            spans.push(Span::raw(" ".repeat(self.indent)));
        }
        for _ in 0..self.quote {
            spans.push(Span::styled("", Style::default().fg(Color::DarkGray)));
        }
        spans
    }
}

/// Renders the comrak AST to terminal lines (#59).
///
/// The terminal output is derived from the very same parse the table of
/// contents and the other two backends use, so the three cannot drift apart on
/// what a heading, a list or a table is. That is what makes h5/h6, syntax
/// highlighting, aligned tables and footnotes fall out rather than being four
/// separate special cases.
struct MdRenderer {
    out: Vec<ParsedLine>,
    /// Footnote definitions, rendered together at the end of the document as
    /// the HTML backends do, whatever their position in the source.
    footnotes: Vec<(String, Vec<ParsedLine>)>,
}

type AstNode<'a> = comrak::arena_tree::Node<'a, std::cell::RefCell<comrak::nodes::Ast>>;

impl MdRenderer {
    fn new() -> Self {
        Self {
            out: Vec::new(),
            footnotes: Vec::new(),
        }
    }

    fn push(&mut self, ctx: BlockCtx, mut spans: Vec<Span<'static>>) {
        let mut line = ctx.prefix();
        line.append(&mut spans);
        self.out.push(ParsedLine::Text(Line::from(line)));
    }

    fn blank(&mut self) {
        // Never open on a blank line, and never repeat one.
        if matches!(self.out.last(), None | Some(ParsedLine::Text(_)))
            && self.plain_last().is_some_and(|t| t.trim().is_empty())
        {
            return;
        }
        if self.out.is_empty() {
            return;
        }
        self.out.push(ParsedLine::Text(Line::from("")));
    }

    fn plain_last(&self) -> Option<String> {
        match self.out.last() {
            Some(ParsedLine::Text(l)) => Some(l.spans.iter().map(|s| s.content.as_ref()).collect()),
            _ => None,
        }
    }

    fn children<'a>(&mut self, node: &'a AstNode<'a>, ctx: BlockCtx) {
        for child in node.children() {
            self.block(child, ctx);
        }
    }

    fn block<'a>(&mut self, node: &'a AstNode<'a>, ctx: BlockCtx) {
        use comrak::nodes::{ListType, NodeValue};

        let value = node.data.borrow().value.clone();
        match value {
            NodeValue::Document => self.children(node, ctx),

            NodeValue::FrontMatter(_) => {}

            NodeValue::Heading(h) => {
                let text: String = inline_text(node);
                let spans = inlines(node, heading_style(h.level));
                if h.level <= 2 {
                    self.blank();
                }
                self.push(ctx, spans);
                if let Some(rule) = heading_rule(h.level, &text) {
                    self.push(ctx, vec![rule]);
                }
                self.blank();
            }

            NodeValue::Paragraph => {
                // A paragraph that is nothing but an image is the one case the
                // terminal can draw as pixels.
                if let Some(image) = lone_image(node) {
                    self.out.push(image);
                    return;
                }
                self.push(ctx, inlines(node, Style::default()));
                if !ctx.tight {
                    self.blank();
                }
            }

            NodeValue::BlockQuote => {
                self.children(node, ctx.quoted());
                self.blank();
            }

            NodeValue::CodeBlock(code) => {
                let lang = code
                    .info
                    .split_whitespace()
                    .next()
                    .unwrap_or("")
                    .to_string();
                if lang == "mermaid" {
                    self.out.push(ParsedLine::MermaidRef {
                        source: code.literal.trim_end().to_string(),
                    });
                    return;
                }
                // The block paints the syntax theme's own background, so the
                // frame and every line have to carry it too — otherwise the
                // panel is a ragged strip of colour behind the text only.
                let background = syntax_background();
                let mut gutter = Style::default().fg(Color::DarkGray);
                if let Some(bg) = background {
                    gutter = gutter.bg(bg);
                }
                let width = str_width(CODE_FRAME_BOTTOM);
                let label = if lang.is_empty() { "code" } else { &lang };
                self.push(ctx, vec![Span::styled(code_frame_top(label), gutter)]);
                for mut spans in highlight_code(code.literal.trim_end_matches('\n'), &lang) {
                    let mut line = vec![Span::styled("", gutter)];
                    line.append(&mut spans);
                    // Pad to the frame width so the background forms a
                    // rectangle. A line longer than the frame is left alone:
                    // truncating it would hide code.
                    let drawn: usize = line.iter().map(|s| str_width(&s.content)).sum();
                    if let Some(missing) = width.checked_sub(drawn)
                        && missing > 0
                    {
                        line.push(Span::styled(" ".repeat(missing), gutter));
                    }
                    self.push(ctx, line);
                }
                self.push(ctx, vec![Span::styled(CODE_FRAME_BOTTOM, gutter)]);
                self.blank();
            }

            NodeValue::List(list) => {
                self.children(node, ctx.tight(list.tight));
                // `ctx` here is still the *enclosing* context: a list nested
                // inside a tight one must not add breathing room of its own.
                if !ctx.tight {
                    self.blank();
                }
            }

            NodeValue::Item(list) => {
                let marker = match list.list_type {
                    ListType::Bullet => "".to_string(),
                    ListType::Ordered => format!("{}. ", list.start),
                };
                self.list_item(node, ctx, marker);
            }

            NodeValue::TaskItem(task) => {
                let marker = if task.symbol.is_some() {
                    ""
                } else {
                    ""
                };
                self.list_item(node, ctx, marker.to_string());
            }

            NodeValue::ThematicBreak => {
                self.push(
                    ctx,
                    vec![Span::styled(
                        "".repeat(60),
                        Style::default().fg(Color::DarkGray),
                    )],
                );
                self.blank();
            }

            NodeValue::Table(table) => self.table(node, ctx, &table.alignments),

            NodeValue::FootnoteDefinition(def) => {
                let mut sub = Self::new();
                sub.children(node, BlockCtx::default());
                self.footnotes.push((def.name, sub.out));
            }

            NodeValue::HtmlBlock(html) => {
                // Raw HTML has no terminal rendering; show it as dim text rather
                // than dropping content the author wrote.
                for line in html.literal.lines() {
                    self.push(
                        ctx,
                        vec![Span::styled(
                            line.to_string(),
                            Style::default().fg(Color::DarkGray),
                        )],
                    );
                }
                self.blank();
            }

            // Anything else that can hold blocks is walked through.
            _ => self.children(node, ctx),
        }
    }

    fn list_item<'a>(&mut self, node: &'a AstNode<'a>, ctx: BlockCtx, marker: String) {
        let before = self.out.len();
        self.children(node, ctx.indented(marker.chars().count()));
        // The marker replaces the indent of the item's first line, so a wrapped
        // continuation lines up under the text (see `continuation_prefix`).
        if let Some(ParsedLine::Text(line)) = self.out.get_mut(before) {
            let indent = ctx.indent;
            let mut spans = std::mem::take(&mut line.spans);
            if !spans.is_empty() && spans[0].content.chars().all(|c| c == ' ') {
                spans.remove(0);
            }
            let mut prefixed = Vec::new();
            if indent > 0 {
                prefixed.push(Span::raw(" ".repeat(indent)));
            }
            prefixed.push(Span::styled(marker, Style::default().fg(Color::Cyan)));
            prefixed.append(&mut spans);
            *line = Line::from(prefixed);
        }
    }

    fn table<'a>(
        &mut self,
        node: &'a AstNode<'a>,
        ctx: BlockCtx,
        alignments: &[comrak::nodes::TableAlignment],
    ) {
        use comrak::nodes::NodeValue;

        // First pass: render every cell, and measure the columns (#59).
        let mut rows: Vec<(bool, Vec<Vec<Span<'static>>>)> = Vec::new();
        for row in node.children() {
            let NodeValue::TableRow(is_header) = row.data.borrow().value else {
                continue;
            };
            let cells: Vec<Vec<Span<'static>>> = row
                .children()
                .map(|cell| {
                    let style = if is_header {
                        Style::default().bold()
                    } else {
                        Style::default()
                    };
                    inlines(cell, style)
                })
                .collect();
            rows.push((is_header, cells));
        }
        if rows.is_empty() {
            return;
        }

        let columns = rows.iter().map(|(_, c)| c.len()).max().unwrap_or(0);
        let mut widths = vec![0usize; columns];
        for (_, cells) in &rows {
            for (i, cell) in cells.iter().enumerate() {
                let w: usize = cell.iter().map(ratatui::prelude::Span::width).sum();
                widths[i] = widths[i].max(w);
            }
        }

        let sep = Style::default().fg(Color::DarkGray);
        for (index, (is_header, cells)) in rows.iter().enumerate() {
            let mut line: Vec<Span<'static>> = Vec::new();
            for (col, width) in widths.iter().enumerate() {
                if col > 0 {
                    line.push(Span::styled("", sep));
                }
                let empty = Vec::new();
                let cell = cells.get(col).unwrap_or(&empty);
                let used: usize = cell.iter().map(ratatui::prelude::Span::width).sum();
                let pad = width.saturating_sub(used);
                let align = alignments
                    .get(col)
                    .copied()
                    .unwrap_or(comrak::nodes::TableAlignment::None);
                let (left, right) = match align {
                    comrak::nodes::TableAlignment::Right => (pad, 0),
                    comrak::nodes::TableAlignment::Center => (pad / 2, pad - pad / 2),
                    _ => (0, pad),
                };
                if left > 0 {
                    line.push(Span::raw(" ".repeat(left)));
                }
                line.extend(cell.iter().cloned());
                if right > 0 {
                    line.push(Span::raw(" ".repeat(right)));
                }
            }
            self.push(ctx, line);

            if *is_header || (index == 0 && rows.len() > 1) {
                let rule: Vec<Span<'static>> = (0..columns)
                    .map(|col| {
                        let mut s = String::new();
                        if col > 0 {
                            s.push_str("─┼─");
                        }
                        s.push_str(&"".repeat(widths[col]));
                        Span::styled(s, sep)
                    })
                    .collect();
                self.push(ctx, rule);
            }
        }
        self.blank();
    }

    fn finish(mut self) -> Vec<ParsedLine> {
        if !self.footnotes.is_empty() {
            let notes = std::mem::take(&mut self.footnotes);
            self.blank();
            self.push(
                BlockCtx::default(),
                vec![Span::styled(
                    "".repeat(20),
                    Style::default().fg(Color::DarkGray),
                )],
            );
            for (name, body) in notes {
                let mut body = body.into_iter();
                if let Some(ParsedLine::Text(first)) = body.next() {
                    let mut spans = vec![Span::styled(
                        format!("[{name}] "),
                        Style::default().fg(Color::Yellow).bold(),
                    )];
                    spans.extend(first.spans);
                    self.out.push(ParsedLine::Text(Line::from(spans)));
                }
                self.out.extend(body);
            }
        }
        // Never end on padding.
        while matches!(self.plain_last(), Some(t) if t.trim().is_empty()) {
            self.out.pop();
        }
        self.out
    }
}

fn heading_style(level: u8) -> Style {
    let base = Style::default().bold();
    match level {
        1 => base.fg(Color::Cyan).underlined(),
        2 => base.fg(Color::Blue),
        3 => base.fg(Color::Yellow),
        4 => base.fg(Color::Magenta),
        5 => base.fg(Color::Green),
        _ => base.fg(Color::Gray),
    }
}

/// The rule drawn under a heading, for the two levels that get one.
fn heading_rule(level: u8, text: &str) -> Option<Span<'static>> {
    let width = str_width(text);
    match level {
        1 => Some(Span::styled(
            "".repeat(width.min(60)),
            Style::default().fg(Color::Cyan),
        )),
        2 => Some(Span::styled(
            "".repeat(width.min(50)),
            Style::default().fg(Color::Blue),
        )),
        _ => None,
    }
}

/// The image of a paragraph that holds nothing else — the only shape the
/// terminal can draw as pixels. Anything else stays text.
fn lone_image<'a>(paragraph: &'a AstNode<'a>) -> Option<ParsedLine> {
    use comrak::nodes::NodeValue;
    let mut image = None;
    for child in paragraph.children() {
        match &child.data.borrow().value {
            NodeValue::Image(link) => {
                if image.is_some() {
                    return None;
                }
                image = Some((inline_text(child), link.url.clone()));
            }
            NodeValue::Text(t) if t.trim().is_empty() => {}
            NodeValue::SoftBreak => {}
            _ => return None,
        }
    }
    image.map(|(alt, url)| ParsedLine::ImageRef { alt, url })
}

/// The plain text of a node's inline content.
fn inline_text<'a>(node: &'a AstNode<'a>) -> String {
    use comrak::nodes::NodeValue;
    let mut out = String::new();
    for child in node.descendants() {
        match &child.data.borrow().value {
            NodeValue::Text(t) => out.push_str(t),
            NodeValue::Code(c) => out.push_str(&c.literal),
            NodeValue::SoftBreak | NodeValue::LineBreak => out.push(' '),
            _ => {}
        }
    }
    out
}

/// Render the inline children of `node` as styled spans.
fn inlines<'a>(node: &'a AstNode<'a>, base: Style) -> Vec<Span<'static>> {
    let mut spans = Vec::new();
    for child in node.children() {
        inline_into(child, base, &mut spans);
    }
    if spans.is_empty() {
        spans.push(Span::styled(String::new(), base));
    }
    spans
}

fn inline_into<'a>(node: &'a AstNode<'a>, style: Style, out: &mut Vec<Span<'static>>) {
    use comrak::nodes::NodeValue;
    let value = node.data.borrow().value.clone();
    match value {
        NodeValue::Text(text) => out.push(Span::styled(text.to_string(), style)),
        NodeValue::Code(code) => out.push(Span::styled(
            code.literal,
            style.fg(Color::Green).bg(Color::Rgb(40, 40, 40)),
        )),
        NodeValue::Emph => descend(node, style.italic(), out),
        NodeValue::Strong => descend(node, style.bold(), out),
        NodeValue::Strikethrough => descend(node, style.crossed_out(), out),
        NodeValue::Underline => descend(node, style.underlined(), out),
        NodeValue::SoftBreak | NodeValue::LineBreak => out.push(Span::styled(" ", style)),
        NodeValue::Link(_) => descend(node, style.fg(Color::Blue).underlined(), out),
        NodeValue::Image(link) => {
            // An image sharing a paragraph with text cannot be drawn as pixels,
            // so it is named instead of dropped.
            let alt = inline_text(node);
            let label = if alt.is_empty() {
                link.url.clone()
            } else {
                alt
            };
            out.push(Span::styled(
                format!("[{label}]"),
                style.fg(Color::Magenta).italic(),
            ));
        }
        NodeValue::FootnoteReference(fr) => out.push(Span::styled(
            format!("[{}]", fr.name),
            style.fg(Color::Yellow),
        )),
        NodeValue::HtmlInline(html) => {
            out.push(Span::styled(html, style.fg(Color::DarkGray)));
        }
        NodeValue::Escaped => descend(node, style, out),
        _ => descend(node, style, out),
    }
}

fn descend<'a>(node: &'a AstNode<'a>, style: Style, out: &mut Vec<Span<'static>>) {
    for child in node.children() {
        inline_into(child, style, out);
    }
}

/// Parse `content` and render it to terminal lines.
///
/// Uses exactly the comrak options `core::toc` and `core::markdown` use, so the
/// terminal, the table of contents and the two graphical backends agree on the
/// structure of the document (#59).
fn markdown_to_lines_with_images(content: &str) -> Vec<ParsedLine> {
    use comrak::{Arena, Options, parse_document};

    let arena = Arena::new();
    let mut options = Options::default();
    options.extension.strikethrough = true;
    options.extension.table = true;
    options.extension.autolink = true;
    options.extension.tasklist = true;
    options.extension.footnotes = true;
    options.extension.front_matter_delimiter = Some("---".to_string());

    let root = parse_document(&arena, content, &options);
    let mut renderer = MdRenderer::new();
    renderer.block(root, BlockCtx::default());
    renderer.finish()
}

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

    /// Build an app with just enough state to draw a frame.
    fn app_for_drawing(content: &str) -> TuiApp {
        let (_tx, watch) = Watch::detached();
        TuiApp {
            content: content.to_string(),
            rendered: build_content_elements(content, &PathBuf::from("t.md"), &None),
            toc_entries: crate::core::toc::extract_toc(content),
            file_path: PathBuf::from("t.md"),
            watch,
            picker: None,
            picker_queried: true,
            content_width: 0,
            scroll_offset: 0,
            toc_selected: 0,
            focus_toc: false,
            should_quit: false,
            search_mode: false,
            search_query: String::new(),
            search_matches: Vec::new(),
            current_match_idx: 0,
        }
    }

    /// How many cells on the bottom row carry the search bar's background.
    fn search_bar_width(query: &str) -> usize {
        let mut app = app_for_drawing("# Titre\n\nDu texte.\n");
        app.search_mode = true;
        app.search_query = query.to_string();

        let backend = ratatui::backend::TestBackend::new(80, 10);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal.draw(|f| ui(f, &mut app)).unwrap();

        let buffer = terminal.backend().buffer();
        let bottom = buffer.area.height - 1;
        (0..buffer.area.width)
            .filter(|x| buffer[(*x, bottom)].style().bg == Some(Color::Rgb(40, 40, 40)))
            .count()
    }

    #[test]
    fn an_oversized_svg_is_scaled_down_before_it_is_rasterised() {
        // The declared size used to decide the buffer size outright, so a
        // document could ask for an allocation of any size it liked.
        let huge = r#"<svg xmlns="http://www.w3.org/2000/svg" width="40000" height="20000"><rect width="10" height="10"/></svg>"#;
        let img = rasterize_svg(huge).expect("an oversized SVG must still render");
        assert!(
            img.width() <= 8192 && img.height() <= 8192,
            "expected a capped surface, got {}x{}",
            img.width(),
            img.height()
        );
        assert!(
            img.width() > 0 && img.height() > 0,
            "the aspect ratio must survive the scaling"
        );

        // A small one is untouched: the cap only ever scales down.
        let small = r#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20"><rect width="10" height="10"/></svg>"#;
        let img = rasterize_svg(small).expect("a small SVG must render");
        assert_eq!((img.width(), img.height()), (40, 20));
    }

    #[test]
    fn a_document_taller_than_u16_keeps_its_real_height() {
        // A wrapped paragraph is as tall as its line count, which nothing bounds
        // to the terminal. `row_height` used to narrow that to `u16`, so a very
        // long document wrapped around past 65535 rows and every offset derived
        // from it — total height, search matches, scrolling — went wrong.
        let tall = u16::MAX as usize + 10;
        let mut text = WrappedText::new(Line::from("x"));
        text.lines = vec![Line::from("x"); tall];
        let elements = vec![ContentElement::TextLine(text)];

        assert_eq!(elements[0].row_height(), tall);
        assert_eq!(
            total_content_rows(&elements),
            tall,
            "the document's height must survive being taller than a u16"
        );
    }

    #[test]
    fn the_bottom_bar_is_measured_in_columns_not_bytes() {
        // Two queries of the same length on screen, one outside ASCII. The bar
        // used to be sized from `str::len`, so the accented one claimed two
        // extra cells per character and painted its background over them.
        let ascii = search_bar_width("aa");
        let accented = search_bar_width("éé");
        assert!(ascii > 0, "the search bar should be drawn at all");
        assert_eq!(
            ascii, accented,
            "two queries that are the same width on screen must fill the same cells"
        );
    }

    #[test]
    fn drawing_into_a_terminal_with_no_rows_does_not_panic() {
        // A pty that reports 0x0 — `script -q /dev/null mdr --backend tui f.md`
        // on macOS is one — used to underflow the bottom bar's row and abort.
        let mut app = app_for_drawing("# Title\n\nText.\n");
        for (w, h) in [(0, 0), (1, 0), (0, 1), (1, 1), (2, 1), (2, 2), (3, 1)] {
            let backend = ratatui::backend::TestBackend::new(w, h);
            let mut terminal = Terminal::new(backend).unwrap();
            terminal.draw(|f| ui(f, &mut app)).unwrap();
        }
    }

    use std::io::Write;

    #[test]
    fn load_image_svg_local_file() {
        // Create a minimal SVG file in a temp directory
        let dir = std::env::temp_dir().join("mdr_test_svg");
        std::fs::create_dir_all(&dir).unwrap();
        let svg_path = dir.join("test.svg");
        let mut f = std::fs::File::create(&svg_path).unwrap();
        write!(f, r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><rect width="100" height="100" fill="red"/></svg>"#).unwrap();

        let result = load_image("test.svg", &dir);
        // This should succeed — SVG files must be rasterized before display
        assert!(
            result.is_ok(),
            "load_image should handle SVG files but got: {:?}",
            result.err()
        );
        let img = result.unwrap();
        assert!(img.width() > 0 && img.height() > 0);

        // Cleanup
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn build_content_elements_with_local_svg() {
        // Create a temp dir with an SVG and a markdown file referencing it
        let dir = std::env::temp_dir().join("mdr_test_svg_content");
        std::fs::create_dir_all(&dir).unwrap();

        let svg_path = dir.join("logo.svg");
        let mut f = std::fs::File::create(&svg_path).unwrap();
        write!(f, r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><rect width="100" height="100" fill="red"/></svg>"#).unwrap();

        let md = "# Hello\n\n![my logo](logo.svg)\n\nSome text after.\n";
        let md_path = dir.join("test.md");
        std::fs::write(&md_path, md).unwrap();

        // Build content elements (without a picker, images become placeholders OR succeed via rasterize)
        let elements = build_content_elements(md, &md_path, &None);

        // Should have parsed lines including the image reference
        // Without a picker, SVG falls back to placeholder — but the markdown parser should find it
        let has_image_ref = elements
            .iter()
            .any(|e| matches!(e, ContentElement::ImagePlaceholder(_)));
        assert!(
            has_image_ref,
            "Should find an image placeholder for the SVG reference"
        );

        // Now test load_image directly to confirm SVG rasterization works
        let img = load_image("logo.svg", &dir);
        assert!(
            img.is_ok(),
            "load_image should rasterize SVG, got: {:?}",
            img.err()
        );
        let img = img.unwrap();
        assert_eq!(img.width(), 100);
        assert_eq!(img.height(), 100);

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn load_image_svg_data_uri() {
        let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50"><circle cx="25" cy="25" r="20" fill="blue"/></svg>"#;
        let b64 =
            base64::Engine::encode(&base64::engine::general_purpose::STANDARD, svg.as_bytes());
        let data_uri = format!("data:image/svg+xml;base64,{b64}");

        let result = load_image(&data_uri, std::path::Path::new("."));
        assert!(
            result.is_ok(),
            "load_image should handle SVG data URIs but got: {:?}",
            result.err()
        );
    }

    #[test]
    fn mermaid_block_produces_mermaid_ref() {
        let md = "# Title\n\n```mermaid\ngraph LR\n  A-->B\n```\n\nSome text after.\n";
        let items = markdown_to_lines_with_images(md);

        let has_mermaid_ref = items
            .iter()
            .any(|item| matches!(item, ParsedLine::MermaidRef { .. }));
        assert!(
            has_mermaid_ref,
            "Mermaid code block should produce a MermaidRef variant"
        );

        // Verify the source is captured correctly
        let mermaid_source = items
            .iter()
            .find_map(|item| {
                if let ParsedLine::MermaidRef { source } = item {
                    Some(source.clone())
                } else {
                    None
                }
            })
            .expect("Should have a MermaidRef");
        assert!(
            mermaid_source.contains("graph LR"),
            "MermaidRef should contain the mermaid source, got: {mermaid_source}"
        );
        assert!(
            mermaid_source.contains("A-->B"),
            "MermaidRef should contain the diagram content"
        );
    }

    #[test]
    fn mermaid_block_not_rendered_as_code_text() {
        let md = "```mermaid\ngraph LR\n  A-->B\n```\n";
        let items = markdown_to_lines_with_images(md);

        // Should NOT have green code lines for mermaid content
        let has_green_code = items.iter().any(|item| {
            if let ParsedLine::Text(line) = item {
                let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
                text.contains("│ graph LR") || text.contains("│   A-->B")
            } else {
                false
            }
        });
        assert!(
            !has_green_code,
            "Mermaid content should NOT appear as regular code text"
        );
    }

    #[test]
    fn non_mermaid_code_block_unchanged() {
        let md = "```rust\nfn main() {}\n```\n";
        let items = markdown_to_lines_with_images(md);

        let has_mermaid_ref = items
            .iter()
            .any(|item| matches!(item, ParsedLine::MermaidRef { .. }));
        assert!(
            !has_mermaid_ref,
            "Non-mermaid code blocks should NOT produce MermaidRef"
        );

        // Should have regular code text
        let has_code_text = items.iter().any(|item| {
            if let ParsedLine::Text(line) = item {
                let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
                text.contains("│ fn main()")
            } else {
                false
            }
        });
        assert!(
            has_code_text,
            "Non-mermaid code should appear as regular code text"
        );
    }

    // --- #54: long lines must be wrapped, not cut off -------------------------

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

    #[test]
    fn a_line_shorter_than_the_width_is_left_alone() {
        let line = Line::from("hello world");
        let out = wrap_line(&line, 40);
        assert_eq!(out.len(), 1);
        assert_eq!(plain_text(&out[0]), "hello world");
    }

    #[test]
    fn a_long_line_is_folded_at_word_boundaries() {
        let line = Line::from("the quick brown fox jumps over the lazy dog");
        let out = wrap_line(&line, 20);
        assert!(out.len() > 1, "a 43-column line must not fit in 20 columns");
        for l in &out {
            assert!(l.width() <= 20, "line too wide: {:?}", plain_text(l));
        }
        let joined = out
            .iter()
            .map(|l| plain_text(l).trim_end().to_string())
            .collect::<Vec<_>>()
            .join(" ");
        assert_eq!(joined, "the quick brown fox jumps over the lazy dog");
    }

    #[test]
    fn a_word_longer_than_the_width_is_hard_split() {
        let line = Line::from("supercalifragilisticexpialidocious");
        let out = wrap_line(&line, 10);
        for l in &out {
            assert!(l.width() <= 10, "line too wide: {:?}", plain_text(l));
        }
        let joined: String = out.iter().map(|l| plain_text(l)).collect();
        assert_eq!(joined, "supercalifragilisticexpialidocious");
    }

    #[test]
    fn wrapping_keeps_the_style_of_every_span() {
        let line = Line::from(vec![
            Span::styled("aaaa bbbb ", Style::default().fg(Color::Red)),
            Span::styled("cccc dddd", Style::default().fg(Color::Blue)),
        ]);
        let out = wrap_line(&line, 12);
        assert!(out.len() > 1);

        let by_color = |color: Color| -> String {
            out.iter()
                .flat_map(|l| l.spans.iter())
                .filter(|s| s.style.fg == Some(color))
                .map(|s| s.content.as_ref())
                .collect::<String>()
                .replace(' ', "")
        };
        assert_eq!(by_color(Color::Red), "aaaabbbb");
        assert_eq!(by_color(Color::Blue), "ccccdddd");
    }

    #[test]
    fn an_empty_line_stays_a_single_empty_line() {
        let out = wrap_line(&Line::from(""), 10);
        assert_eq!(out.len(), 1);
        assert_eq!(plain_text(&out[0]), "");
    }

    #[test]
    fn a_tiny_width_still_yields_the_whole_text() {
        let line = Line::from("alpha beta gamma");
        for width in 0..6 {
            let out = wrap_line(&line, width);
            assert!(!out.is_empty(), "width {width} produced no line at all");
            let joined: String = out.iter().map(|l| plain_text(l)).collect();
            assert!(
                joined.replace(' ', "").contains("alphabetagamma"),
                "width {width} lost text: {joined:?}"
            );
        }
    }

    #[test]
    fn a_wrapped_list_item_keeps_its_bullet_indent() {
        let line = Line::from(vec![
            Span::raw("  "),
            Span::styled("\u{2022} ", Style::default().fg(Color::Cyan)),
            Span::raw("one two three four five six seven eight"),
        ]);
        let out = wrap_line(&line, 20);
        assert!(out.len() > 1);
        let second = plain_text(&out[1]);
        assert!(
            second.starts_with("    "),
            "continuation must line up under the item text, got {second:?}"
        );
        assert!(
            !second.contains('\u{2022}'),
            "the bullet must not be repeated: {second:?}"
        );
    }

    #[test]
    fn a_wrapped_code_line_keeps_its_gutter() {
        let line = Line::from(Span::styled(
            "\u{2502} let x = some_very_long_expression_here();",
            Style::default().fg(Color::Green),
        ));
        let out = wrap_line(&line, 20);
        assert!(out.len() > 1);
        assert!(
            plain_text(&out[1]).starts_with("\u{2502} "),
            "the code gutter must be repeated, got {:?}",
            plain_text(&out[1])
        );
    }

    #[test]
    fn wrapped_lines_count_towards_the_scroll_height() {
        let md = "a bb ccc dddd eeeee ffffff ggggggg hhhhhhhh iiiiiiiii jjjjjjjjjj\n";
        let path = std::path::PathBuf::from("/tmp/mdr_wrap_height.md");
        let mut elements = build_content_elements(md, &path, &None);
        let unwrapped = total_content_rows(&elements);
        rewrap_elements(&mut elements, 20);
        let wrapped = total_content_rows(&elements);
        assert!(
            wrapped > unwrapped,
            "wrapping must be reflected in the scroll height ({unwrapped} -> {wrapped})"
        );
    }

    #[test]
    fn search_offsets_follow_the_wrapped_layout() {
        let md = "aaaa bbbb cccc dddd eeee ffff gggg hhhh\n\nneedle\n";
        let path = std::path::PathBuf::from("/tmp/mdr_wrap_search.md");
        let mut elements = build_content_elements(md, &path, &None);
        rewrap_elements(&mut elements, 12);

        let matches = compute_search_matches(&elements, "needle");
        assert_eq!(matches.len(), 1, "exactly one line holds the needle");

        // The offset must be the sum of the *wrapped* heights of everything
        // above it, otherwise jumping to a match scrolls to the wrong place.
        let mut expected = 0usize;
        for element in &elements {
            if let ContentElement::TextLine(text) = element
                && text.text().contains("needle")
            {
                break;
            }
            expected += element.row_height();
        }
        assert_eq!(matches[0], expected);
        assert!(
            expected >= 4,
            "the wrapped paragraph should push the match down, got {expected}"
        );
    }

    // --- #58: the terminal capability query must not delay the first frame ----

    #[test]
    fn a_document_without_images_needs_no_picker() {
        let md =
            "# Title\n\nJust text with `code` and a [link](https://example.com).\n\n- a\n- b\n";
        assert!(!document_needs_picker(md));
    }

    #[test]
    fn a_document_with_a_local_image_needs_a_picker() {
        assert!(document_needs_picker("# T\n\n![logo](images/logo.png)\n"));
    }

    #[test]
    fn a_document_with_a_remote_image_needs_a_picker() {
        assert!(document_needs_picker(
            "![logo](https://example.com/logo.png)\n"
        ));
    }

    #[test]
    fn a_document_with_a_mermaid_diagram_needs_a_picker() {
        assert!(document_needs_picker(
            "```mermaid\ngraph LR\n  A-->B\n```\n"
        ));
    }

    #[test]
    fn an_image_inside_a_paragraph_needs_no_picker() {
        // Inline images are rendered as `[Image: alt]` text, never as pixels.
        assert!(!document_needs_picker("see ![logo](logo.png) in context\n"));
    }

    #[test]
    fn an_image_written_inside_a_code_block_needs_no_picker() {
        assert!(!document_needs_picker("```md\n![logo](logo.png)\n```\n"));
    }

    // --- #61: images living outside the document's own directory -------------

    /// Write a tiny valid SVG, the cheapest file `validate_image_file` accepts.
    fn write_svg(path: &std::path::Path) {
        std::fs::write(
            path,
            r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="10" height="10" fill="red"/></svg>"#,
        )
        .unwrap();
    }

    #[test]
    fn an_image_in_a_sibling_directory_of_the_project_is_loaded() {
        let tmp = tempfile::tempdir().unwrap();
        let proj = tmp.path().join("proj");
        std::fs::create_dir_all(proj.join(".git")).unwrap();
        std::fs::create_dir_all(proj.join("docs")).unwrap();
        std::fs::create_dir_all(proj.join("images")).unwrap();
        write_svg(&proj.join("images/schema.svg"));

        let img = load_image("../images/schema.svg", &proj.join("docs"));
        assert!(
            img.is_ok(),
            "an image from a parent directory inside the project must load, got: {:?}",
            img.err()
        );
    }

    #[test]
    fn an_image_outside_the_project_is_still_refused() {
        let tmp = tempfile::tempdir().unwrap();
        let proj = tmp.path().join("proj");
        std::fs::create_dir_all(proj.join(".git")).unwrap();
        std::fs::create_dir_all(proj.join("docs")).unwrap();
        write_svg(&tmp.path().join("secret.svg"));

        let img = load_image("../../secret.svg", &proj.join("docs"));
        assert!(
            img.is_err(),
            "an image outside the enclosing project must stay refused"
        );
    }

    #[test]
    fn mermaid_build_content_elements_fallback_without_picker() {
        // Without a picker, mermaid should fall back to code block display
        let md = "```mermaid\ngraph LR\n  A-->B\n```\n";
        let md_path = std::path::PathBuf::from("/tmp/test_mermaid.md");
        let elements = build_content_elements(md, &md_path, &None);

        // Without picker, mermaid rendering should either produce TextLines (fallback)
        // or ImagePlaceholder - but NOT be empty
        assert!(
            !elements.is_empty(),
            "Should produce content elements for mermaid block"
        );

        // Check that we have some text lines (the fallback code display)
        let has_text = elements
            .iter()
            .any(|e| matches!(e, ContentElement::TextLine(_)));
        assert!(has_text, "Mermaid fallback should produce text lines");
    }
}

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

    /// The plain text of every rendered line, in order.
    fn rendered(md: &str) -> Vec<String> {
        markdown_to_lines_with_images(md)
            .into_iter()
            .filter_map(|item| match item {
                ParsedLine::Text(line) => {
                    Some(line.spans.iter().map(|s| s.content.as_ref()).collect())
                }
                _ => None,
            })
            .collect()
    }

    /// Every distinct foreground colour used across the rendered lines.
    fn colours(md: &str) -> std::collections::BTreeSet<String> {
        markdown_to_lines_with_images(md)
            .into_iter()
            .filter_map(|item| match item {
                ParsedLine::Text(line) => Some(line),
                _ => None,
            })
            .flat_map(|line| {
                line.spans
                    .iter()
                    .map(|s| format!("{:?}", s.style.fg))
                    .collect::<Vec<_>>()
            })
            .collect()
    }

    // --- code frame and syntax theme (0.5.1) ---

    /// The frame around a code block used to be left open on the right as soon
    /// as the fence named a language: `┌─ rust ─────────` with no `┐`.
    #[test]
    fn the_code_frame_is_closed_and_square_whatever_the_label() {
        for label in [
            "code",
            "rust",
            "mermaid",
            "",
            "a-very-long-language-name-indeed",
        ] {
            let top = code_frame_top(label);
            assert!(top.starts_with(''), "{top:?}");
            assert!(
                top.ends_with(''),
                "top edge left open for {label:?}: {top:?}"
            );
            assert_eq!(
                str_width(&top),
                str_width(CODE_FRAME_BOTTOM),
                "top and bottom edges must line up for {label:?}: {top:?}"
            );
        }
    }

    #[test]
    fn a_named_language_still_appears_in_the_frame() {
        assert!(code_frame_top("rust").contains("rust"));
    }

    /// `COLORFGBG` is `fg;bg`, sometimes with a middle field. The background is
    /// the last one, as an ANSI palette index.
    #[test]
    fn the_terminal_background_is_read_from_colorfgbg() {
        assert_eq!(terminal_background_is_light(Some("15;0")), Some(false));
        assert_eq!(terminal_background_is_light(Some("0;15")), Some(true));
        assert_eq!(
            terminal_background_is_light(Some("15;default;0")),
            Some(false)
        );
        assert_eq!(
            terminal_background_is_light(Some("0;default;7")),
            Some(true)
        );
        // Nothing usable: no answer, so the caller keeps its default.
        assert_eq!(terminal_background_is_light(None), None);
        assert_eq!(terminal_background_is_light(Some("")), None);
        assert_eq!(terminal_background_is_light(Some("15;default")), None);
        assert_eq!(terminal_background_is_light(Some("0;99")), None);
    }

    #[test]
    fn an_explicit_theme_always_wins_over_the_terminal() {
        use crate::core::Theme;
        // A light terminal, overridden to dark, and the other way round.
        assert!(
            !syntax_prefers_light(Theme::Dark, Some("0;15")),
            "an explicit dark theme must not follow a light terminal"
        );
        assert!(
            syntax_prefers_light(Theme::Light, Some("15;0")),
            "an explicit light theme must not follow a dark terminal"
        );
    }

    #[test]
    fn auto_follows_the_terminal_and_falls_back_to_dark() {
        use crate::core::Theme;
        assert!(syntax_prefers_light(Theme::Auto, Some("0;15")));
        assert!(!syntax_prefers_light(Theme::Auto, Some("15;0")));
        // A terminal that says nothing must not cost a query, and dark is the
        // safe assumption for a pager.
        assert!(!syntax_prefers_light(Theme::Auto, None));
    }

    #[test]
    fn the_theme_toggle_flips_and_reports_the_one_in_use() {
        // `t` has to change something in the terminal too, or the shortcut
        // would be listed and do nothing. What it changes is the syntax
        // highlighting: the terminal owns the rest of its colours.
        use std::sync::atomic::{AtomicBool, Ordering};
        for start in [true, false] {
            let flag = AtomicBool::new(start);
            assert_eq!(flip(&flag), !start, "each press must flip the theme");
            assert_eq!(
                flag.load(Ordering::Relaxed),
                !start,
                "the reported theme must be the one actually stored"
            );
            assert_eq!(flip(&flag), start, "a second press must come back");
        }
    }

    #[test]
    fn the_two_syntax_themes_are_both_kept_in_the_cache() {
        // Only one used to be loaded, chosen at startup. Switching would have
        // meant reloading the set, which is the parse this cache exists to
        // avoid — so both are resolved once and picked between.
        let assets = syntax_assets();
        assert_ne!(
            assets.light.name, assets.dark.name,
            "the light and dark themes must be two different themes"
        );
    }

    /// Both theme names must exist in syntect's defaults, or highlighting would
    /// silently fall back to an empty theme.
    #[test]
    fn both_themes_exist_in_syntect_defaults() {
        let themes = syntect::highlighting::ThemeSet::load_defaults();
        for name in [DARK_SYNTAX_THEME, LIGHT_SYNTAX_THEME] {
            assert!(
                themes.themes.contains_key(name),
                "syntect has no theme {:?}; available: {:?}",
                name,
                themes.themes.keys().collect::<Vec<_>>()
            );
        }
    }

    // --- regressions found while writing the AST renderer ---

    /// `CommonMark` "tight" vs "loose": a list written without blank lines
    /// between its items must not gain any, and one written with them must
    /// keep them. Both directions broke at different points of the rewrite.
    #[test]
    fn a_tight_list_does_not_breathe_and_a_loose_one_does() {
        let tight = rendered("- un\n- deux\n- trois\n");
        let blanks = tight.iter().filter(|l| l.trim().is_empty()).count();
        assert_eq!(
            blanks, 0,
            "a tight list must not gain blank lines: {tight:?}"
        );

        let loose = rendered("- un\n\n- deux\n\n- trois\n");
        let blanks = loose.iter().filter(|l| l.trim().is_empty()).count();
        assert!(blanks >= 2, "a loose list must keep its spacing: {loose:?}");
    }

    /// A list nested inside a tight list must not add spacing of its own.
    #[test]
    fn a_nested_list_inside_a_tight_list_stays_tight() {
        let lines = rendered("- un\n- deux\n  - imbriqué\n- trois\n");
        assert!(
            !lines.iter().any(|l| l.trim().is_empty()),
            "no blank line belongs inside a tight list: {lines:?}"
        );
        assert!(
            lines
                .iter()
                .any(|l| l.starts_with("  ") && l.contains("imbriqué")),
            "the nested item must keep its indent: {lines:?}"
        );
    }

    /// `find_heading_row` scrolls the TOC by looking for the entry's text
    /// inside a rendered line. If the renderer ever decorated headings in a way
    /// that broke that `contains`, TOC navigation would silently stop working.
    #[test]
    fn every_toc_entry_can_still_be_found_in_the_rendered_lines() {
        let md = "# Un\n\ntexte\n\n## Deux trois\n\ntexte\n\n##### Cinq\n\ntexte\n";
        let lines = rendered(md);
        for entry in crate::core::toc::extract_toc(md) {
            assert!(
                lines.iter().any(|l| l.contains(&entry.text)),
                "TOC entry {:?} has no rendered line containing it: {:?}",
                entry.text,
                lines
            );
        }
    }

    /// Inline markup must not reach the screen as raw syntax.
    #[test]
    fn inline_markup_is_styled_not_printed() {
        let lines = rendered("A **b** *c* ~~d~~ `e` [f](http://x) end\n");
        let joined = lines.join(" ");
        for raw in ["**", "~~", "`", "](", "http://x"] {
            assert!(
                !joined.contains(raw),
                "raw {raw:?} reached the screen: {joined:?}"
            );
        }
        for word in ["b", "c", "d", "e", "f", "end"] {
            assert!(joined.contains(word), "{word:?} was dropped: {joined:?}");
        }
    }

    /// Column alignment markers are honoured, not just the width.
    #[test]
    fn table_alignment_markers_are_honoured() {
        let md = "| l | c | r |\n|:--|:-:|--:|\n| x | x | x |\n";
        let body = rendered(md)
            .into_iter()
            .find(|l| l.matches('x').count() == 3)
            .expect("body row");
        let cells: Vec<&str> = body.split('').collect();
        assert_eq!(cells.len(), 3, "expected three cells: {body:?}");
        assert!(cells[0].starts_with('x'), "left column: {:?}", cells[0]);
        assert!(
            cells[2].trim_start().ends_with('x'),
            "right column: {:?}",
            cells[2]
        );
    }

    // #59, symptom 1: headings deeper than #### are printed raw.
    #[test]
    fn h5_and_h6_are_rendered_as_headings_not_raw_text() {
        for (md, title) in [("##### Deep\n", "Deep"), ("###### Deeper\n", "Deeper")] {
            let lines = rendered(md);
            assert!(
                lines.iter().any(|l| l.trim() == title),
                "expected a line holding just {title:?}, got {lines:?}"
            );
            assert!(
                !lines.iter().any(|l| l.contains('#')),
                "the hashes must not reach the screen, got {lines:?}"
            );
        }
    }

    // #59, symptom 2: code blocks have no syntax highlighting.
    #[test]
    fn offline_mode_makes_no_request_at_all() {
        // `--offline` says "never access the network". This backend used to
        // fetch anyway — `core::offline` was not even compiled for it — so the
        // documentation promised something the code did not do. Counting the
        // calls is the only way to show none were made; a URL that fails would
        // pass either way.
        use std::sync::atomic::{AtomicUsize, Ordering};
        let calls = AtomicUsize::new(0);
        let fetch = |_: &str| -> LoadedImage {
            calls.fetch_add(1, Ordering::Relaxed);
            Err("should never be reached".into())
        };

        let result = load_image_with(
            "https://example.com/badge.svg",
            std::path::Path::new("/"),
            true,
            &fetch,
        );

        assert!(result.is_err(), "a remote image cannot load while offline");
        assert_eq!(
            calls.load(Ordering::Relaxed),
            0,
            "offline mode must not reach the network"
        );
    }

    #[test]
    fn a_remote_image_is_fetched_when_online() {
        // The other half of the contract: the refusal above is the flag, not a
        // backend that never fetches.
        use std::sync::atomic::{AtomicUsize, Ordering};
        let calls = AtomicUsize::new(0);
        let fetch = |_: &str| -> LoadedImage {
            calls.fetch_add(1, Ordering::Relaxed);
            Err("no network in a test".into())
        };

        let _ = load_image_with(
            "https://example.com/badge.svg",
            std::path::Path::new("/"),
            false,
            &fetch,
        );

        assert_eq!(calls.load(Ordering::Relaxed), 1, "the fetch should be used");
    }

    #[test]
    fn only_a_bare_t_flips_the_theme() {
        // `gui` refuses a modifier on this binding, and the terminal has to
        // agree: Ctrl+T and Alt+T belong to whoever else wants them.
        assert!(is_theme_toggle(KeyCode::Char('t'), KeyModifiers::NONE));
        for modifier in [
            KeyModifiers::CONTROL,
            KeyModifiers::ALT,
            KeyModifiers::SUPER,
        ] {
            assert!(
                !is_theme_toggle(KeyCode::Char('t'), modifier),
                "{modifier:?}+t must not flip the theme"
            );
        }
        assert!(!is_theme_toggle(KeyCode::Char('q'), KeyModifiers::NONE));
    }

    #[test]
    fn an_unlabelled_fence_is_painted_like_a_highlighted_one() {
        // The fallback used to be a bare green with no background, so the most
        // ordinary block of all — a fence with no language — sat unpainted
        // inside a painted frame.
        for code in ["plain text\n", "some code\n"] {
            for lang in ["", "wharrgarbl"] {
                for line in highlight_code(code, lang) {
                    for span in line {
                        assert!(
                            span.style.bg.is_some(),
                            "a {lang:?} fence must be painted like any other"
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn the_help_bar_offers_the_theme_toggle_on_a_standard_terminal() {
        // 80 columns of terminal leave the bar about 48. A fixed string of all
        // six hints is 78, so the toggle used to be clipped away exactly where
        // most people would have looked for it.
        let bar = help_bar(48);
        assert!(
            bar.contains("t: theme"),
            "the theme toggle must survive a standard terminal: {bar:?}"
        );
    }

    #[test]
    fn the_help_bar_drops_whole_hints_and_never_overflows() {
        for columns in 0..100 {
            let bar = help_bar(columns);
            assert!(
                str_width(&bar) <= columns,
                "{columns} columns produced a bar of {}: {bar:?}",
                str_width(&bar)
            );
            // Whole hints only: anything shown must be shown in full.
            for hint in HELP_HINTS {
                let shown = bar.contains(hint);
                let partial = !shown
                    && hint
                        .split_once(':')
                        .is_some_and(|(key, _)| bar.contains(&format!("{key}:")));
                assert!(!partial, "{hint:?} is cut short in {bar:?}");
            }
        }
    }

    #[test]
    fn a_wide_terminal_gets_every_hint() {
        let bar = help_bar(200);
        for hint in HELP_HINTS {
            assert!(bar.contains(hint), "{hint:?} missing from {bar:?}");
        }
    }

    #[test]
    fn a_code_block_paints_a_rectangular_panel_at_the_frame_width() {
        // A syntect theme picks its foregrounds for its own background. Without
        // one painted behind them, `--theme light` is dark text on whatever the
        // terminal happens to be — which on a dark terminal is barely legible.
        //
        // The rectangle is only claimed at the frame's own width, which is what
        // this checks: the lines as built. A viewport narrower than the frame
        // folds them like any other line, and a source line longer than the
        // frame is deliberately left wider rather than truncated. What survives
        // both is the painting, which is the part that matters — see the test
        // below.
        let md = "```rust\nfn main() {\n    let x: u32 = 42;\n}\n```\n";
        let block: Vec<Line<'static>> = markdown_to_lines_with_images(md)
            .into_iter()
            .filter_map(|item| match item {
                ParsedLine::Text(line) => Some(line),
                _ => None,
            })
            .filter(|line| {
                let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
                text.starts_with('') || text.starts_with('') || text.starts_with('')
            })
            .collect();
        assert!(
            block.len() >= 5,
            "expected a frame and three code lines, got {}",
            block.len()
        );

        let expected = str_width(CODE_FRAME_BOTTOM);
        for line in &block {
            let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
            assert_eq!(
                str_width(&text),
                expected,
                "every line of the block must be the frame's width, got {text:?}"
            );
            for span in &line.spans {
                assert!(
                    span.style.bg.is_some(),
                    "every span of the block must be painted, bare one in {text:?}"
                );
            }
        }
    }

    #[test]
    fn code_stays_painted_once_the_lines_are_folded() {
        // The panel is built at the frame's width, but it is drawn through
        // `wrap_line`. Folding must not hand a line back to the terminal's own
        // colours, or a narrow window would undo the legibility the painting is
        // there for.
        let md = "```rust\nfn main() { let a_rather_long_identifier = 42; }\n```\n";
        let block: Vec<Line<'static>> = markdown_to_lines_with_images(md)
            .into_iter()
            .filter_map(|item| match item {
                ParsedLine::Text(line) => Some(line),
                _ => None,
            })
            .filter(|line| {
                let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
                text.starts_with('')
            })
            .collect();
        assert!(!block.is_empty(), "expected at least one code line");

        for width in [20, 30, 43] {
            for line in &block {
                let folded = wrap_line(line, width);
                assert!(folded.len() > 1 || line.width() <= width, "expected a fold");
                for piece in folded {
                    for span in piece.spans {
                        assert!(
                            span.content.trim().is_empty() || span.style.bg.is_some(),
                            "a fold at {width} columns lost the painting: {:?}",
                            span.content
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn a_code_block_is_syntax_highlighted() {
        let md = "```rust\nfn main() { let x: u32 = 1; }\n```\n";
        let used = colours(md);
        assert!(
            used.len() > 3,
            "a highlighted Rust block should use more than a couple of colours, got {used:?}"
        );
    }

    // #59, symptom 3: table cells are not aligned on column width.
    #[test]
    fn table_cells_are_padded_to_the_column_width() {
        let md = "| a | long header |\n|---|---|\n| 1 | 2 |\n";
        let lines: Vec<String> = rendered(md)
            .into_iter()
            .filter(|l| l.contains('1') || l.contains("long header"))
            .collect();
        assert!(
            lines.len() >= 2,
            "expected header and body rows, got {lines:?}"
        );
        // Deliberately not trimmed: the trailing padding *is* the alignment.
        let widths: std::collections::BTreeSet<usize> =
            lines.iter().map(|l| l.chars().count()).collect();
        assert_eq!(
            widths.len(),
            1,
            "every row of a table must be the same width once padded, got {lines:?}"
        );
    }

    // #59, symptom 4: footnotes are not rendered — the raw `[^1]` and `[^1]:`
    // markers reach the screen instead of being turned into a reference and a
    // note section.
    #[test]
    fn footnotes_are_rendered() {
        let md = "Some text[^1].\n\n[^1]: The note itself.\n";
        let lines = rendered(md);
        assert!(
            lines.iter().any(|l| l.contains("The note itself")),
            "the footnote body must appear, got {lines:?}"
        );
        assert!(
            !lines.iter().any(|l| l.contains("[^1]")),
            "the raw footnote syntax must not reach the screen, got {lines:?}"
        );
    }
}