edamame 0.1.6

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

use edamame::config::Theme;
use edamame::editor::vim_ops::VisualKind;
use edamame::editor::Mode;
use edamame::ui::status_bar::{StatusBar, StatusBarState};

fn render_status_bar(
    mode: Mode,
    filename: &str,
    line_count: usize,
    modified: bool,
    width: u16,
) -> String {
    let theme = Box::leak(Box::new(Theme::default()));
    let backend = TestBackend::new(width, 1);
    let mut terminal = Terminal::new(backend).unwrap();

    terminal
        .draw(|frame| {
            let bar = StatusBar {
                state: StatusBarState {
                    mode,
                    filename,
                    line_count,
                    scroll_total: line_count,
                    viewport_rows: 1,
                    modified,
                    scroll: 0,
                    cursor_line: None,
                    cursor_col: None,
                    section_path: Vec::new(),
                    diff_progress: None,
                    vim_mode_label: None,
                },
                theme,
            };
            frame.render_widget(bar, frame.area());
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    (0..width)
        .map(|x| {
            buf.cell((x, 0))
                .map_or(' ', |c| c.symbol().chars().next().unwrap_or(' '))
        })
        .collect()
}

#[test]
fn status_bar_preview_mode() {
    let out = render_status_bar(Mode::Preview, "test.md", 42, false, 60);
    assert!(out.contains("PREVIEW"), "got: {out:?}");
}

#[test]
fn status_bar_filename() {
    let out = render_status_bar(Mode::Preview, "my_notes.md", 10, false, 60);
    assert!(out.contains("my_notes.md"), "got: {out:?}");
}

#[test]
fn status_bar_line_count() {
    let out = render_status_bar(Mode::Preview, "f.md", 123, false, 80);
    assert!(out.contains("123"), "got: {out:?}");
}

#[test]
fn status_bar_modified_flag() {
    let out = render_status_bar(Mode::Preview, "f.md", 5, true, 80);
    assert!(out.contains("f.md*"), "got: {out:?}");
    assert!(!out.contains("[modified]"), "got: {out:?}");
}

#[test]
fn status_bar_clean_no_modified_flag() {
    let out = render_status_bar(Mode::Preview, "f.md", 5, false, 80);
    assert!(!out.contains("f.md*"), "got: {out:?}");
}

#[test]
fn status_bar_raw_mode_label() {
    let out = render_status_bar(Mode::Raw, "f.md", 5, false, 60);
    assert!(out.contains("RAW"), "got: {out:?}");
}

#[test]
fn status_bar_edit_mode_label() {
    let out = render_status_bar(Mode::Rendered, "f.md", 5, false, 60);
    assert!(out.contains("EDIT"), "got: {out:?}");
}

#[test]
fn snapshot_status_bar_preview() {
    let out = render_status_bar(Mode::Preview, "readme.md", 100, false, 80);
    insta::assert_snapshot!(out);
}

#[test]
fn snapshot_status_bar_modified() {
    let out = render_status_bar(Mode::Rendered, "notes.md", 42, true, 80);
    insta::assert_snapshot!(out);
}

/// Render the status bar with a vim sub-mode badge (`NORMAL` / `INSERT` /
/// `VISUAL` / `V-LINE`), which takes precedence over the rendering-mode
/// badge.  The view mode stays `Rendered` (vim never rests in Preview).
fn render_status_bar_vim(label: &str, width: u16) -> String {
    let theme = Box::leak(Box::new(Theme::default()));
    let backend = TestBackend::new(width, 1);
    let mut terminal = Terminal::new(backend).unwrap();
    terminal
        .draw(|frame| {
            let bar = StatusBar {
                state: StatusBarState {
                    mode: Mode::Rendered,
                    filename: "notes.md",
                    line_count: 42,
                    scroll_total: 42,
                    viewport_rows: 1,
                    modified: false,
                    scroll: 0,
                    cursor_line: Some(1),
                    cursor_col: Some(1),
                    section_path: Vec::new(),
                    diff_progress: None,
                    vim_mode_label: Some(label),
                },
                theme,
            };
            frame.render_widget(bar, frame.area());
        })
        .unwrap();
    let buf = terminal.backend().buffer().clone();
    (0..width)
        .map(|x| {
            buf.cell((x, 0))
                .map_or(' ', |c| c.symbol().chars().next().unwrap_or(' '))
        })
        .collect()
}

#[test]
fn status_bar_vim_normal_badge_wins_over_view_mode() {
    let out = render_status_bar_vim("NORMAL", 60);
    assert!(out.contains("NORMAL"), "got: {out:?}");
    // The vim badge replaces the rendering-mode `EDIT` badge.
    assert!(!out.contains("EDIT"), "got: {out:?}");
}

#[test]
fn snapshot_status_bar_vim_normal() {
    let out = render_status_bar_vim("NORMAL", 80);
    insta::assert_snapshot!(out);
}

#[test]
fn snapshot_status_bar_vim_insert() {
    let out = render_status_bar_vim("INSERT", 80);
    insta::assert_snapshot!(out);
}

#[test]
fn snapshot_status_bar_vim_visual() {
    let out = render_status_bar_vim("VISUAL", 80);
    insta::assert_snapshot!(out);
}

#[test]
fn yank_flash_paints_the_yanked_span() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::terminal::Capabilities;
    use edamame::ui::bottom_region::{HintContent, HintSet};
    use edamame::ui::{EditorView, EditorViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let mut state = EditorState::new(Buffer::from_str("hello world\n"), theme);
    state.mode = Mode::Rendered;
    // Flash "hello" (chars 0..5).
    state.flash_yank(0, 5);

    let backend = TestBackend::new(40, 6);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = EditorViewState::new();
    let caps = Capabilities::default();
    terminal
        .draw(|frame| {
            let view = EditorView {
                state: &mut state,
                theme,
                filename: "test.md",
                show_table_buttons: false,
                table_drop_indicator: None,
                capabilities: &caps,
                show_line_numbers: false,
                is_scrolling: false,
                hint: HintContent::Chords(HintSet::default()),
                vim_mode_label: None,
                visual_kind: None,
                editor_cursor_style: theme.status_mode_rendered,
                max_width_enabled: false,
                max_width_cols: 0,
                scrollbar_active: false,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    // Cols 1..5 of row 0 ("ello") must carry the flash (selection) bg — col 0
    // holds the block cursor, which wins over the wash.
    for x in 1..5u16 {
        assert_eq!(
            buf.cell((x, 0)).unwrap().style().bg,
            theme.selection.bg,
            "yanked col {x} must carry the flash bg"
        );
    }
    // The space after "hello" (col 5) is outside the flash span.
    assert_ne!(buf.cell((5, 0)).unwrap().style().bg, theme.selection.bg);
}

#[test]
fn rendered_view_paints_selection_across_multiple_rendered_blocks() {
    use edamame::document::{Buffer, Selection};
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // Two paragraphs separated by a blank line.  Selection starts mid-first
    // paragraph and ends mid-second.
    let src = "first para here\n\nsecond para here\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    // Selection covers all of "para" in first and "second" in second.
    // Use char offsets that span multiple blocks.
    state.selection = Some(Selection {
        anchor: 6,  // start of "para" in first
        active: 23, // part-way into "second"
    });
    state.cursor.offset = 23;

    let backend = TestBackend::new(25, 5);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    // Row 0 is "first para here" — at least one cell on it must have the
    // selection bg (cells 6+ for "para here").
    let row_has_sel_bg = |y: u16| {
        (0..25u16).any(|x| {
            buf.cell((x, y))
                .map(|c| c.style().bg == theme.selection.bg)
                .unwrap_or(false)
        })
    };
    assert!(row_has_sel_bg(0), "first paragraph row must show selection");
    // Row 2 is the second paragraph.  It should also have selection bg on
    // the covered portion.
    assert!(
        row_has_sel_bg(2),
        "second paragraph row must show selection"
    );
}

/// With reflow on in Rendered mode a reflowed paragraph renders as one wrapped flow, but
/// revealing it (cursor inside) must stack all its raw source lines — not just the cursor's one
/// line — so you edit the real bytes.
#[test]
fn reflowed_paragraph_reveals_all_raw_source_lines_stacked() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // Markdown that differs raw-vs-rendered (`**bold**`) so the reveal is unmistakable.
    let src = "**bold** words\nsecond line\nthird line\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    state.set_viewport_width(40);
    state.set_reflow(true);
    // Cursor at the start → inside the paragraph; `cursor_block_entered_at == None` ⇒ revealed.
    state.cursor.offset = 0;

    let width = 40u16;
    let backend = TestBackend::new(width, 6);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();
    let buf = terminal.backend().buffer().clone();
    let row_text = |y: u16| -> String {
        (0..width)
            .filter_map(|x| buf.cell((x, y)).map(|c| c.symbol().to_string()))
            .collect::<String>()
    };
    assert!(
        row_text(0).contains("**bold**"),
        "row 0 must show the raw first source line, got {:?}",
        row_text(0)
    );
    assert!(
        row_text(1).contains("second line"),
        "row 1 must show the raw second source line, got {:?}",
        row_text(1)
    );
    assert!(
        row_text(2).contains("third line"),
        "row 2 must show the raw third source line, got {:?}",
        row_text(2)
    );
}

/// A nested reflowed paragraph (a quote's, an item's) reveals the same way, but alone: its one
/// flow row expands to its whole source lines, container prefix included (`> `, `- `, the
/// continuation indent), while the rows around it — the quote's other paragraphs, the sibling
/// items, a footnote's first paragraph — stay rendered and the rows below shift down past the
/// stack.
#[test]
fn nested_reflowed_paragraph_reveals_its_whole_source_lines_stacked() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let width = 40u16;
    for (src, needle, expected) in [
        (
            "> first para\n>\n> alpha bravo\n> charlie delta\n>\n> last\n",
            "charlie",
            &[
                "▎ first para",
                "▎",
                "> alpha bravo",
                "> charlie delta",
                "▎",
                "▎ last",
            ][..],
        ),
        (
            "- one\n- alpha bravo\n  charlie delta\n- three\n",
            "charlie",
            &["• one", "- alpha bravo", "  charlie delta", "• three"],
        ),
        (
            // `b soft` continues item `a`'s paragraph, so both its lines stack.
            "> - a\n>   b soft\n> - c\n",
            "soft",
            &["> - a", ">   b soft", "▎ • c"],
        ),
        (
            // The nested item renders at its 4-cell nesting, so its 2-space source lines reveal
            // padded by the difference, keeping the text where it was (issue #65).
            "- a\n  - b\n    soft word\n- c\n",
            "soft",
            &["• a", "    - b", "      soft word", "• c"],
        ),
        (
            // A footnote's first paragraph stacks from its `[^n]:` line; the second stays a flow.
            // The continuation's 4-space indent is padded to the leader's 6, the column the
            // flow's text starts at.
            "ref[^n]\n\n[^n]: note one\n    two three\n\n    second para\n    more\n\nafter\n",
            "two",
            &[
                "ref[n]",
                "",
                "[^n]: note one",
                "      two three",
                "",
                "      second para more ↩",
                "",
                "after",
            ],
        ),
        (
            // Its second paragraph: the first stays one rendered flow behind the leader.
            "ref[^n]\n\n[^n]: note one\n    two three\n\n    second para\n    more\n\nafter\n",
            "more",
            &[
                "ref[n]",
                "",
                "  n.  note one two three",
                "",
                "      second para",
                "      more",
                "",
                "after",
            ],
        ),
    ] {
        let mut state = EditorState::new(Buffer::from_str(src), theme);
        state.mode = Mode::Rendered;
        state.set_viewport_width(width as usize);
        state.set_reflow(true);
        state.cursor.offset = src.find(needle).unwrap();
        state.update_cursor_block();
        state.cursor_block_entered_at = None;

        let mut terminal = Terminal::new(TestBackend::new(width, 8)).unwrap();
        let mut view_state = RenderedViewState::default();
        terminal
            .draw(|frame| {
                let view = RenderedView {
                    cursor_style: theme.status_mode_rendered,
                    visual_kind: None,
                    drop_indicator: None,
                    show_table_buttons: false,
                    state: &state,
                    theme,
                };
                frame.render_stateful_widget(view, frame.area(), &mut view_state);
            })
            .unwrap();
        let buf = terminal.backend().buffer().clone();
        let rows: Vec<String> = (0..expected.len() as u16)
            .map(|y| {
                (0..width)
                    .map(|x| buf.cell((x, y)).unwrap().symbol().to_string())
                    .collect::<String>()
                    .trim_end()
                    .to_string()
            })
            .collect();
        assert_eq!(rows, expected, "in {src:?}");
    }
}

/// Regression: with the cursor on the phantom final line (after the source's
/// trailing '\n'), the last real block must stay rendered.  Before the
/// phantom-line virtual block existed, the cursor fell back to the last real
/// block and its rendered text was replaced by an empty raw reveal —
/// "swallowing" the next-to-last line.
#[test]
fn cursor_on_phantom_final_line_does_not_swallow_last_block() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let src = "Alpha\n\nBeta\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    // Cursor at the very end of the buffer — on the phantom empty line.
    state.cursor.offset = src.chars().count();

    let backend = TestBackend::new(25, 5);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let row_text = |y: u16| -> String {
        (0..25u16)
            .filter_map(|x| buf.cell((x, y)).map(|c| c.symbol().to_string()))
            .collect()
    };
    assert!(
        row_text(2).contains("Beta"),
        "last text line must stay rendered with cursor on the phantom line, got {:?}",
        row_text(2)
    );
}

/// Regression: with the cursor inside a loose (blank-separated) list, the raw
/// reveal of the cursor's line must land on that line's *rendered* row — not
/// be shifted up by the separator blanks, which now render as their own rows.
/// This guards the raw→rendered line mapping in the reveal against a
/// re-introduction of the old "count only non-blank lines" compression, which
/// swallowed the blank row and painted the raw line one row too high.
#[test]
fn cursor_in_loose_list_reveals_correct_row_and_keeps_blank() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // Source restarts numbering after the blank; the loose list renders it
    // sequentially (1, 2, 3, 4) but the raw reveal shows the literal `1.`.
    let src = "1. alpha\n2. beta\n\n1. gamma\n2. delta\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    state.cursor.offset = src.find("gamma").unwrap();

    let backend = TestBackend::new(20, 8);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let row_text = |y: u16| -> String {
        (0..20u16)
            .filter_map(|x| buf.cell((x, y)).map(|c| c.symbol().to_string()))
            .collect::<String>()
            .trim_end()
            .to_string()
    };
    assert_eq!(row_text(0), "1. alpha");
    assert_eq!(row_text(1), "2. beta");
    assert_eq!(row_text(2), "", "separator blank row must be preserved");
    // Cursor's line is revealed raw: the literal `1. gamma`, at its own row.
    assert_eq!(
        row_text(3),
        "1. gamma",
        "cursor line must reveal raw source at its true rendered row"
    );
    // Sibling item keeps its sequential rendered number.
    assert_eq!(row_text(4), "4. delta");
}

/// Selection highlight on a line with inline bold markup should cover the
/// *rendered* glyph positions (cells 0-3 for "bold"), not the raw positions
/// (cells 2-7 for "**bold**").  This catches "map is correct but never
/// called" wiring bugs that unit tests alone would miss.
#[test]
fn selection_on_bold_text_highlights_rendered_positions() {
    use edamame::document::{Buffer, Selection};
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // Line 0 is a spacer so line 1 stays rendered (cursor on line 0).
    // Line 1: "**bold** text" renders as "bold text".
    let src = "x\n**bold** text\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    // Select the raw range covering "bold" inside the ** markers.
    // "x\n" = 2 chars, then "**" = 2 more, so "bold" starts at char 4
    // and ends at char 8 (exclusive).
    state.selection = Some(Selection {
        anchor: 4,
        active: 8,
    });
    state.cursor.offset = 0; // cursor on line 0

    let width = 40u16;
    let backend = TestBackend::new(width, 5);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    // Row 1 renders "bold text".  Selection should highlight cells 0-3
    // ("bold" in rendered coords), NOT cells 2-7 (raw coords with markers).
    let cell_has_sel = |x: u16, y: u16| {
        buf.cell((x, y))
            .map(|c| c.style().bg == theme.selection.bg)
            .unwrap_or(false)
    };
    // Rendered "bold" occupies cells 0..4 on row 1.
    for x in 0..4 {
        assert!(
            cell_has_sel(x, 1),
            "cell ({x}, 1) should have selection bg (rendered 'bold' range)"
        );
    }
    // Cell 4 is the space after "bold" — should NOT be selected.
    assert!(
        !cell_has_sel(4, 1),
        "cell (4, 1) should NOT have selection bg (past 'bold')"
    );
}

/// Regression: a VisualLine selection over a rendered list line must paint the
/// list marker (`• ` / `1. `) too, not just the item text.  The marker→content
/// column map snaps a within-marker start forward to the content column, so a
/// full-line (col-0) selection would otherwise leave the marker cells unpainted
/// even though the underlying bytes are selected.
#[test]
fn visual_line_selection_paints_the_list_marker() {
    use edamame::document::{Buffer, Selection};
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // Line 0 is a spacer holding the cursor so the list lines below stay
    // rendered (a cursor on a list line would reveal it as raw instead).
    let src = "x\n- alpha\n- beta\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    // Charwise anchors inside the two bullet items; VisualLine widening
    // expands them to the whole lines (markers included).
    state.selection = Some(Selection {
        anchor: 4,  // inside "alpha"
        active: 14, // inside "beta"
    });
    state.cursor.offset = 0; // cursor parked on the spacer line

    let backend = TestBackend::new(25, 5);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: Some(VisualKind::Line),
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let cell_has_sel = |x: u16, y: u16| {
        buf.cell((x, y))
            .map(|c| c.style().bg == theme.selection.bg)
            .unwrap_or(false)
    };
    // Row 1 renders "• alpha": cell 0 is the bullet marker and must be
    // highlighted, as must the content past it.
    assert!(
        cell_has_sel(0, 1),
        "VisualLine highlight must cover the list marker cell, not start past it"
    );
    assert!(cell_has_sel(2, 1), "item content must stay highlighted");
    // Row 2 ("• beta") must be fully covered the same way.
    assert!(cell_has_sel(0, 2), "second item marker must be highlighted");
}

#[test]
fn setext_heading_reveals_both_title_and_underline_on_cursor() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // Setext H2 heading followed by a blank line + paragraph so the reveal
    // region is isolated.
    let src = "Title\n-----\n\nBody\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    // Cursor on the underline line (raw line 1).  Leaving `cursor_block_entered_at`
    // as None makes `cursor_block_revealed` return true immediately.
    state.cursor.offset = src.find('-').unwrap();

    let backend = TestBackend::new(20, 5);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let row_text = |y: u16| -> String {
        (0..20u16)
            .map(|x| {
                buf.cell((x, y))
                    .map_or(' ', |c| c.symbol().chars().next().unwrap_or(' '))
            })
            .collect()
    };
    // Row 0 must show the raw title "Title", not the styled heading glyph.
    assert!(
        row_text(0).starts_with("Title"),
        "row 0 = {:?}",
        row_text(0)
    );
    // Row 1 must show the raw underline, not a rendered rule.  The block
    // cursor recolors a cell but leaves the character visible.
    assert!(
        row_text(1).starts_with("-----"),
        "row 1 = {:?}",
        row_text(1)
    );
}

/// Paint `src` revealed in Rendered mode, the cursor at char `offset`, 20 cells wide: each
/// row's text, and the column of the cell carrying the cursor's colors, with its row.
fn paint_revealed(src: &str, offset: usize) -> (Vec<String>, Option<(u16, u16)>) {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    state.cursor.offset = offset;
    state.update_cursor_block();
    state.cursor_block_entered_at = None;

    let mut terminal = Terminal::new(TestBackend::new(20, 6)).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();
    let buf = terminal.backend().buffer().clone();
    let rows = (0..6u16)
        .map(|y| {
            (0..20u16)
                .map(|x| buf.cell((x, y)).map_or(" ", |c| c.symbol()))
                .collect::<String>()
                .trim_end()
                .to_owned()
        })
        .collect();
    let cursor_bg = theme.status_mode_rendered.bg.unwrap();
    let cursor = (0..6u16)
        .flat_map(|y| (0..20u16).map(move |x| (x, y)))
        .find(|&cell| buf.cell(cell).is_some_and(|c| c.bg == cursor_bg));
    (rows, cursor)
}

/// Paint `src` in Rendered mode at `width`, the cursor at byte `cursor` with its row revealed,
/// or held off (no reveal) when `None`: each row's text, trailing blanks trimmed, and the cell
/// carrying the cursor's colors.
fn paint_rows(src: &str, width: u16, cursor: Option<usize>) -> (Vec<String>, Option<(u16, u16)>) {
    use std::time::{Duration, Instant};

    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    const HEIGHT: u16 = 14;
    let theme = Box::leak(Box::new(Theme::default()));
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    state.set_viewport_width(usize::from(width));
    if let Some(byte) = cursor {
        state.cursor.offset = state.buffer.rope().byte_to_char(byte);
        state.update_cursor_block();
    }
    state.cursor_block_entered_at = match cursor {
        Some(_) => None,
        None => Some(Instant::now() + Duration::from_secs(3600)),
    };
    let mut terminal = Terminal::new(TestBackend::new(width, HEIGHT)).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();
    let buf = terminal.backend().buffer().clone();
    let mut rows: Vec<String> = (0..HEIGHT)
        .map(|y| {
            (0..width)
                .map(|x| buf.cell((x, y)).map_or(" ", |c| c.symbol()))
                .collect::<String>()
                .trim_end()
                .to_owned()
        })
        .collect();
    while rows.last().is_some_and(String::is_empty) {
        rows.pop();
    }
    let cursor_bg = theme.status_mode_rendered.bg.unwrap();
    let cell = (0..HEIGHT)
        .flat_map(|y| (0..width).map(move |x| (x, y)))
        .find(|&c| buf.cell(c).is_some_and(|c| c.bg == cursor_bg));
    (rows, cell)
}

/// A prefix before long CJK text keeps the text's first glyphs on its row (issue #58): CJK
/// breaks between any two glyphs, so a list marker, a quote bar or a `Note:` label no longer
/// goes alone onto a row of its own.
#[test]
fn a_prefix_before_long_cjk_text_keeps_it_on_its_row() {
    let text = "日本語のリスト項目がとても長くてテキストが続きます";
    for (src, head) in [
        (format!("- {text}\n"), "• 日"),
        (format!("> {text}\n"), "▎ 日"),
        (format!("Note: {text}\n"), "Note: 日"),
    ] {
        let (rows, _) = paint_rows(&src, 24, None);
        assert!(rows[0].starts_with(head), "{rows:?} in {src:?}");
    }
}

/// A reflowed paragraph's soft break between CJK glyphs renders as nothing (issue #79), as a
/// browser renders it, at the top level and nested; beside Latin text or Hangul it stays a space.
#[test]
fn a_soft_break_between_cjk_glyphs_renders_as_nothing() {
    use unicode_width::UnicodeWidthChar;

    for (src, row) in [
        ("日本語の\nリスト項目が\n", "日本語のリスト項目が"),
        ("- 日本語の\n  リスト項目が\n", "• 日本語のリスト項目が"),
        ("> 日本語の\n> リスト項目が\n", "▎ 日本語のリスト項目が"),
        ("日本語の\n、続き\n", "日本語の、続き"),
        ("**日本**\n*語*\n", "日本語"),
        ("日本語の\nabc\n", "日本語の abc"),
        ("한국어\n문장\n", "한국어 문장"),
    ] {
        // The buffer holds a wide glyph's second cell as a blank.
        let row: String = row
            .chars()
            .flat_map(|c| [Some(c), (c.width() == Some(2)).then_some(' ')])
            .flatten()
            .collect();
        let (rows, _) = paint_rows(src, 40, None);
        assert_eq!(
            rows.first().map(|r| r.trim_end()),
            Some(row.trim_end()),
            "{rows:?} in {src:?}"
        );
    }
}

/// A code line wider than the viewport with no break point of its own starts on its first row
/// (issue #58): the only break used to be the pad cell, which left a blank row above the text.
#[test]
fn a_long_code_line_starts_on_its_first_row() {
    for src in [
        "```\nabcdefghijklmnopqrstuvwxyz0123456789\n```\n",
        "```\n日本語のコードはとても長い行になります\n```\n",
    ] {
        let (rows, _) = paint_rows(src, 20, None);
        // The fence row, then the line's rows; the closing fence row is blank and dropped.
        assert!(
            rows.len() > 2 && rows[1..].iter().all(|r| !r.trim().is_empty()),
            "{rows:?} in {src:?}"
        );
    }
}

/// A wrapped row's continuation rows start where the renderer drew its text, never where its
/// text merely looks like it starts (issue #71): a footnote hangs under the text past its leader,
/// numeric or named, and a paragraph opening with an escaped marker doesn't hang at all, at top
/// level or in a quote.  Each was guessed from the row's text, one cell short, under the label,
/// and as a list item, respectively.
#[test]
fn wrapped_rows_hang_where_the_renderer_drew_their_text() {
    for (src, width, expected) in [
        (
            "ref[^1]\n\n[^1]: alpha bravo charlie delta echo foxtrot golf\n",
            24,
            &[
                "ref[1]",
                "",
                "  1.  alpha bravo",
                "      charlie delta",
                "      echo foxtrot golf",
                "      ↩",
            ][..],
        ),
        (
            "ref[^note]\n\n[^note]: alpha bravo charlie delta echo foxtrot golf\n",
            24,
            &[
                "ref[note]",
                "",
                "  note.  alpha bravo",
                "         charlie delta",
                "         echo foxtrot",
                "         golf ↩",
            ],
        ),
        (
            "1\\. alpha bravo charlie delta echo\n",
            16,
            &["1. alpha bravo", "charlie delta", "echo"],
        ),
        (
            "\\- alpha bravo charlie delta echo\n",
            16,
            &["- alpha bravo", "charlie delta", "echo"],
        ),
        (
            "> 2\\. alpha bravo charlie delta echo\n",
            16,
            &["▎ 2. alpha", "▎ bravo charlie", "▎ delta echo"],
        ),
    ] {
        // The cursor rests on the trailing blank line, so nothing reveals.
        let (rows, _) = paint_rows(src, width, Some(src.len()));
        assert_eq!(rows, expected, "in {src:?}");
    }
}

/// A revealed ordered item keeps its rendered marker alignment: ` 6.` beside `10.` reveals as
/// ` 6.`, not `6.`, so its text doesn't move a cell left, and its wrapped rows hang under that
/// text (issue #65).  The cursor shows on the char it rests on, past the pad.
#[test]
fn a_revealed_ordered_item_keeps_its_marker_alignment() {
    let src = "1. a\n2. b\n3. c\n4. d\n5. e\n6. alpha bravo charlie delta echo\n7. g\n8. h\n\
               9. i\n10. j\n";
    let at = src.find("lpha").unwrap();
    let (rendered, _) = paint_rows(src, 16, None);
    let (revealed, cursor) = paint_rows(src, 16, Some(at));
    assert_eq!(rendered[5], " 6. alpha bravo");
    assert_eq!(revealed[5], " 6. alpha bravo");
    assert_eq!(revealed[6..8], ["    charlie", "    delta echo"]);
    assert_eq!(revealed[8], " 7. g");
    assert_eq!(cursor, Some((5, 5)), "on the `l` of `alpha`");
}

/// Vertical navigation lays each line out as the view paints it: on every char, the column
/// `current_visual_col` reports is the cell the cursor paints at, and a visual move down lands
/// one painted row lower: always within the line, and onto the next one where moving the reveal
/// there changes no height (a footnote's rendered back-link takes a row of its own here).
/// Navigation once wrapped the whole buffer line, so it counted an indented paragraph's
/// unpainted indent and missed a code row's pad cell.
#[test]
fn vertical_navigation_lands_where_the_cursor_paints() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;

    const WIDTH: u16 = 12;
    let state_at = |src: &str, byte: usize| {
        let theme = Box::leak(Box::new(Theme::default()));
        let mut state = EditorState::new(Buffer::from_str(src), theme);
        state.mode = Mode::Rendered;
        state.set_viewport_width(usize::from(WIDTH));
        state.cursor.offset = state.buffer.rope().byte_to_char(byte);
        state.update_cursor_block();
        state
    };
    for (src, line, crosses) in [
        ("  para alpha bravo charlie delta\n\nend\n", 0, true),
        ("```\n    code alpha bravo charlie\n```\n\nend\n", 1, true),
        (
            "- a\n\n  ```\n    code alpha bravo\n  ```\n\nend\n",
            3,
            true,
        ),
        ("> - alpha bravo charlie delta\n\nend\n", 0, true),
        (
            "x[^1]\n\n[^1]: alpha bravo charlie delta\n\nend\n",
            2,
            false,
        ),
        (
            "1. a\n2. b\n3. c\n4. d\n5. e\n6. alpha bravo charlie delta\n7. g\n8. h\n9. i\n\
             10. j\n",
            5,
            true,
        ),
    ] {
        let start: usize = src.split_inclusive('\n').take(line).map(str::len).sum();
        let end = start + src[start..].find('\n').unwrap();
        for byte in start..end {
            let (_, painted) = paint_rows(src, WIDTH, Some(byte));
            let (x, y) = painted.unwrap_or_else(|| panic!("no cursor at {byte} in {src:?}"));
            let mut state = state_at(src, byte);
            let col = state.current_visual_col(usize::from(WIDTH));
            assert_eq!(col, usize::from(x), "column at byte {byte} of {src:?}");

            state.cursor.preferred_col = col;
            state.move_down_visual(usize::from(WIDTH));
            let below = state.buffer.rope().char_to_byte(state.cursor.offset);
            let (_, moved) = paint_rows(src, WIDTH, Some(below));
            let (_, moved_y) = moved.unwrap();
            if !crosses && below > end {
                continue;
            }
            assert_eq!(
                moved_y,
                y + 1,
                "down from byte {byte} of {src:?} to {below}"
            );
        }
    }
}

/// A multi-line setext heading renders its text on one row.  With the cursor on any of its
/// lines, the underline included, that row stacks every text line, and the rule reveals as the
/// underline; the cursor shows on its own line.  It once showed only the cursor's line, or
/// only the first, with the cursor on the underline.
#[test]
fn multi_line_setext_heading_reveals_every_text_line() {
    let src = "Multi\nline\n---\n\nBody\n";
    for (line, at) in [(0u16, "Multi"), (1, "line"), (2, "---")] {
        let offset = src.find(at).unwrap() + 1;
        let (rows, cursor) = paint_revealed(src, offset);
        assert_eq!(
            rows[..3],
            ["Multi", "line", "---"],
            "the cursor on line {line}"
        );
        assert_eq!(
            cursor,
            Some((1, line)),
            "the cursor on line {line}: {rows:?}"
        );
    }
}

/// A link reference definition inside a quote renders no row: the line below it shares it.
/// With the cursor on the definition, both lines show, so the cursor's line no longer paints
/// over the one below.
#[test]
fn a_quotes_hidden_definition_reveals_with_the_line_below() {
    let src = "> a\n>\n> [d]: /u\n> b\n\nafter\n";
    let (rows, cursor) = paint_revealed(src, src.find("[d]").unwrap() + 1);
    assert_eq!(rows[2], "> [d]: /u", "{rows:?}");
    assert_eq!(rows[3], "> b", "{rows:?}");
    assert_eq!(cursor, Some((3, 2)), "{rows:?}");
}

/// A comment inside a quote renders no row either, and reveals the same way: with the line below.
#[test]
fn a_quotes_hidden_comment_reveals_with_the_line_below() {
    let src = "> a\n>\n> <!-- note -->\n> b\n\nafter\n";
    let (rows, cursor) = paint_revealed(src, src.find("note").unwrap());
    assert_eq!(rows[2], "> <!-- note -->", "{rows:?}");
    assert_eq!(rows[3], "> b", "{rows:?}");
    assert_eq!(cursor, Some((7, 2)), "{rows:?}");
}

/// A hidden definition sharing a marker row (`- - a`'s outer bullet, whose line shows again on
/// the row below) reveals over that row alone: stacking the marker's line too would show it
/// twice, raw and then rendered.
#[test]
fn a_hidden_definition_over_a_marker_row_shows_no_line_twice() {
    let src = "> [d]: /u\n> - - a\n\nafter\n";
    let (rows, cursor) = paint_revealed(src, src.find("[d]").unwrap() + 1);
    assert_eq!(rows[0], "> [d]: /u", "{rows:?}");
    assert!(rows[1].ends_with("• a"), "{rows:?}");
    assert!(!rows.iter().any(|r| r == "> - - a"), "{rows:?}");
    assert_eq!(cursor, Some((3, 0)), "{rows:?}");
}

/// The quote's background wash reaches the viewport edge (the way a code
/// block's does), and the one row revealed as raw source while the cursor
/// rests in it keeps that wash rather than dropping out of the block.
#[test]
fn blockquote_wash_fills_the_row_and_survives_the_raw_reveal() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let src = "> quoted\n> lines\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    // Cursor on raw line 0.  Leaving `cursor_block_entered_at` as None makes
    // `cursor_block_revealed` return true immediately.
    state.cursor.offset = 0;

    let backend = TestBackend::new(20, 4);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let wash = theme.blockquote_text.bg;
    // Row 1 is rendered: the bar, the text, and every trailing cell carry
    // the wash.
    for x in 0..20u16 {
        assert_eq!(
            buf.cell((x, 1)).unwrap().style().bg,
            wash,
            "rendered quote row must be washed to the edge at col {x}"
        );
    }
    // Row 0 is revealed as raw `> quoted` — still inside the quote, so still
    // washed.  Col 0 carries the block cursor, which wins over the wash.
    for x in 1..20u16 {
        assert_eq!(
            buf.cell((x, 0)).unwrap().style().bg,
            wash,
            "revealed quote row must keep the wash at col {x}"
        );
    }
}

/// The blank line after a quote is not in the quote, though pulldown-cmark's range for the quote
/// absorbs it: with the cursor there, the revealed blank row takes the normal background, not
/// the quote's wash.
#[test]
fn a_blank_line_after_a_quote_reveals_without_its_wash() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let src = "> quoted\n\nafter\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    // Cursor on the blank line (row 1), which is revealed with no reveal delay pending.
    state.cursor.offset = src.find("\n\n").unwrap() + 1;

    let backend = TestBackend::new(20, 4);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let wash = theme.blockquote_text.bg;
    assert_eq!(
        buf.cell((5, 0)).unwrap().style().bg,
        wash,
        "the quote row keeps its wash"
    );
    // Col 0 carries the block cursor.
    for x in 1..20u16 {
        assert_ne!(
            buf.cell((x, 1)).unwrap().style().bg,
            wash,
            "the blank row after the quote must not take its wash at col {x}"
        );
    }
}

#[test]
fn rendered_view_selection_in_table_cell_does_not_spill_into_borders() {
    use edamame::document::{Buffer, Selection};
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // 3-row table; select just the "yy" bytes in the data row.
    let src = "| a | bb | c |\n|---|----|---|\n| x | yy | z |\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    let yy_start = src.find("yy").unwrap();
    state.selection = Some(Selection {
        anchor: yy_start,
        active: yy_start + 2,
    });
    // Place cursor elsewhere (col 0 of header) so the cursor block reveal
    // path doesn't overlap the data cell's selection highlight.
    state.cursor.offset = 0;

    let backend = TestBackend::new(30, 6);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let has_sel_bg = |x: u16, y: u16| {
        buf.cell((x, y))
            .map(|c| c.style().bg == theme.selection.bg)
            .unwrap_or(false)
    };
    // Row 0 is the top border (┌─┬─┐) — no selection bg anywhere.
    for x in 0..30u16 {
        assert!(
            !has_sel_bg(x, 0),
            "top border col {x} must not carry selection bg"
        );
    }
    // Row 2 is the separator (├─┼─┤) — no selection bg.
    for x in 0..30u16 {
        assert!(
            !has_sel_bg(x, 2),
            "separator col {x} must not carry selection bg"
        );
    }
    // Row 3 is the data row.  Some cells there MUST carry the selection bg
    // (where "yy" is rendered).  We don't pin exact cols here — the renderer
    // decides layout widths — but at least one cell must be highlighted.
    let data_row_has_sel = (0..30u16).any(|x| has_sel_bg(x, 3));
    assert!(
        data_row_has_sel,
        "data row must show selection bg on the 'yy' cell"
    );
}

#[test]
fn rendered_view_selection_inside_cursors_own_cell_survives_cell_overlay() {
    // Regression for the issue: after click-drag selection within a
    // table cell (or a double-/triple-click that lands the cursor inside its
    // own cell) the highlight used to vanish because the cell overlay
    // repainted the cell's rendered cells with raw text, clobbering whatever
    // `paint_selection_overlay` had drawn.
    use edamame::document::{Buffer, Selection};
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let src = "| aaa | bbb | ccc |\n|---|---|---|\n| 1 | 2 | 3 |\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;

    // Cursor on the first 'b' of the middle header cell — char 8 in `src`.
    // Leaving `cursor_block_entered_at` at None makes `cursor_block_revealed`
    // return true immediately, so the cell overlay path is taken.
    state.cursor.offset = 8;
    // Select "bbb" — raw chars [8..11).
    state.selection = Some(Selection {
        anchor: 8,
        active: 11,
    });

    let backend = TestBackend::new(25, 5);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let has_sel_bg = |x: u16, y: u16| {
        buf.cell((x, y))
            .map(|c| c.style().bg == theme.selection.bg)
            .unwrap_or(false)
    };
    // At least one cell across the active cell's rendered range (cols 7..11 on
    // row 1 — the header with "bbb") must carry the selection bg.  Before the
    // fix, all cells here were painted by `overlay_raw_cell` using only the
    // base style, so the selection bg was lost entirely on this row.
    let any_cell_highlighted = (7u16..=11).any(|x| has_sel_bg(x, 1));
    assert!(
        any_cell_highlighted,
        "selection bg must survive the cell overlay for the cursor's own cell"
    );
}

/// A table nested in a list item takes overlays through its cells and reveals cell by cell, as
/// a top-level one does: its rows are found by their origins, not by the block's source.
#[test]
fn rendered_view_nested_table_highlights_and_reveals_by_cell() {
    use edamame::document::{Buffer, Selection};
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let src = "- item\n\n  | a | b |\n  |---|---|\n  | 1 | 2 |\n";
    let draw = |state: &EditorState| {
        let mut terminal = Terminal::new(TestBackend::new(30, 8)).unwrap();
        let mut view_state = RenderedViewState::default();
        terminal
            .draw(|frame| {
                let view = RenderedView {
                    cursor_style: theme.status_mode_rendered,
                    visual_kind: None,
                    drop_indicator: None,
                    show_table_buttons: false,
                    state,
                    theme,
                };
                frame.render_stateful_widget(view, frame.area(), &mut view_state);
            })
            .unwrap();
        terminal.backend().buffer().clone()
    };
    let row_text = |buf: &ratatui::buffer::Buffer, y: u16| -> String {
        (0..30).map(|x| buf[(x, y)].symbol()).collect()
    };
    let data_row = |buf: &ratatui::buffer::Buffer| {
        (0..8)
            .find(|&y| row_text(buf, y).contains('2'))
            .expect("the data row is painted")
    };

    // `2` selected, the cursor on the item's text.
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    let two = src.rfind('2').unwrap();
    state.selection = Some(Selection {
        anchor: two,
        active: two + 1,
    });
    let buf = draw(&state);
    let y = data_row(&buf);
    let text = row_text(&buf, y);
    let highlighted: Vec<u16> = (0..30)
        .filter(|&x| buf[(x, y)].style().bg == theme.selection.bg)
        .collect();
    let two_x = text.chars().position(|c| c == '2').unwrap() as u16;
    assert_eq!(highlighted, [two_x], "only the selected `2`: {text:?}");

    // The cursor on `1`, revealed at once (no reveal delay running).
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    state.cursor.offset = src.rfind('1').unwrap();
    state.update_cursor_block();
    state.cursor_block_entered_at = None;
    let buf = draw(&state);
    let text = row_text(&buf, data_row(&buf));
    assert!(
        text.contains('│') && !text.contains('|'),
        "the cursor's row keeps its rendered pipes: {text:?}"
    );
}

#[test]
fn rendered_view_cell_scoped_reveal_keeps_neighbouring_pipes_rendered() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let src = "| aaa | bbb | ccc |\n|---|---|---|\n| 1 | 2 | 3 |\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    // Place the cursor on the first 'b' of the middle header cell. Chars
    // 0..19 in src form the header row: `| aaa | bbb | ccc |`, so char 8 is
    // the first 'b'. Leaving `cursor_block_entered_at` at its default (None)
    // causes `cursor_block_revealed()` to return true immediately — bypassing
    // the RAW_REVEAL_DELAY without any sleeping in the test.
    state.cursor.offset = 8;

    let backend = TestBackend::new(25, 5);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let symbol_at = |x: u16, y: u16| {
        buf.cell((x, y))
            .map_or(' ', |c| c.symbol().chars().next().unwrap_or(' '))
    };

    // Rendered layout, y=0 is the top border (┌──┬──┐), y=1 is the header row.
    // Pipes (│) sit at cols 0, 6, 12, 18 on every data/header row.
    for &x in &[0u16, 6, 12, 18] {
        assert_eq!(symbol_at(x, 1), '│', "expected │ at ({x}, 1)");
    }

    // Neighbouring cells keep their rendered content — NOT replaced by raw.
    for (x, ch) in [
        (2u16, 'a'),
        (3, 'a'),
        (4, 'a'),
        (14, 'c'),
        (15, 'c'),
        (16, 'c'),
    ] {
        assert_eq!(
            symbol_at(x, 1),
            ch,
            "neighbouring cell char at ({x}, 1) should still be rendered"
        );
    }

    // Active cell shows raw text "bbb" at cols 8-10 (between pipes at 6 and
    // 12).  Col 8 carries the block cursor, which recolors the cell but leaves
    // the 'b' visible; cols 9-10 still show raw 'b'.
    for x in 8u16..=10 {
        assert_eq!(
            symbol_at(x, 1),
            'b',
            "active cell should show raw 'b' at ({x}, 1)"
        );
    }

    // Cursor indicator: the block at (8, 1) carries the cursor bg, NOT the
    // other two 'b' cells.
    let cell_at = |x: u16, y: u16| buf.cell((x, y)).expect("cell in bounds");
    let cursor_bg = theme.status_mode_rendered.bg;
    assert!(cursor_bg.is_some(), "status_mode_rendered must carry a bg");
    assert_eq!(
        cell_at(8, 1).style().bg,
        cursor_bg,
        "cursor cell at (8, 1) should carry the cursor bg"
    );
    for x in [9u16, 10] {
        assert_ne!(
            cell_at(x, 1).style().bg,
            cursor_bg,
            "non-cursor cell at ({x}, 1) must not carry the cursor bg"
        );
    }
}

#[test]
fn table_view_paints_row_and_column_handles_when_enabled() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let src = "| aa | bb |\n|---|---|\n| 1  | 2  |\n| 3  | 4  |\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;

    let backend = TestBackend::new(30, 10);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                state: &state,
                theme,
                show_table_buttons: true,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let symbol_at = |x: u16, y: u16| {
        buf.cell((x, y))
            .map_or(' ', |c| c.symbol().chars().next().unwrap_or(' '))
    };

    // The snapshot-build pass should have produced exactly one snapshot with
    // the row-reorder gutter, the top-border row (column-reorder glyph site),
    // and the header row (column-resize glyph site) all populated.
    assert_eq!(view_state.table_snapshots.len(), 1);
    let snap = &view_state.table_snapshots[0];
    assert!(
        snap.row_handle_col.is_some(),
        "row handle col must be set when handles enabled"
    );
    assert!(
        snap.top_border_row.is_some(),
        "top border row must be set when handles enabled"
    );
    assert!(
        snap.header_row.is_some(),
        "header row must be set when handles enabled"
    );

    // Row-reorder: `⠿` on the left gutter for each data row.
    let handle_col = snap.row_handle_col.unwrap();
    let mut row_handle_count = 0;
    for y_range in &snap.row_ranges {
        if symbol_at(handle_col, y_range.start) == '⠿' {
            row_handle_count += 1;
        }
    }
    assert_eq!(
        row_handle_count,
        snap.row_ranges.len(),
        "every data row should show a ⠿ reorder glyph in the gutter"
    );

    // Column-reorder: `⠿` centered on each column's top border.
    let top_y = snap.top_border_row.unwrap();
    let col_reorder_count = snap
        .col_ranges
        .iter()
        .filter(|r| {
            let mid = r.start + (r.end - r.start) / 2;
            symbol_at(mid, top_y) == '⠿'
        })
        .count();
    assert_eq!(
        col_reorder_count,
        snap.col_ranges.len(),
        "every column should show a ⠿ reorder glyph on the top border"
    );

    // Column-resize: `⇔` on every header-row `│` — interior borders AND
    // the rightmost outer border (which resizes the last column).
    let header_y = snap.header_row.unwrap();
    let resize_count = snap
        .col_ranges
        .iter()
        .filter(|r| symbol_at(r.end, header_y) == '⇔')
        .count();
    assert_eq!(
        resize_count,
        snap.col_ranges.len(),
        "every border (interior + right outer) should show a ⇔ resize glyph"
    );
}

/// For a multi-row data row whose cell wrapped to two
/// rendered sub-lines, exactly ONE `⠿` row-handle glyph paints (on
/// the row's first sub-line).  Painting on every wrapped sub-line
/// reads as visual noise without making the row easier to grab.
#[test]
fn table_view_paints_one_row_handle_per_logical_row() {
    use edamame::config::Theme;
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme: &'static Theme = Box::leak(Box::new(Theme::default()));
    // First data row's second cell wraps under a narrow viewport.
    let src = "| Name | Notes |\n|---|---|\n| a | This is a very long note that wraps |\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    // Cursor in the data row so handles paint.
    let target = src.find("This").unwrap();
    state.cursor.offset = state.buffer.rope().byte_to_char(target);
    state.update_cursor_block();

    let backend = TestBackend::new(28, 12);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                state: &state,
                theme,
                show_table_buttons: true,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let symbol_at = |x: u16, y: u16| {
        buf.cell((x, y))
            .map_or(' ', |c| c.symbol().chars().next().unwrap_or(' '))
    };

    assert_eq!(view_state.table_snapshots.len(), 1);
    let snap = &view_state.table_snapshots[0];
    assert_eq!(snap.row_ranges.len(), 1, "one logical data row");
    let y_range = &snap.row_ranges[0];
    // Wrapped: the row spans more than one rendered y.
    assert!(
        y_range.end - y_range.start > 1,
        "test fixture must produce a wrapped row, got {y_range:?}",
    );
    let handle_col = snap.row_handle_col.expect("row handle col is set");
    let mut painted = 0usize;
    for y in y_range.start..y_range.end {
        if symbol_at(handle_col, y) == '⠿' {
            painted += 1;
        }
    }
    assert_eq!(
        painted, 1,
        "exactly one ⠿ row handle should paint per logical row, got {painted}",
    );
}

/// When the cursor enters a *wrapped* table cell, the
/// rendered table layout (including the row's wrap continuation
/// sub-lines) must stay intact.  Pre-fix behaviour collapsed the
/// row to a single line of raw markdown like
/// `| a | This is ... long note |`; the post-fix behaviour leaves
/// every rendered table line in place and paints just a cursor
/// indicator on the cursor's wrap sub-line.
#[test]
fn rendered_view_wrapped_cell_keeps_table_layout_when_cursor_inside() {
    use edamame::config::Theme;
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme: &'static Theme = Box::leak(Box::new(Theme::default()));
    let src = "| Name | Notes |\n|---|---|\n| a | This is a very long note that wraps |\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    // Cursor on a char inside the wrapped cell (the second cell of the
    // first data row).
    let target = src.find("very").unwrap();
    state.cursor.offset = state.buffer.rope().byte_to_char(target);
    state.update_cursor_block();
    // Force the reveal delay to be elapsed so we test the steady-state
    // behaviour, not the jitter-suppression path.
    state.cursor_block_entered_at =
        Some(std::time::Instant::now() - std::time::Duration::from_secs(1));

    let backend = TestBackend::new(28, 12);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                state: &state,
                theme,
                show_table_buttons: false,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let row_text = |y: u16| -> String {
        (0..28u16)
            .map(|x| {
                buf.cell((x, y))
                    .and_then(|c| c.symbol().chars().next())
                    .unwrap_or(' ')
            })
            .collect()
    };

    // Every visible row of the rendered table starts with a box-drawing
    // glyph (`┌`, `│`, `┝`, `└`).  If the row collapsed to a raw line
    // we'd see `|` (ASCII pipe) at column 0 — explicitly rule that out.
    for y in 0u16..8 {
        let row = row_text(y);
        if row.is_empty() {
            continue;
        }
        let first = row.chars().next().unwrap();
        if first == ' ' {
            continue; // blank rows past the table
        }
        assert!(
            !row.starts_with('|'),
            "row {y} should not collapse to raw markdown ({row:?})",
        );
    }

    // Confirm the table's box-drawing glyphs are still visible.
    let mut found_top = false;
    let mut found_bottom = false;
    for y in 0u16..12 {
        let row = row_text(y);
        if row.starts_with('┌') {
            found_top = true;
        }
        if row.starts_with('└') {
            found_bottom = true;
        }
    }
    assert!(found_top, "top border must still render");
    assert!(found_bottom, "bottom border must still render");
}

/// When a cell's raw markdown is too wide for the
/// rendered cell (e.g. `**_words_**` in a column whose auto-fit is
/// keyed off the rendered "words"), the cell horizontally scrolls to
/// keep the cursor's chunk visible.  The user must see *raw* chars
/// (`*`, `_`) where the cursor is — not the rendered bold-italic
/// glyphs of the formatted output.
#[test]
fn rendered_view_wrapped_cell_shows_raw_markdown_chunk() {
    use edamame::config::Theme;
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme: &'static Theme = Box::leak(Box::new(Theme::default()));
    // Cell content `**_words_**` renders as the 5-char word "words".
    // With a narrow viewport the column auto-fits to ~5 chars, so the
    // raw 11-char source can't sit on the rendered row.
    let src = "| a | b |\n|---|---|\n| x | **_words_** |\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    let target = src.find("words").unwrap();
    state.cursor.offset = state.buffer.rope().byte_to_char(target);
    state.update_cursor_block();
    state.cursor_block_entered_at =
        Some(std::time::Instant::now() - std::time::Duration::from_secs(1));

    let backend = TestBackend::new(20, 8);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                state: &state,
                theme,
                show_table_buttons: false,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let row_text = |y: u16| -> String {
        (0..20u16)
            .map(|x| {
                buf.cell((x, y))
                    .and_then(|c| c.symbol().chars().next())
                    .unwrap_or(' ')
            })
            .collect()
    };

    // Find the data row (starts with `│`, not `┌` / `┝` / `└`).
    let mut data_row_text = None;
    for y in 0u16..8 {
        let row = row_text(y);
        if row.starts_with('│') && !row.contains('━') {
            // The first `│`-prefixed row is the header; skip until we
            // see one whose content isn't `a` / `b`.
            if row.contains('x') || row.contains('*') || row.contains('w') {
                data_row_text = Some(row);
                break;
            }
        }
    }
    let data_row = data_row_text.expect("data row should be on screen");
    // The cursor's chunk should expose at least one `*` or `_` (raw
    // markdown markers), proving we didn't just paint rendered styled
    // text.
    assert!(
        data_row.contains('*') || data_row.contains('_'),
        "cursor's cell should show raw markdown chars; got {data_row:?}",
    );
}

/// When an in-line edit shrinks a wrapped cell's raw text so it wraps
/// to FEWER chunks than the row's rendered height (the parse is still
/// the pre-edit one during the deferral window), the leftover rendered
/// sub-lines of the cell must be wiped — not left showing a stale tail
/// of the de-rendered wrap.
#[test]
fn rendered_view_wrapped_cell_wipes_stale_tail_when_raw_shrinks() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let src = "| a | b |\n|---|---|\n| x | `breakable_code_name` words |\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    state.set_viewport_width(24);
    // Cursor inside the code span of the wrapped cell.
    let target = src.find("breakable").unwrap();
    state.cursor.offset = state.buffer.rope().byte_to_char(target);
    state.update_cursor_block();
    state.cursor_block_entered_at =
        Some(std::time::Instant::now() - std::time::Duration::from_secs(1));

    let backend = TestBackend::new(24, 10);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    let draw = |terminal: &mut Terminal<TestBackend>,
                state: &EditorState,
                view_state: &mut RenderedViewState| {
        terminal
            .draw(|frame| {
                let view = RenderedView {
                    cursor_style: theme.status_mode_rendered,
                    visual_kind: None,
                    drop_indicator: None,
                    state,
                    theme,
                    show_table_buttons: false,
                };
                frame.render_stateful_widget(view, frame.area(), &mut *view_state);
            })
            .unwrap();
    };
    let rows_text = |terminal: &Terminal<TestBackend>| -> Vec<String> {
        let buf = terminal.backend().buffer().clone();
        (0..10u16)
            .map(|y| {
                (0..24u16)
                    .map(|x| {
                        buf.cell((x, y))
                            .and_then(|c| c.symbol().chars().next())
                            .unwrap_or(' ')
                    })
                    .collect()
            })
            .collect()
    };

    // Sanity: the fixture wraps — the cell's second wrap chunk
    // ("code_name") is on screen before the edit.
    draw(&mut terminal, &state, &mut view_state);
    assert!(
        rows_text(&terminal).iter().any(|r| r.contains("code_name")),
        "fixture must wrap the code cell across sub-lines",
    );

    // Shrink the cell in the buffer WITHOUT reparsing — mirrors the
    // in-line-edit deferral window where the rendered row height is
    // still the pre-edit parse's.  `breakable_code_name` → `break`.
    let cut_start = src.find("able_code_name").unwrap();
    state
        .buffer
        .remove(cut_start, cut_start + "able_code_name".len());

    draw(&mut terminal, &state, &mut view_state);
    let rows = rows_text(&terminal);
    assert!(
        !rows.iter().any(|r| r.contains("code_name")),
        "stale wrap tail must be wiped from the de-rendered cell: {rows:#?}",
    );
}

/// Buttons paint only on the table the cursor is inside.
/// With the cursor parked in a paragraph above a table, the table's
/// buttons must be invisible; moving the cursor onto the table
/// reveals them.  Snapshots are still captured for hit-testing in
/// either case.
#[test]
fn table_view_handles_only_paint_when_cursor_in_table() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // A paragraph followed by a table.  Cursor starts at offset 0 (in
    // the paragraph), then later we move it into the table.
    let src = "intro line\n\n| aa | bb |\n|---|---|\n| 1  | 2  |\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;

    // Cursor in the paragraph: snapshot exists, but no glyphs.
    let backend = TestBackend::new(30, 10);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                state: &state,
                theme,
                show_table_buttons: true,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let symbol_at = |buf: &ratatui::buffer::Buffer, x: u16, y: u16| {
        buf.cell((x, y))
            .map_or(' ', |c| c.symbol().chars().next().unwrap_or(' '))
    };

    assert_eq!(view_state.table_snapshots.len(), 1);
    // No `⠿` (row/column reorder) glyphs anywhere on the screen yet.
    let mut painted = 0usize;
    for y in 0u16..10 {
        for x in 0u16..30 {
            if symbol_at(&buf, x, y) == '⠿' {
                painted += 1;
            }
        }
    }
    assert_eq!(
        painted, 0,
        "no handles should paint when cursor is outside the table",
    );

    // Move cursor into the table's first cell — find a byte offset
    // inside the first data row.  The table starts at byte 12 (`| aa`)
    // so byte 35 is comfortably inside `| 1  | 2  |`.
    let table_start = src.find("| aa").unwrap();
    let data_byte = src[table_start..]
        .find("| 1")
        .map(|off| table_start + off + 2) // jump past `| ` to land on '1'
        .unwrap();
    let target_char = state.buffer.rope().byte_to_char(data_byte);
    state.cursor.offset = target_char;
    state.update_cursor_block();

    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                state: &state,
                theme,
                show_table_buttons: true,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();
    let buf = terminal.backend().buffer().clone();

    let mut painted = 0usize;
    for y in 0u16..10 {
        for x in 0u16..30 {
            if symbol_at(&buf, x, y) == '⠿' {
                painted += 1;
            }
        }
    }
    assert!(
        painted > 0,
        "cursor inside the table should reveal `⠿` handle glyphs",
    );
}

#[test]
fn table_view_snapshots_empty_when_no_table() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let state = EditorState::new(Buffer::from_str("plain paragraph\n"), theme);

    let backend = TestBackend::new(30, 5);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                state: &state,
                theme,
                show_table_buttons: true,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    assert!(view_state.table_snapshots.is_empty());
}

/// Partial user widths (issue 2): columns marked `_` in the comment should
/// auto-size while numeric columns stay pinned.
#[test]
fn table_view_partial_user_widths_honours_auto_underscore_entries() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;

    let theme = Box::leak(Box::new(Theme::default()));
    // Natural widths: col 0 = 3 ("abc"), col 1 = 6 ("defghi").  With
    // `[5, _]` col 0 pins to 5 and col 1 stays at its natural 6.
    let src = "| abc | defghi |\n| --- | --- |\n| bar | baz |\n<!-- tui-columns: [5, _] -->\n";
    let state = EditorState::new(Buffer::from_str(src), theme);

    let header = state
        .parsed
        .lines
        .iter()
        .find(|l| l.spans.iter().any(|s| s.content.contains('│')))
        .expect("rendered a header row");
    let mut pipes = Vec::new();
    let mut col = 0usize;
    for span in &header.spans {
        for ch in span.content.chars() {
            if ch == '│' {
                pipes.push(col);
            }
            col += 1;
        }
    }
    assert_eq!(pipes.len(), 3);
    // Col 0 content area = pinned width (5) + 2 padding = 7.
    assert_eq!(pipes[1] - pipes[0] - 1, 7);
    // Col 1 content area = natural (6) + 2 padding = 8.
    assert_eq!(pipes[2] - pipes[1] - 1, 8);
}

#[test]
fn table_view_persists_user_widths_from_tui_columns_comment() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;

    let theme = Box::leak(Box::new(Theme::default()));
    let src = "| a | b |\n|---|---|\n| 1 | 2 |\n<!-- tui-columns: [10, 20] -->\n";
    let state = EditorState::new(Buffer::from_str(src), theme);

    // The parsed doc's first block should be a table whose rendering uses
    // the persisted widths — we can verify this by measuring the pipe
    // positions on the rendered header row.
    let first_line = state
        .parsed
        .lines
        .iter()
        .find(|l| l.spans.iter().any(|s| s.content.contains('│')))
        .expect("rendered a header row");
    let pipes: Vec<usize> = {
        let mut positions = Vec::new();
        let mut col = 0usize;
        for span in &first_line.spans {
            for ch in span.content.chars() {
                if ch == '│' {
                    positions.push(col);
                }
                col += 1;
            }
        }
        positions
    };
    assert_eq!(pipes.len(), 3, "header has two cells + three pipes");
    // Col 0 content width: widths[0]=10, plus a 1-char pad on each side = 12.
    let col0_width = pipes[1] - pipes[0] - 1;
    assert_eq!(col0_width, 12);
    // Col 1 content width: widths[1]=20, plus 1+1 pad = 22.
    let col1_width = pipes[2] - pipes[1] - 1;
    assert_eq!(col1_width, 22);
}

#[test]
fn status_bar_shows_cursor_position() {
    let theme = Box::leak(Box::new(Theme::default()));
    let backend = TestBackend::new(80, 1);
    let mut terminal = Terminal::new(backend).unwrap();
    terminal
        .draw(|frame| {
            let bar = StatusBar {
                state: StatusBarState {
                    mode: Mode::Rendered,
                    filename: "f.md",
                    line_count: 10,
                    scroll_total: 10,
                    viewport_rows: 1,
                    modified: false,
                    scroll: 0,
                    cursor_line: Some(5),
                    cursor_col: Some(12),
                    section_path: Vec::new(),
                    diff_progress: None,
                    vim_mode_label: None,
                },
                theme,
            };
            frame.render_widget(bar, frame.area());
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let out: String = (0..80u16)
        .map(|x| {
            buf.cell((x, 0))
                .map_or(' ', |c| c.symbol().chars().next().unwrap_or(' '))
        })
        .collect();
    assert!(out.contains("5:12"), "got: {out:?}");
}

// ── Row striping and drop indicators ────────────────────────────────────────

/// With `row_striping = true`, alternating data rows pick up
/// `Theme::table_row_even` / `Theme::table_row_odd` as their background.
/// Asserts that row 0's cell carries the `table_row_even` style and row
/// 1's carries `table_row_odd` (themed to a contrasting bg here so we
/// can verify the difference).
#[test]
fn table_row_striping_alternates_bg_per_data_row() {
    use edamame::config::Theme;
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};
    use ratatui::style::{Color, Style};

    // Build a custom theme whose row striping styles are visibly
    // different so the assertion has a clear signal to check.
    let theme_owned = Theme {
        table_row_even: Style::default().bg(Color::Indexed(238)),
        table_row_odd: Style::default().bg(Color::Indexed(237)),
        ..Theme::default()
    };
    let theme: &'static Theme = Box::leak(Box::new(theme_owned));

    let src = "| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    state.set_row_striping(true);

    let backend = TestBackend::new(20, 10);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                state: &state,
                theme,
                show_table_buttons: false,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let cell_at = |x: u16, y: u16| buf.cell((x, y)).cloned().unwrap_or_default();

    // Layout: y=0 top border, y=1 header, y=2 thick sep, y=3 data row 0,
    // y=4 thin sep, y=5 data row 1.  Pick a column inside the cell
    // content area (x=2 sits inside col 0's `1` / `3`).
    let row0_bg = cell_at(2, 3).bg;
    let row1_bg = cell_at(2, 5).bg;
    assert_eq!(
        row0_bg,
        Color::Indexed(238),
        "row 0 even-stripe bg mismatch"
    );
    assert_eq!(row1_bg, Color::Indexed(237), "row 1 odd-stripe bg mismatch");
}

/// With `row_striping` on, the inter-row separator between two data
/// rows is rendered as a *blank* line (NBSP-padded) instead of the
/// `├─┼─┤` rule.  The blank line carries the background of the row
/// immediately above it so each striped row reads as a 2-row band of
/// its own color, with no horizontal rule breaking up the rhythm.
#[test]
fn table_row_striping_replaces_thin_rule_with_blank_separator() {
    use edamame::config::Theme;
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};
    use ratatui::style::{Color, Style};

    let theme_owned = Theme {
        table_row_even: Style::default().bg(Color::Indexed(238)),
        table_row_odd: Style::default().bg(Color::Indexed(237)),
        ..Theme::default()
    };
    let theme: &'static Theme = Box::leak(Box::new(theme_owned));

    let src = "| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    state.set_row_striping(true);

    let backend = TestBackend::new(20, 10);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                state: &state,
                theme,
                show_table_buttons: false,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let symbol_at = |x: u16, y: u16| {
        buf.cell((x, y))
            .map_or(' ', |c| c.symbol().chars().next().unwrap_or(' '))
    };
    let bg_at = |x: u16, y: u16| buf.cell((x, y)).map(|c| c.bg).unwrap_or(Color::Reset);

    // Layout when stripe is on: y=0 top, y=1 header, y=2 thick,
    // y=3 row 0, y=4 BLANK separator (bg matches row 0), y=5 row 1,
    // y=6 bottom.
    // The "thin rule" position (y=4) must NOT carry `├` / `┼` /
    // `─` glyphs — only `│` and NBSP (which renders visually as a
    // space).
    for x in 0u16..16 {
        let g = symbol_at(x, 4);
        assert!(
            g != '├' && g != '┼' && g != '┤' && g != '─',
            "stripe-on separator at ({x}, 4) should be blank, got {g:?}",
        );
    }

    // The blank separator below row 0 should pick up row 0's bg
    // (Indexed(238)) on the cell-padding NBSPs.
    assert_eq!(
        bg_at(2, 4),
        Color::Indexed(238),
        "blank separator below row 0 should carry row 0's bg",
    );
}

/// With striping disabled (the default), the renderer must NOT apply
/// either striping style — every data row falls through to
/// `Theme::table_cell` and the cell background stays at terminal
/// default.
#[test]
fn table_row_striping_off_leaves_default_bg() {
    use edamame::config::Theme;
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};
    use ratatui::style::{Color, Style};

    let theme_owned = Theme {
        table_row_even: Style::default().bg(Color::Indexed(238)),
        table_row_odd: Style::default().bg(Color::Indexed(237)),
        ..Theme::default()
    };
    let theme: &'static Theme = Box::leak(Box::new(theme_owned));

    let src = "| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    // Note: row_striping is false (default).

    let backend = TestBackend::new(20, 10);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                state: &state,
                theme,
                show_table_buttons: false,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let bg_at = |x: u16, y: u16| buf.cell((x, y)).map(|c| c.bg).unwrap_or(Color::Reset);
    // Both data rows should have the same (default) background — neither
    // stripe color should leak through.
    assert_ne!(bg_at(2, 3), Color::Indexed(238));
    assert_ne!(bg_at(2, 3), Color::Indexed(237));
    assert_eq!(bg_at(2, 3), bg_at(2, 5));
}

/// During a row-handle drag, `paint_drop_indicator` overlays a heavy
/// horizontal rule on the destination separator.  The painter renders
/// `DROP_ROW_GLYPH` ('━') styled with `Theme::table_drop_indicator`
/// across the table's full width on the separator y-coordinate.
#[test]
fn table_view_paints_drop_indicator_on_row_drag() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::table_view::DropIndicator;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let src = "| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;

    // Drag from data row index 2 (first data row) onto data row 3
    // (second data row).  The painter should highlight the separator
    // *below* the second data row → drop_below.
    let indicator = DropIndicator::Row {
        table_byte_start: 0,
        src_row_idx: 2,
        hover_row_idx: 3,
    };

    let backend = TestBackend::new(30, 10);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: Some(indicator),
                state: &state,
                theme,
                show_table_buttons: false,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let symbol_at = |x: u16, y: u16| {
        buf.cell((x, y))
            .map_or(' ', |c| c.symbol().chars().next().unwrap_or(' '))
    };

    assert_eq!(view_state.table_snapshots.len(), 1);
    let snap = &view_state.table_snapshots[0];
    assert_eq!(snap.row_ranges.len(), 2);
    // Drop is below hover row (data idx = 1 → second data row).  Its
    // separator y is row_ranges[1].end.
    let sep_y = snap.row_ranges[1].end;
    let first_x = snap.col_ranges.first().unwrap().start;
    let last_x = snap.col_ranges.last().unwrap().end;
    let mut found = 0usize;
    for x in first_x.saturating_sub(1)..=last_x {
        if symbol_at(x, sep_y) == '━' {
            found += 1;
        }
    }
    assert!(
        found > 0,
        "drop indicator should paint ━ on separator y={sep_y}, got 0 matches"
    );
}

#[test]
fn rendered_view_code_block_only_opening_fence_de_renders() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // Fenced code block with a language tag.  The renderer produces:
    //   row 0: " rust " language label
    //   row 1: " fn main() {} " padded body line
    // The closing fence has no rendered row of its own.
    let src = "```rust\nfn main() {}\n```\n";

    let row_text = |term: &Terminal<TestBackend>, y: u16, w: u16| -> String {
        let buf = term.backend().buffer().clone();
        (0..w)
            .map(|x| {
                buf.cell((x, y))
                    .map_or(' ', |c| c.symbol().chars().next().unwrap_or(' '))
            })
            .collect()
    };

    let render = |state: &EditorState| -> Terminal<TestBackend> {
        let backend = TestBackend::new(30, 5);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut view_state = RenderedViewState::default();
        terminal
            .draw(|frame| {
                let view = RenderedView {
                    cursor_style: theme.status_mode_rendered,
                    visual_kind: None,
                    drop_indicator: None,
                    show_table_buttons: false,
                    state,
                    theme,
                };
                frame.render_stateful_widget(view, frame.area(), &mut view_state);
            })
            .unwrap();
        terminal
    };

    // Cursor on the opening fence (raw line 0 — the ```rust line).
    {
        let mut state = EditorState::new(Buffer::from_str(src), theme);
        state.mode = Mode::Rendered;
        state.cursor.offset = 0;
        let term = render(&state);
        // Row 0 must show the raw fence, not the styled "rust" label.  The
        // block cursor recolors the first backtick cell but leaves it visible.
        assert!(
            row_text(&term, 0, 30).contains("```rust"),
            "row 0 should show raw fence: {:?}",
            row_text(&term, 0, 30)
        );
        // Row 1 must still show the body line rendered.
        assert!(
            row_text(&term, 1, 30).contains("fn main() {}"),
            "row 1 should show rendered body: {:?}",
            row_text(&term, 1, 30)
        );
    }

    // Cursor on the body line — must NOT de-render to raw text.  The
    // rendered body row already shows the same characters, so we instead
    // assert that the row 0 language label is the styled " rust " (no
    // backticks bleed in from a misplaced de-render).
    {
        let mut state = EditorState::new(Buffer::from_str(src), theme);
        state.mode = Mode::Rendered;
        state.cursor.offset = src.find("fn main").unwrap();
        let term = render(&state);
        assert!(
            !row_text(&term, 0, 30).contains("```"),
            "row 0 must remain the styled language label, got: {:?}",
            row_text(&term, 0, 30)
        );
        assert!(
            row_text(&term, 1, 30).contains("fn main() {}"),
            "row 1 should show rendered body: {:?}",
            row_text(&term, 1, 30)
        );
    }

    // Cursor on the closing fence — must NOT replace the body row with ```.
    {
        let mut state = EditorState::new(Buffer::from_str(src), theme);
        state.mode = Mode::Rendered;
        state.cursor.offset = src.rfind("```").unwrap();
        let term = render(&state);
        assert!(
            row_text(&term, 1, 30).contains("fn main() {}"),
            "body row must stay rendered when cursor is on closing fence: {:?}",
            row_text(&term, 1, 30)
        );
    }
}

/// Regression: a fenced block's byte range ends with the trailing newline,
/// so `split('\n')` appends a phantom empty entry and the *real* closing
/// fence is not the last element.  Testing the fence against that length
/// classified the closing fence as a body row and mapped its columns
/// instead of washing the whole rendered row, leaving a selected block
/// with a three-cell smudge at the bottom instead of a covered row.
#[test]
fn rendered_view_selection_covers_the_whole_closing_fence_row() {
    use edamame::document::{Buffer, Selection};
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // Rendered rows: 0 = " rust " label, 1 = " let x = 1;",
    // 2 = the closing-fence placeholder row.
    let src = "```rust\nlet x = 1;\n```\n";
    let width: u16 = 25;
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    state.set_viewport_width(width as usize);
    state.selection = Some(Selection {
        anchor: 0,
        active: src.chars().count(),
    });
    state.cursor.offset = src.chars().count();

    let backend = TestBackend::new(width, 6);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let selected = |x: u16, y: u16| {
        buf.cell((x, y))
            .map(|c| c.style().bg == theme.selection.bg)
            .unwrap_or(false)
    };
    let washed = (0..width).filter(|&x| selected(x, 2)).count();
    assert!(
        washed > 3,
        "closing fence row must be washed whole, only {washed} cells were",
    );
}

/// Regression for issue #28: the renderer paints every code body row
/// behind one leading pad cell, so the cursor indicator must be shifted
/// right by it — otherwise the block cursor sits on the cell *before* the
/// character it is logically on, for every character of every code block.
#[test]
fn rendered_view_code_block_cursor_indicator_sits_on_its_char() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // Rendered rows: 0 = " rust " label, 1 = " let x = 1;" (padded body).
    let src = "```rust\nlet x = 1;\n```\n";
    let width: u16 = 30;

    // Every raw column of the body line, including col 0 and end-of-line:
    // a single sample at col 0 would pass on an off-by-one that clamped.
    for raw_col in 0..="let x = 1;".len() {
        let mut state = EditorState::new(Buffer::from_str(src), theme);
        state.mode = Mode::Rendered;
        state.cursor.offset = src.find("let").unwrap() + raw_col;
        state.set_viewport_width(width as usize);

        let backend = TestBackend::new(width, 8);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut view_state = RenderedViewState::default();
        terminal
            .draw(|frame| {
                let view = RenderedView {
                    cursor_style: theme.status_mode_rendered,
                    visual_kind: None,
                    drop_indicator: None,
                    show_table_buttons: false,
                    state: &state,
                    theme,
                };
                frame.render_stateful_widget(view, frame.area(), &mut view_state);
            })
            .unwrap();

        let buf = terminal.backend().buffer().clone();
        let cursor_x = (0..width).find(|&x| {
            buf.cell((x, 1))
                .map(|c| {
                    c.style().bg == theme.status_mode_rendered.bg
                        && c.style().fg == theme.status_mode_rendered.fg
                })
                .unwrap_or(false)
        });
        assert_eq!(
            cursor_x,
            Some(raw_col as u16 + 1),
            "raw col {raw_col} must paint one cell right of itself (the pad)",
        );
        // The symbol under the cursor is the real pin: it is independent of
        // how the theme colours the block.
        let expected = "let x = 1;".chars().nth(raw_col).unwrap_or(' ');
        assert_eq!(
            buf.cell((raw_col as u16 + 1, 1))
                .map(|c| c.symbol().to_string()),
            Some(expected.to_string()),
            "cursor cell must carry the char at raw col {raw_col}",
        );
    }
}

/// A code block nested in a list item belongs to the `List` block, which reveals its cursor
/// line as raw source.  A code body line must not: the row keeps its highlighting, background
/// and layout, and only gains the cursor indicator — on the char it is on, past the pad cell
/// and the item indent pulldown-cmark stripped.
#[test]
fn rendered_view_code_nested_in_list_item_does_not_reveal_its_body() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // Rendered rows: 0 = "8. Tag it.", 1 = blank, 2 = "    bash " label, 3 = "    gh run watch":
    // the block sits under the item's text, 3 cells in.
    let src = "8. Tag it.\n\n    ```bash\n    gh run watch\n    ```\n";
    let width: u16 = 30;
    let draw = |cursor: usize| {
        let mut state = EditorState::new(Buffer::from_str(src), theme);
        state.mode = Mode::Rendered;
        state.cursor.offset = cursor;
        state.set_viewport_width(width as usize);
        state.update_cursor_block();
        state.cursor_block_entered_at = None; // reveal fires immediately
        let mut terminal = Terminal::new(TestBackend::new(width, 8)).unwrap();
        let mut view_state = RenderedViewState::default();
        terminal
            .draw(|frame| {
                let view = RenderedView {
                    cursor_style: theme.status_mode_rendered,
                    visual_kind: None,
                    drop_indicator: None,
                    show_table_buttons: false,
                    state: &state,
                    theme,
                };
                frame.render_stateful_widget(view, frame.area(), &mut view_state);
            })
            .unwrap();
        terminal.backend().buffer().clone()
    };

    let resting = draw(0);
    // The `r` of `run`: raw col 7, rendered col 3 + (7 - 4) + 1 = 7.
    let active = draw(src.find("run").unwrap());
    let cursor_x = 7u16;
    for x in 0..width {
        let (r, a) = (resting.cell((x, 3)).unwrap(), active.cell((x, 3)).unwrap());
        assert_eq!(a.symbol(), r.symbol(), "row text changed at col {x}");
        if x != cursor_x {
            assert_eq!(a.style(), r.style(), "row styling changed at col {x}");
        }
    }
    assert_eq!(active.cell((cursor_x, 3)).unwrap().symbol(), "r");
    assert_eq!(
        active.cell((cursor_x, 3)).unwrap().style().bg,
        theme.status_mode_rendered.bg,
        "cursor indicator must sit on the `r`",
    );
}

/// The selection overlay on a code body row nested in a list item maps through the pad cell
/// and the stripped item indent, and finds the row's source line below the item's blank line
/// (a 1:1 lookup, when that blank rendered no row, washed the line above).
#[test]
fn rendered_view_selection_on_code_nested_in_list_item_covers_its_chars() {
    use edamame::document::{Buffer, Selection};
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // Rendered rows: 0 = "8. Tag it.", 1 = blank, 2 = "    bash " label, 3 = "    gh run watch":
    // the block sits under the item's text, 3 cells in.
    let src = "8. Tag it.\n\n    ```bash\n    gh run watch\n    ```\n";
    let width: u16 = 30;
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    state.set_viewport_width(width as usize);
    let run = src.find("run").unwrap();
    state.selection = Some(Selection {
        anchor: run,
        active: run + 3,
    });
    state.cursor.offset = 0;

    let mut terminal = Terminal::new(TestBackend::new(width, 6)).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let washed = |y: u16| -> Vec<u16> {
        (0..width)
            .filter(|&x| buf.cell((x, y)).unwrap().style().bg == theme.selection.bg)
            .collect()
    };
    assert_eq!(
        washed(3),
        [7, 8, 9],
        "`run` sits at cols 7..10 of the body row"
    );
    assert!(washed(2).is_empty(), "the label row must stay unselected");
}

/// The selection overlay on the nested item a last list item opens on its marker line: it
/// renders below the line's own row, which the trailing blank the block's range absorbs used to
/// claim, so nothing was washed.
#[test]
fn rendered_view_selection_on_a_last_items_nested_item_covers_it() {
    use edamame::document::{Buffer, Selection};
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // Rendered rows: 0 = "• a", 1 = "•", 2 = the nested "• q".
    let src = "- a\n- - q\n\nafter\n";
    let width: u16 = 30;
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    state.set_viewport_width(width as usize);
    let q = src.find('q').unwrap();
    state.selection = Some(Selection {
        anchor: q,
        active: q + 1,
    });
    state.cursor.offset = src.find("after").unwrap();
    state.update_cursor_block();

    let mut terminal = Terminal::new(TestBackend::new(width, 6)).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let washed: Vec<&str> = (0..width)
        .map(|x| buf.cell((x, 2)).unwrap())
        .filter(|c| c.style().bg == theme.selection.bg)
        .map(|c| c.symbol())
        .collect();
    assert_eq!(washed, ["q"], "the nested item's `q` must be washed");
}

/// A nested item's continuation line renders at the renderer's child indent, deeper than the
/// source's; mapping it 1:1 washed the cells two to the left of the match.  The third level's
/// six-space indent would parse as an indented code block on its own, so the map must not.
/// With reflow off, so each continuation keeps a row of its own.
#[test]
fn rendered_view_selection_on_a_nested_items_continuation_covers_it() {
    use edamame::document::{Buffer, Selection};
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // Rendered rows: 0 = "• a", 1 = "    • b", 2 = "      soft *word*", 3 = "        • c",
    // 4 = "          deep word".
    let src = "- a\n  - b\n    soft *word*\n    - c\n      deep word\n\nafter\n";
    let width: u16 = 30;
    for (needle, row, expected) in [("word*", 2u16, "word"), ("word\n", 4, "word")] {
        let mut state = EditorState::new(Buffer::from_str(src), theme);
        state.mode = Mode::Rendered;
        state.set_reflow(false);
        state.set_viewport_width(width as usize);
        let start = src.find(needle).unwrap();
        state.selection = Some(Selection {
            anchor: start,
            active: start + 4,
        });
        state.cursor.offset = src.find("after").unwrap();
        state.update_cursor_block();

        let mut terminal = Terminal::new(TestBackend::new(width, 8)).unwrap();
        let mut view_state = RenderedViewState::default();
        terminal
            .draw(|frame| {
                let view = RenderedView {
                    cursor_style: theme.status_mode_rendered,
                    visual_kind: None,
                    drop_indicator: None,
                    show_table_buttons: false,
                    state: &state,
                    theme,
                };
                frame.render_stateful_widget(view, frame.area(), &mut view_state);
            })
            .unwrap();

        let buf = terminal.backend().buffer().clone();
        let washed: String = (0..width)
            .map(|x| buf.cell((x, row)).unwrap())
            .filter(|c| c.style().bg == theme.selection.bg)
            .map(|c| c.symbol())
            .collect();
        assert_eq!(washed, expected, "row {row}");
    }
}

/// Companion to the fenced case: pulldown-cmark strips an indented block's
/// leading indent, so the rendered column is `raw - strip + pad`.
#[test]
fn rendered_view_indented_code_block_cursor_indicator_sits_on_its_char() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // An indented code block: 4 spaces stripped, one pad cell added, so the
    // `=` at raw col 10 renders at col 10 - 4 + 1 = 7.
    let src = "Intro.\n\n    let x = 1;\n";
    let width: u16 = 30;

    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    state.cursor.offset = src.find('=').unwrap();
    state.set_viewport_width(width as usize);

    let backend = TestBackend::new(width, 8);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let code_row = (0..8u16)
        .find(|&y| (0..width).any(|x| buf.cell((x, y)).map(|c| c.symbol() == "=").unwrap_or(false)))
        .expect("indented code row must render");
    let cursor_x = (0..width).find(|&x| {
        buf.cell((x, code_row))
            .map(|c| {
                c.style().bg == theme.status_mode_rendered.bg
                    && c.style().fg == theme.status_mode_rendered.fg
            })
            .unwrap_or(false)
    });
    assert_eq!(cursor_x, Some(7), "stripped indent must be subtracted back");
    assert_eq!(
        buf.cell((7, code_row)).map(|c| c.symbol().to_string()),
        Some("=".to_string()),
    );
}

#[test]
fn rendered_view_code_block_blank_body_line_aligns_cursor_indicator() {
    // Regression: blank lines inside code blocks DO render (as NBSP-padded
    // rows), so the raw-to-rendered mapping must NOT compress them out.
    // Previously the list-style "preceding non-blank" compression made the
    // cursor indicator paint one row higher than the body line the cursor
    // is actually editing for every blank line above it.
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // ```rust
    // A
    //          ← blank body line
    // B
    // ```
    let src = "```rust\nA\n\nB\n```\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    // Cursor on the 'B' body line — the line BELOW the blank.
    state.cursor.offset = src.find('B').unwrap();

    // Match viewport_width to area width so the NBSP-padded blank body
    // line fits in a single visual row (without this the default 80-col
    // padding wraps to 3 rows on a 30-col area and hides the bug).
    let width: u16 = 30;
    state.set_viewport_width(width as usize);

    let backend = TestBackend::new(width, 8);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    // Layout: row 0 = " rust " label, row 1 = " A", row 2 = NBSP padding,
    // row 3 = " B".  The block cursor (recolored cell, char left visible) must
    // be on row 3, not row 2.
    let row_has_cursor = |y: u16| {
        (0..width).any(|x| {
            buf.cell((x, y))
                .map(|c| {
                    c.style().bg == theme.status_mode_rendered.bg
                        && c.style().fg == theme.status_mode_rendered.fg
                })
                .unwrap_or(false)
        })
    };
    assert!(
        row_has_cursor(3),
        "cursor indicator must paint on row 3 (the 'B' line) not above it"
    );
    assert!(
        !row_has_cursor(2),
        "cursor indicator must not paint on row 2 (the blank padding line)"
    );
}

#[test]
fn rendered_view_bare_code_fence_de_renders_opening_fence() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // Code block with no language tag — the renderer reserves a padded
    // opening-fence row (matching the closing-fence row) that the cursor
    // can land on and reveal the raw ``` glyphs.
    let src = "```\nfn main() {}\n```\n";

    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    // Place cursor on the opening fence.
    state.cursor.offset = 0;

    let backend = TestBackend::new(30, 5);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let row_text = |y: u16| -> String {
        (0..30u16)
            .map(|x| {
                buf.cell((x, y))
                    .map_or(' ', |c| c.symbol().chars().next().unwrap_or(' '))
            })
            .collect()
    };
    // The cursor sits on raw line 0 (the opening fence).  Row 0 must show
    // the raw ``` glyphs and the body line stays on row 1.  The block cursor
    // recolors the first backtick cell but leaves it visible.
    assert!(
        row_text(0).contains("```"),
        "opening fence must de-render to show ``` glyphs, got: {:?}",
        row_text(0)
    );
    assert!(
        row_text(1).contains("fn main() {}"),
        "body line must follow the opening-fence row, got: {:?}",
        row_text(1)
    );
}

#[test]
fn mermaid_block_reveals_full_raw_source_on_cursor_entry() {
    // When the cursor enters a `\`\`\`mermaid` fenced block, the entire
    // image-reservation region must paint the mermaid source styled as
    // a regular fenced code block (matching how the block would render
    // when the `diagrams` setting is disabled).  Regression guard for
    // the "only one line de-renders" bug.
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // Small image_max_height so the reserved region stays bounded.  The
    // mermaid source is 5 raw lines (fence, 3 content, fence), which
    // fits in 6 rows.
    let src = "```mermaid\nflowchart TD\nA-->B\nB-->C\n```\n";
    let mut state = EditorState::new_with_config(Buffer::from_str(src), theme, true, true, 6);
    state.mode = Mode::Rendered;
    // Cursor on the first content line "flowchart TD".
    let byte = src.find("flowchart").unwrap();
    state.cursor.offset = state.buffer.rope().byte_to_char(byte);
    state.update_cursor_block();
    // Skip the reveal delay so raw paint runs this frame.
    state.cursor_block_entered_at = None;

    let backend = TestBackend::new(20, 7);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let row_text = |y: u16| -> String {
        (0..20u16)
            .map(|x| {
                buf.cell((x, y))
                    .map_or(' ', |c| c.symbol().chars().next().unwrap_or(' '))
            })
            .collect()
    };
    // The cursor is on the first body line, so the block reveals as a
    // fenced code block would: row 0 is the ` mermaid ` language label,
    // body rows show their raw source, and the closing fence row is the
    // padded placeholder (the raw `` ``` `` only appears when the cursor
    // sits on that row).
    assert!(
        row_text(0).trim_start().starts_with("mermaid"),
        "row 0 must show the ` mermaid ` language label, got: {:?}",
        row_text(0)
    );
    // Row 1 carries the cursor: the block recolors the leading 'f' cell of
    // "flowchart TD" but leaves it visible.
    assert!(
        row_text(1).starts_with("flowchart TD"),
        "row 1 must show first body line, got: {:?}",
        row_text(1)
    );
    assert!(
        row_text(2).starts_with("A-->B"),
        "row 2 must show second body line, got: {:?}",
        row_text(2)
    );
    assert!(
        row_text(3).starts_with("B-->C"),
        "row 3 must show third body line, got: {:?}",
        row_text(3)
    );
    // The placeholder text the renderer would otherwise emit on row 0
    // must not be visible anywhere in the reserved region.
    for y in 0..5u16 {
        assert!(
            !row_text(y).contains("[Image"),
            "row {y} must not show image placeholder, got: {:?}",
            row_text(y)
        );
    }
}

/// Before the reveal shrinks the reservation to the source (the frame
/// `sync_image_reveal` hasn't run for yet), the image's rows outnumber the
/// source lines.  The rows past the source pad the block: they must not
/// repeat its last line, even with the cursor on it.
#[test]
fn mermaid_reveal_pads_rows_past_the_source() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // Four source lines against eight reserved rows.
    let src = "```mermaid\nflowchart TD\nA-->B\n```\n";
    let mut state = EditorState::new_with_config(Buffer::from_str(src), theme, true, true, 8);
    state.mode = Mode::Rendered;
    // Cursor on the closing fence, so its row shows the raw fence.
    let byte = src.rfind("```").unwrap();
    state.cursor.offset = state.buffer.rope().byte_to_char(byte);
    state.update_cursor_block();
    state.cursor_block_entered_at = None;

    let backend = TestBackend::new(20, 9);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let row_text = |y: u16| -> String {
        (0..20u16)
            .map(|x| buf.cell((x, y)).unwrap().symbol())
            .collect::<String>()
            .trim_end()
            .to_string()
    };
    assert_eq!(
        row_text(3),
        "```",
        "the closing fence shows raw under the cursor"
    );
    for y in 4..8u16 {
        assert_eq!(row_text(y), "", "row {y} past the source must be padding");
    }
}

/// Any valid closing fence reveals as the padded placeholder, not as a body row showing the
/// fence: a tilde fence, a longer backtick fence, and a closing run longer than the opener.  An
/// unclosed fence's last line is a body row.  The closing fence was once recognized only as
/// exactly `` ``` `` (issue #68).
#[test]
fn mermaid_reveal_hides_every_kind_of_closing_fence() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    for (src, closing) in [
        ("~~~mermaid\nflowchart TD\nA-->B\n~~~\n", Some("~~~")),
        ("````mermaid\nflowchart TD\nA-->B\n````\n", Some("````")),
        ("```mermaid\nflowchart TD\nA-->B\n`````\n", Some("`````")),
        ("```mermaid\nflowchart TD\nA-->B\n```\n", Some("```")),
        ("```mermaid\nflowchart TD\nA-->B\n", None),
    ] {
        let mut state = EditorState::new_with_config(Buffer::from_str(src), theme, true, true, 8);
        state.mode = Mode::Rendered;
        let byte = src.find("A-->B").unwrap() + 1;
        state.cursor.offset = state.buffer.rope().byte_to_char(byte);
        state.update_cursor_block();
        state.cursor_block_entered_at = None;

        let mut terminal = Terminal::new(TestBackend::new(20, 9)).unwrap();
        let mut view_state = RenderedViewState::default();
        terminal
            .draw(|frame| {
                let view = RenderedView {
                    cursor_style: theme.status_mode_rendered,
                    visual_kind: None,
                    drop_indicator: None,
                    show_table_buttons: false,
                    state: &state,
                    theme,
                };
                frame.render_stateful_widget(view, frame.area(), &mut view_state);
            })
            .unwrap();
        let buf = terminal.backend().buffer().clone();
        let row_text = |y: u16| -> String {
            (0..20u16)
                .map(|x| buf.cell((x, y)).unwrap().symbol())
                .collect::<String>()
                .trim_end()
                .replace('\u{00A0}', " ")
                .trim_end()
                .to_string()
        };
        assert_eq!(row_text(2), "A-->B", "in {src:?}");
        match closing {
            Some(fence) => {
                assert_eq!(
                    row_text(3),
                    "",
                    "{fence} must be the placeholder in {src:?}"
                );
                // With the cursor on it, the fence shows raw.
                let at = src.rfind(fence).unwrap();
                state.cursor.offset = state.buffer.rope().byte_to_char(at);
                state.update_cursor_block();
                state.cursor_block_entered_at = None;
                terminal
                    .draw(|frame| {
                        let view = RenderedView {
                            cursor_style: theme.status_mode_rendered,
                            visual_kind: None,
                            drop_indicator: None,
                            show_table_buttons: false,
                            state: &state,
                            theme,
                        };
                        frame.render_stateful_widget(view, frame.area(), &mut view_state);
                    })
                    .unwrap();
                let buf = terminal.backend().buffer().clone();
                let row3: String = (0..20u16)
                    .map(|x| buf.cell((x, 3)).unwrap().symbol())
                    .collect();
                assert_eq!(
                    row3.trim_end(),
                    fence,
                    "{fence} under the cursor in {src:?}"
                );
            }
            None => assert_eq!(row_text(1), "flowchart TD", "in {src:?}"),
        }
    }
}

/// A yank flash over a revealed diagram's source line paints that line's
/// raw text, and nothing on the rows around it.  The post-pass overlay
/// skips image rows, so the reveal paints the flash itself, as it does a
/// selection; it used to land on the placeholder `Line`'s cells, whose width
/// was 0 on every row but the label's.
#[test]
fn yank_flash_paints_a_revealed_diagrams_source_line() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::terminal::Capabilities;
    use edamame::ui::bottom_region::{HintContent, HintSet};
    use edamame::ui::{EditorView, EditorViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let src = "```mermaid\nflowchart TD\nA-->B\n```\n";
    for (line, row) in [("flowchart TD", 1u16), ("```mermaid", 0)] {
        let mut state = EditorState::new_with_config(Buffer::from_str(src), theme, true, true, 8);
        state.mode = Mode::Rendered;
        // Cursor at the end of `A-->B`, clear of the flashed line.
        let cursor = src.find("A-->B").unwrap() + "A-->B".len();
        state.cursor.offset = state.buffer.rope().byte_to_char(cursor);
        state.update_cursor_block();
        state.cursor_block_entered_at = None;
        let start = state.buffer.rope().byte_to_char(src.find(line).unwrap());
        state.flash_yank(start, start + line.chars().count());

        let backend = TestBackend::new(30, 9);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut view_state = EditorViewState::new();
        let caps = Capabilities::default();
        terminal
            .draw(|frame| {
                let view = EditorView {
                    state: &mut state,
                    theme,
                    filename: "test.md",
                    show_table_buttons: false,
                    table_drop_indicator: None,
                    capabilities: &caps,
                    show_line_numbers: false,
                    is_scrolling: false,
                    hint: HintContent::Chords(HintSet::default()),
                    vim_mode_label: None,
                    visual_kind: None,
                    editor_cursor_style: theme.status_mode_rendered,
                    max_width_enabled: false,
                    max_width_cols: 0,
                    scrollbar_active: false,
                };
                frame.render_stateful_widget(view, frame.area(), &mut view_state);
            })
            .unwrap();

        let buf = terminal.backend().buffer().clone();
        let flashed = |y: u16| -> Vec<u16> {
            (0..30u16)
                .filter(|&x| buf.cell((x, y)).unwrap().style().bg == theme.selection.bg)
                .collect()
        };
        if row == 1 {
            // A body row shows its raw text, and the flash covers all of it.
            let n = line.chars().count() as u16;
            assert_eq!(flashed(1), (0..n).collect::<Vec<_>>(), "{line:?}");
        } else {
            // The opening fence shows its ` mermaid ` label without the
            // cursor: there is no raw text to flash.
            assert_eq!(flashed(0), Vec::<u16>::new(), "{line:?}");
        }
        for y in (0..8u16).filter(|&y| y != row) {
            assert_eq!(flashed(y), Vec::<u16>::new(), "{line:?}: row {y}");
        }
    }
}

/// A yank flash over a revealed block paints the raw text each row shows, at
/// its raw columns, and rows below a stacked reveal stay aligned.  The flash
/// used to be a post-pass over the rendered layout, so it landed at rendered
/// columns over raw text, washed a big H1's blanked rows whole, and was a row
/// off below a revealed reflowed paragraph.
#[test]
fn yank_flash_paints_revealed_rows_at_their_raw_columns() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::terminal::Capabilities;
    use edamame::ui::bottom_region::{HintContent, HintSet};
    use edamame::ui::{EditorView, EditorViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // (source, cursor at, flashed text, reflow, big H1, highlighted cells per row 0..6)
    #[allow(clippy::type_complexity)]
    let cases: &[(&str, &str, &str, bool, bool, [std::ops::Range<u16>; 6])] = &[
        // The cursor's row shows `a **bold** word`: `word` is at raw col 11.
        (
            "a **bold** word\n\nnext\n",
            "a **",
            "word",
            false,
            false,
            [11..15, 0..0, 0..0, 0..0, 0..0, 0..0],
        ),
        (
            "- a **b** word\n- c\n",
            "a **",
            "word",
            false,
            false,
            [10..14, 0..0, 0..0, 0..0, 0..0, 0..0],
        ),
        (
            "Title *x* end\n===\n\nnext\n",
            "Title",
            "end",
            false,
            false,
            [10..13, 0..0, 0..0, 0..0, 0..0, 0..0],
        ),
        // The underline shows raw, so only its three chars light.
        (
            "Title *x* end\n---\n\nnext\n",
            "Title",
            "---",
            false,
            false,
            [0..0, 0..3, 0..0, 0..0, 0..0, 0..0],
        ),
        // Big H1: the raw line, a blanked row, then the rendered rule, which as
        // chrome washes whole under a flash of its line.
        (
            "# **T** end\n\nnext\n",
            "# **",
            "end",
            false,
            true,
            [8..11, 0..0, 0..30, 0..0, 0..0, 0..0],
        ),
        // A revealed reflowed paragraph stacks its two source lines.
        (
            "a **b** c\nmore word\n\nnext\n",
            "a **",
            "word",
            true,
            false,
            [0..0, 5..9, 0..0, 0..0, 0..0, 0..0],
        ),
        (
            "a **b** c\nmore word\n\nnext\n",
            "a **",
            "next",
            true,
            false,
            [0..0, 0..0, 0..0, 0..4, 0..0, 0..0],
        ),
    ];
    for (src, at, flash, reflow, big_h1, expected) in cases {
        let mut state = EditorState::new(Buffer::from_str(src), theme);
        state.mode = Mode::Rendered;
        state.set_viewport_width(30);
        state.set_reflow(!*reflow);
        state.set_reflow(*reflow);
        state.set_big_h1(*big_h1);
        let cursor = src.find(at).unwrap();
        state.cursor.offset = state.buffer.rope().byte_to_char(cursor);
        state.update_cursor_block();
        state.cursor_block_entered_at = None;
        let start = state.buffer.rope().byte_to_char(src.find(flash).unwrap());
        state.flash_yank(start, start + flash.chars().count());

        let backend = TestBackend::new(30, 10);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut view_state = EditorViewState::new();
        let caps = Capabilities::default();
        terminal
            .draw(|frame| {
                let view = EditorView {
                    state: &mut state,
                    theme,
                    filename: "test.md",
                    show_table_buttons: false,
                    table_drop_indicator: None,
                    capabilities: &caps,
                    show_line_numbers: false,
                    is_scrolling: false,
                    hint: HintContent::Chords(HintSet::default()),
                    vim_mode_label: None,
                    visual_kind: None,
                    editor_cursor_style: theme.status_mode_rendered,
                    max_width_enabled: false,
                    max_width_cols: 0,
                    scrollbar_active: false,
                };
                frame.render_stateful_widget(view, frame.area(), &mut view_state);
            })
            .unwrap();

        let buf = terminal.backend().buffer().clone();
        for (y, want) in expected.iter().enumerate() {
            let y = y as u16;
            let got: Vec<u16> = (0..30u16)
                .filter(|&x| buf.cell((x, y)).unwrap().style().bg == theme.selection.bg)
                .collect();
            assert_eq!(
                got,
                want.clone().collect::<Vec<_>>(),
                "{src:?}, flash {flash:?}: row {y}"
            );
        }
    }
}

/// In a cell without hidden markers the raw and formatted text line up, so
/// the cursor keeps its column when the cell reveals.  On a cell's first char
/// it used to land one column left before the reveal, on the pad space.
#[test]
fn table_cursor_keeps_its_column_when_a_plain_cell_reveals() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let src = "| a | bb |\n|---|---|\n| 1 | 2 |\n";
    // On `a`, the first char of a cell, and on the second `b`, past it.
    for (at, col) in [
        (src.find('a').unwrap(), 2u16),
        (src.find("b |").unwrap(), 9),
    ] {
        let mut columns = Vec::new();
        for revealed in [false, true] {
            let mut state = EditorState::new(Buffer::from_str(src), theme);
            state.mode = Mode::Rendered;
            state.set_viewport_width(30);
            state.cursor.offset = state.buffer.rope().byte_to_char(at);
            state.update_cursor_block();
            // Still inside the reveal delay, or past it.
            state.cursor_block_entered_at = (!revealed).then(std::time::Instant::now);

            let backend = TestBackend::new(30, 6);
            let mut terminal = Terminal::new(backend).unwrap();
            let mut view_state = RenderedViewState::default();
            terminal
                .draw(|frame| {
                    let view = RenderedView {
                        cursor_style: theme.status_mode_rendered,
                        visual_kind: None,
                        drop_indicator: None,
                        show_table_buttons: false,
                        state: &state,
                        theme,
                    };
                    frame.render_stateful_widget(view, frame.area(), &mut view_state);
                })
                .unwrap();
            let buf = terminal.backend().buffer().clone();
            let cursor: Vec<u16> = (0..30u16)
                .filter(|&x| buf.cell((x, 1)).unwrap().style().bg == theme.status_mode_rendered.bg)
                .collect();
            columns.push(cursor);
        }
        assert_eq!(
            columns[0],
            vec![col],
            "before the reveal, cursor at byte {at}"
        );
        assert_eq!(
            columns[1],
            vec![col],
            "after the reveal, cursor at byte {at}"
        );
    }
}

/// A cursor in a cell GFM drops (past the header's count) has no drawn cell to reveal into, so
/// the row reveals whole, its dropped cells included, with the cursor on its char; the last
/// drawn cell still reveals on its own.
#[test]
fn table_cursor_in_a_dropped_cell_reveals_the_whole_row() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let src = "| a | b |\n|---|---|\n| 1 | 2 | 3 | 4 |\n";
    let draw = |at: usize| {
        let mut state = EditorState::new(Buffer::from_str(src), theme);
        state.mode = Mode::Rendered;
        state.set_viewport_width(30);
        state.cursor.offset = state.buffer.rope().byte_to_char(at);
        state.update_cursor_block();
        state.cursor_block_entered_at = None;
        let mut terminal = Terminal::new(TestBackend::new(30, 6)).unwrap();
        let mut view_state = RenderedViewState::default();
        terminal
            .draw(|frame| {
                let view = RenderedView {
                    cursor_style: theme.status_mode_rendered,
                    visual_kind: None,
                    drop_indicator: None,
                    show_table_buttons: false,
                    state: &state,
                    theme,
                };
                frame.render_stateful_widget(view, frame.area(), &mut view_state);
            })
            .unwrap();
        terminal.backend().buffer().clone()
    };
    let row_with = |buf: &ratatui::buffer::Buffer, needle: char| {
        (0..6u16)
            .map(|y| (0..30u16).map(|x| buf[(x, y)].symbol()).collect::<String>())
            .find(|row| row.contains(needle))
    };
    let cursor_symbols = |buf: &ratatui::buffer::Buffer| -> Vec<String> {
        (0..6u16)
            .flat_map(|y| (0..30u16).map(move |x| (x, y)))
            .filter(|&p| buf[p].style().bg == theme.status_mode_rendered.bg)
            .map(|p| buf[p].symbol().to_owned())
            .collect()
    };

    let buf = draw(src.rfind('4').unwrap());
    let row = row_with(&buf, '4').expect("the dropped cells show");
    assert!(row.starts_with("| 1 | 2 | 3 | 4 |"), "raw row: {row:?}");
    assert_eq!(cursor_symbols(&buf), ["4"]);

    let buf = draw(src.rfind('2').unwrap());
    assert!(row_with(&buf, '4').is_none(), "a drawn cell reveals alone");
    assert_eq!(cursor_symbols(&buf), ["2"]);
}

/// While a table row is drawn formatted (before its cell reveals, or for as
/// long as search holds the reveal off), the cursor shows on the glyph it is
/// on, past any markers the cell hides, and on the right sub-line of a wrapped
/// cell; a click there puts it back on the same char.  It used to count raw
/// chars over the formatted text, so it sat past its glyph (in the padding,
/// during a whole search).  The reveal then draws it in the raw text.
#[test]
fn table_cursor_shows_on_its_glyph_while_the_row_is_formatted() {
    use crossterm::event::KeyModifiers;
    use edamame::document::Buffer;
    use edamame::editor::{mouse_ops, EditorState};
    use edamame::input::MouseAction;
    use edamame::search::SearchState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    // (source, cursor on, viewport width, screen row, formatted col, revealed col)
    let cases = [
        // `b x y` formatted, `**b** x y` revealed.
        (
            "| a | **b** x y |\n|---|---|\n| 1 | 2222222222222 |\n",
            "x y",
            40,
            1,
            10,
            14,
        ),
        // `alpha` / `bravo` formatted; raw `**alph` / `a**` / `bravo` scrolls to its last
        // two chunks for a cursor in `bravo`, and shows its first for one in `alpha`.
        (
            "| h | k |\n|---|---|\n| a | **alpha** bravo |\n",
            "avo",
            16,
            4,
            10,
            10,
        ),
        (
            "| h | k |\n|---|---|\n| a | **alpha** bravo |\n",
            "pha",
            16,
            3,
            10,
            12,
        ),
    ];
    for (src, on, width, row, formatted, revealed) in cases {
        let at = src.find(on).unwrap();
        let cursor_cols = |phase: &str| -> Vec<u16> {
            let mut state = EditorState::new(Buffer::from_str(src), theme);
            state.mode = Mode::Rendered;
            state.set_viewport_width(width as usize);
            if phase == "search" {
                state.enter_search(SearchState::new("zzz".to_owned(), None).unwrap());
            }
            state.cursor.offset = state.buffer.rope().byte_to_char(at);
            state.update_cursor_block();
            state.cursor_block_entered_at = (phase == "delay").then(std::time::Instant::now);
            let mut terminal = Terminal::new(TestBackend::new(width, 8)).unwrap();
            let mut view_state = RenderedViewState::default();
            terminal
                .draw(|frame| {
                    let view = RenderedView {
                        cursor_style: theme.status_mode_rendered,
                        visual_kind: None,
                        drop_indicator: None,
                        show_table_buttons: false,
                        state: &state,
                        theme,
                    };
                    frame.render_stateful_widget(view, frame.area(), &mut view_state);
                })
                .unwrap();
            let buf = terminal.backend().buffer().clone();
            (0..width)
                .filter(|&x| {
                    buf.cell((x, row)).unwrap().style().bg == theme.status_mode_rendered.bg
                })
                .collect()
        };
        assert_eq!(
            cursor_cols("delay"),
            vec![formatted],
            "{on:?} before the reveal"
        );
        assert_eq!(
            cursor_cols("search"),
            vec![formatted],
            "{on:?} during search"
        );
        assert_eq!(cursor_cols("revealed"), vec![revealed], "{on:?} revealed");

        // A click on the formatted glyph, from outside the table, lands on that char.
        let mut state = EditorState::new(Buffer::from_str(&format!("{src}\nafter\n")), theme);
        state.mode = Mode::Rendered;
        state.set_viewport_width(width as usize);
        state.cursor.offset = state.buffer.len_chars() - 1;
        state.update_cursor_block();
        let click = MouseAction::Click {
            col: formatted,
            row,
            modifiers: KeyModifiers::NONE,
        };
        mouse_ops::apply(&mut state, click, &mut None, &[], 20, width as usize);
        assert_eq!(
            state.buffer.rope().char_to_byte(state.cursor.offset),
            at,
            "{on:?}: a click where the cursor showed"
        );
    }
}

/// Drag-selection highlight must paint on a wrapped cell's continuation
/// sub-line while the drag is still in progress.  During a drag the raw
/// reveal is suppressed (`drag_in_progress`), so the generic byte-range
/// overlay is the only painter — before the fix it skipped continuation
/// sub-lines and the highlight only appeared after mouse release.
#[test]
fn rendered_view_drag_selection_paints_wrapped_cell_continuation() {
    use edamame::config::Theme;
    use edamame::document::{Buffer, Selection};
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme: &'static Theme = Box::leak(Box::new(Theme::default()));
    let src = "| Name | Notes |\n|---|---|\n| a | This is a very long note that wraps |\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    // Re-render at the test viewport's width so the Notes column actually
    // wraps into separate rendered sub-lines (the default 80-col render
    // fits the whole cell on one line and only soft-wraps on screen).
    state.set_viewport_width(28);

    // Select the whole long cell's content; mid-drag state.
    let sel_start = src.find("This").unwrap();
    let sel_end = sel_start + src[sel_start..].find(" |\n").unwrap();
    let rope = state.buffer.rope();
    state.selection = Some(Selection {
        anchor: rope.byte_to_char(sel_start),
        active: rope.byte_to_char(sel_end),
    });
    state.cursor.offset = rope.byte_to_char(sel_end);
    state.update_cursor_block();
    state.drag_in_progress = true; // mouse button still down — reveal suppressed

    let backend = TestBackend::new(28, 12);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                state: &state,
                theme,
                show_table_buttons: false,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let row_text = |y: u16| -> String {
        (0..28u16)
            .map(|x| {
                buf.cell((x, y))
                    .and_then(|c| c.symbol().chars().next())
                    .unwrap_or(' ')
            })
            .collect()
    };

    // Find the continuation sub-line: the row showing the final chunk
    // ("wraps") of the wrapped cell.
    let cont_y = (0..12u16)
        .find(|&y| row_text(y).contains("wraps"))
        .expect("wrapped continuation row visible");
    let x = row_text(cont_y).find("wraps").unwrap() as u16;
    let cell = buf.cell((x, cont_y)).expect("cell in bounds");
    assert_eq!(
        cell.style().bg,
        theme.selection.bg,
        "selection background must paint on the wrapped continuation row mid-drag"
    );
}

/// The line-number gutter numbers *source* lines in Rendered mode, not the
/// renderer's output rows.  A 5-line GFM table plus a trailing paragraph
/// renders taller than its source, so the numbers must skip the border rows
/// rather than run 1..N down the side of the document.
#[test]
fn gutter_numbers_source_lines_in_rendered_mode() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::terminal::Capabilities;
    use edamame::ui::bottom_region::{HintContent, HintSet};
    use edamame::ui::{EditorView, EditorViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let src = "| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\nafter\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;

    let backend = TestBackend::new(40, 14);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = EditorViewState::new();
    let caps = Capabilities::default();
    terminal
        .draw(|frame| {
            let view = EditorView {
                state: &mut state,
                theme,
                filename: "test.md",
                show_table_buttons: false,
                table_drop_indicator: None,
                capabilities: &caps,
                show_line_numbers: true,
                is_scrolling: false,
                hint: HintContent::Chords(HintSet::default()),
                vim_mode_label: None,
                visual_kind: None,
                editor_cursor_style: theme.status_mode_rendered,
                max_width_enabled: false,
                max_width_cols: 0,
                scrollbar_active: false,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    // 6 buffer lines → 1 digit + 2 padding.
    let buf = terminal.backend().buffer().clone();
    let gutter: Vec<String> = (0..12u16)
        .map(|y| {
            (0..3u16)
                .map(|x| buf.cell((x, y)).unwrap().symbol())
                .collect::<String>()
                .trim()
                .to_string()
        })
        .collect();

    // Every number appears exactly once, in source order, and the rows in
    // between (table borders) are blank.
    let numbers: Vec<&str> = gutter
        .iter()
        .filter(|s| !s.is_empty())
        .map(|s| s.as_str())
        .collect();
    assert_eq!(
        numbers,
        vec!["1", "2", "3", "4", "5", "6"],
        "gutter: {gutter:?}"
    );
    assert!(
        gutter.iter().filter(|s| s.is_empty()).count() >= 4,
        "expected blank rows for table borders: {gutter:?}"
    );
}

/// Regression (issue #24): a diagram whose rendered image is shorter than
/// its mermaid source must not clip the raw-source reveal.  The block
/// reserves the image's rows until the cursor enters it, then reserves one
/// row per source line — so every line of the fence is on screen and the
/// content below reflows down.
#[test]
fn revealed_diagram_shows_every_source_line() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let src = "```mermaid\nflowchart LR\n    A --> B\n    B --> C\n```\n\nAfter.\n";
    // Two reserved image rows — the short-wide diagram from the report.
    let mut state = EditorState::new_with_config(Buffer::from_str(src), theme, true, true, 2);
    state.mode = Mode::Rendered;
    let byte = src.find("flowchart").unwrap();
    state.cursor.offset = state.buffer.rope().byte_to_char(byte);
    // `RenderedView` reveals the block named by the *cached* `cursor_block_idx`,
    // which a bare `cursor.offset` write leaves pointing at whatever block the
    // cursor was constructed on.  Resolve it the way every production cursor
    // move does, so this test keeps testing the reveal rather than the fence
    // happening to be block 0.
    state.update_cursor_block();
    // `update_cursor_block` arms the reveal timer; the reveal is what happens
    // once it elapses, so skip the delay rather than sleep it.
    state.cursor_block_entered_at = None;
    assert!(
        state.sync_image_reveal(),
        "entering the diagram must re-lay the document out"
    );

    let backend = TestBackend::new(30, 10);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let rows: Vec<String> = (0..10u16)
        .map(|y| {
            (0..30u16)
                .map(|x| buf.cell((x, y)).unwrap().symbol())
                .collect::<String>()
                .trim_end()
                .to_string()
        })
        .collect();
    let joined = rows.join("\n");
    for line in ["flowchart LR", "A --> B", "B --> C"] {
        assert!(
            joined.contains(line),
            "revealed diagram must show {line:?}: {rows:?}"
        );
    }
    // The document reflowed around the taller block: the trailer is still
    // painted, below the whole fence.
    let after = rows
        .iter()
        .position(|r| r.contains("After."))
        .unwrap_or_else(|| panic!("trailer must stay visible: {rows:?}"));
    let last_source = rows
        .iter()
        .position(|r| r.contains("B --> C"))
        .expect("last diagram line");
    assert!(
        after > last_source,
        "trailer must follow the fence: {rows:?}"
    );
}

/// The mirror case: an ordinary `![alt](url)` is one source line behind a
/// reservation as tall as its picture, so revealing it used to leave the
/// rest of those rows as blank space with the source line floating in it.
/// The block collapses to its one line instead and the document reflows up
/// around it — keeping the blank separator line the image's extended block
/// range absorbs, which is a virtual block of its own.
#[test]
fn revealed_image_reflows_the_document_around_its_source_line() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let src = "Above.\n\n![cat](cat.png)\n\nBelow.\n";
    // Twelve reserved rows: with no decode in flight the renderer falls
    // back to `image_max_height`, which is what a tall picture would take.
    let mut state = EditorState::new_with_config(Buffer::from_str(src), theme, true, true, 12);
    state.mode = Mode::Rendered;
    let byte = src.find("![cat]").unwrap();
    state.cursor.offset = state.buffer.rope().byte_to_char(byte);
    state.update_cursor_block();
    state.cursor_block_entered_at = None;
    assert!(
        state.sync_image_reveal(),
        "entering the image must re-lay the document out"
    );

    let backend = TestBackend::new(30, 10);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let rows: Vec<String> = (0..10u16)
        .map(|y| {
            (0..30u16)
                .map(|x| buf.cell((x, y)).unwrap().symbol())
                .collect::<String>()
                .trim_end()
                .to_string()
        })
        .collect();

    let image = rows
        .iter()
        .position(|r| r.contains("![cat](cat.png)"))
        .unwrap_or_else(|| panic!("the raw source line must be painted: {rows:?}"));
    let below = rows
        .iter()
        .position(|r| r.contains("Below."))
        .unwrap_or_else(|| panic!("trailer must stay visible: {rows:?}"));
    assert_eq!(
        below,
        image + 2,
        "the trailer must follow one blank separator row, not the \
         picture's reservation: {rows:?}"
    );
}

// ── Raw mode: flat wrap ───────────────────────────────────────────────────

/// Render `text` in Raw mode at `width` × `height` and return the painted
/// rows as strings (trailing blanks trimmed).
fn render_raw_rows(state: &edamame::editor::EditorState, width: u16, height: u16) -> Vec<String> {
    use edamame::ui::raw_view::{RawView, RawViewState};
    use ratatui::widgets::StatefulWidget;

    let theme = Box::leak(Box::new(Theme::default()));
    let mut view_state = RawViewState::default();
    let backend = TestBackend::new(width, height);
    let mut terminal = Terminal::new(backend).unwrap();
    terminal
        .draw(|frame| {
            let view = RawView {
                state,
                theme,
                visual_kind: None,
                cursor_style: theme.status_mode_raw,
            };
            StatefulWidget::render(view, frame.area(), frame.buffer_mut(), &mut view_state);
        })
        .unwrap();

    let tbuf = terminal.backend().buffer().clone();
    (0..height)
        .map(|y| {
            let row: String = (0..width)
                .map(|x| {
                    tbuf.cell((x, y))
                        .map_or(' ', |c| c.symbol().chars().next().unwrap_or(' '))
                })
                .collect();
            row.trim_end().to_string()
        })
        .collect()
}

fn raw_state(text: &str) -> edamame::editor::EditorState {
    let theme = Box::leak(Box::new(Theme::default()));
    let mut state =
        edamame::editor::EditorState::new(edamame::document::Buffer::from_str(text), theme);
    state.mode = Mode::Raw;
    state
}

#[test]
fn raw_view_wraps_a_list_item_without_a_hanging_indent() {
    // Raw mode shows the file: word-wrap is the one liberty it takes, so a
    // continuation row starts at column 0 rather than aligning under the
    // list marker's text column (which would paint two spaces that aren't
    // in the document).
    let state = raw_state("- alpha bravo charlie delta echo foxtrot\n");
    let rows = render_raw_rows(&state, 16, 6);
    assert_eq!(rows[0], "- alpha bravo");
    assert!(
        !rows[1].starts_with(' '),
        "continuation row is indented: {:?}",
        rows[1]
    );
    assert_eq!(rows[1], "charlie delta");
}

#[test]
fn raw_view_wrapped_rows_agree_with_the_click_mapping() {
    // The painter, the scroll cache and `mouse_ops::coord` must all wrap
    // the same way.  Click every painted cell of a wrapped list item and
    // assert the cursor lands on the character drawn there — a hanging
    // indent in the painter alone would skew every continuation row by the
    // marker width.
    use edamame::editor::mouse_ops;

    const W: u16 = 16;
    let src = "- alpha bravo charlie delta echo foxtrot\nplain tail line\n";
    let mut state = raw_state(src);
    let rows = render_raw_rows(&state, W, 8);

    for (y, row) in rows.iter().enumerate() {
        for (x, painted) in row.chars().enumerate() {
            if painted == ' ' {
                continue; // a wrap-eaten space has no unique source char
            }
            let mut anchor: Option<mouse_ops::DragTarget> = None;
            let action = edamame::input::MouseAction::Click {
                col: x as u16,
                row: y as u16,
                modifiers: crossterm::event::KeyModifiers::NONE,
            };
            mouse_ops::apply(&mut state, action, &mut anchor, &[], 8, W as usize);
            let at_cursor = state
                .buffer
                .rope()
                .chars_at(state.cursor.offset)
                .next()
                .unwrap_or('\n');
            assert_eq!(
                at_cursor, painted,
                "click at ({x}, {y}) landed on {at_cursor:?}, painted {painted:?}"
            );
        }
    }
}

/// Regression: an empty document must still show the block cursor in
/// Rendered mode.  An empty source produces no Markdown blocks, so before
/// the phantom-line virtual block covered `total_bytes == 0` there were no
/// rendered lines at all and `RenderedView`'s paint loop broke out
/// immediately — the cursor was never drawn.  Raw mode was unaffected
/// because `RawView` walks the rope, which reports one empty line for `""`.
#[test]
fn empty_document_shows_the_cursor_in_rendered_mode() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let mut state = EditorState::new(Buffer::from_str(""), theme);
    state.mode = Mode::Rendered;
    state.cursor.offset = 0;

    let backend = TestBackend::new(20, 4);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let cell = buf.cell((0, 0)).expect("cell (0,0) must exist");
    let style = cell.style();
    assert_eq!(
        (style.fg, style.bg),
        (theme.status_mode_rendered.fg, theme.status_mode_rendered.bg),
        "the cursor block must be painted at line 0, column 0 of an empty document"
    );
}

/// A revealed `$$...$$` math block is styled like a mermaid fence: the
/// opening `$$` becomes a ` math ` language header on the `code_block_lang`
/// surface, the body carries the `code_block_text` code surface, and the
/// closing `$$` is a blank padded row on that same surface — the delimiter
/// rows show their literal `$$` only when the cursor is on them.  Here the
/// cursor sits on the body line, so the delimiters show their styled forms.
/// Preview off keeps the source flush to the block top (no formula band),
/// so rows 0/1/2 are opening / body / closing.
#[test]
fn revealed_math_block_is_styled_like_a_code_block() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let mut state = EditorState::new(Buffer::from_str("$$\nE = mc^2\n$$\n"), theme);
    state.mode = Mode::Rendered;
    state.math_preview = false; // source flush to the top, no formula band
                                // Cursor on the body line ("E = mc^2"), past the opening "$$\n".
    state.cursor.offset = "$$\n".chars().count() + 1;
    state.update_cursor_block();
    state.cursor_block_entered_at = None; // skip the jitter delay
    assert!(state.cursor_block_revealed(), "the math block must reveal");
    assert!(state.sync_image_reveal());

    let backend = TestBackend::new(25, 6);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let row_text = |y: u16| -> String {
        (0..25u16)
            .filter_map(|x| buf.cell((x, y)).map(|c| c.symbol().to_string()))
            .collect()
    };
    let row_has_bg = |y: u16, bg| {
        (0..25u16).any(|x| {
            buf.cell((x, y))
                .map(|c| c.style().bg == bg)
                .unwrap_or(false)
        })
    };

    // Row 0: the ` math ` header on the language surface — not a literal `$$`.
    assert!(
        row_text(0).contains("math"),
        "opening row: {:?}",
        row_text(0)
    );
    assert!(
        !row_text(0).contains("$$"),
        "opening `$$` must be hidden when the cursor is elsewhere: {:?}",
        row_text(0)
    );
    assert!(
        row_has_bg(0, theme.code_block_lang.bg),
        "header row must carry the code-block language surface"
    );
    // Row 1: the body line on the code surface.
    assert!(
        row_text(1).contains("E = mc^2"),
        "body row: {:?}",
        row_text(1)
    );
    assert!(
        row_has_bg(1, theme.code_block_text.bg),
        "body row must carry the code-block text surface"
    );
    // Row 2: the closing `$$` renders as a blank padded row on the code
    // surface (no literal `$$` without the cursor).
    assert!(
        !row_text(2).contains("$$"),
        "closing `$$` must be hidden when the cursor is elsewhere: {:?}",
        row_text(2)
    );
    assert!(
        row_has_bg(2, theme.code_block_text.bg),
        "closing row must carry the code-block surface"
    );
}

/// When the cursor lands on a `$$...$$` block's opening delimiter, that row
/// reveals its literal `$$` for editing (rather than the ` math ` header) —
/// the same affordance a fenced code block gives its opening fence.
#[test]
fn revealed_math_block_shows_literal_delimiter_under_the_cursor() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let mut state = EditorState::new(Buffer::from_str("$$\nE = mc^2\n$$\n"), theme);
    state.mode = Mode::Rendered;
    state.math_preview = false;
    state.cursor.offset = 0; // on the opening `$$`
    state.update_cursor_block();
    state.cursor_block_entered_at = None;
    assert!(state.cursor_block_revealed());
    assert!(state.sync_image_reveal());

    let backend = TestBackend::new(25, 6);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    let row0: String = (0..25u16)
        .filter_map(|x| buf.cell((x, 0)).map(|c| c.symbol().to_string()))
        .collect();
    assert!(
        row0.contains("$$"),
        "opening row must reveal its literal `$$` under the cursor: {row0:?}"
    );
    assert!(
        !row0.contains("math"),
        "the ` math ` header must yield to the raw delimiter under the cursor: {row0:?}"
    );
}

/// Regression: when a `$$...$$` block is followed by more content, its byte
/// range absorbs the trailing blank line, so the reveal's `raw_lines` gains
/// a trailing empty entry past the real closing `$$`.  The closing must
/// still be detected (matched by its `$$` text, not by the last index) and
/// render as a blank padded row — not fall through to the body branch and
/// show a literal `$$`.  Cursor on the body so the closing has no cursor.
#[test]
fn revealed_math_block_closing_is_blank_even_with_trailing_content() {
    use edamame::document::Buffer;
    use edamame::editor::EditorState;
    use edamame::ui::{RenderedView, RenderedViewState};

    let theme = Box::leak(Box::new(Theme::default()));
    let src = "Intro.\n\n$$\nE = mc^2\n$$\n\nAfter.\n";
    let mut state = EditorState::new(Buffer::from_str(src), theme);
    state.mode = Mode::Rendered;
    state.math_preview = false;
    // Cursor on the body line "E = mc^2" (offset past "Intro.\n\n$$\n").
    state.cursor.offset = "Intro.\n\n$$\n".chars().count() + 1;
    state.update_cursor_block();
    state.cursor_block_entered_at = None; // skip the jitter delay (block changed)
    assert!(state.cursor_block_revealed(), "the math block must reveal");
    assert!(state.sync_image_reveal());

    let backend = TestBackend::new(25, 10);
    let mut terminal = Terminal::new(backend).unwrap();
    let mut view_state = RenderedViewState::default();
    terminal
        .draw(|frame| {
            let view = RenderedView {
                cursor_style: theme.status_mode_rendered,
                visual_kind: None,
                drop_indicator: None,
                show_table_buttons: false,
                state: &state,
                theme,
            };
            frame.render_stateful_widget(view, frame.area(), &mut view_state);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    // No row in the whole view may show a literal `$$` — the opening is the
    // ` math ` header and the closing is a blank padded row (neither has the
    // cursor).  Before the fix the closing `$$` leaked through as body text.
    let mut full = String::new();
    for y in 0..10u16 {
        for x in 0..25u16 {
            if let Some(c) = buf.cell((x, y)) {
                full.push_str(c.symbol());
            }
        }
    }
    assert!(
        !full.contains("$$"),
        "no literal `$$` should render while the cursor is on the body: {full:?}"
    );
}