shoin 0.2.0

A no-clutter terminal Markdown editor with modal editing
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
//! Painting a frame. Pure: reads state, writes cells, mutates nothing.
//!
//! Build-order steps 1-3 render plain text. Markdown styling arrives in step 4
//! (block classification) and step 5 (inline), concealment in step 6 — all of
//! which slot in where the row `Span` is currently built raw.

use ratatui::layout::{Alignment, Position, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Borders, Clear, Paragraph};
use ratatui::Frame;

use crate::app::{App, FlashKind};
use crate::finder::{Finder, VISIBLE_ROWS};
use crate::help::Help;
use crate::input::mode::{Mode, Prompt, PromptKind};
use crate::render::align::{self, TextAlign};
use crate::render::cache::RenderCache;
use crate::render::markdown::block::BlockKind;
use crate::render::splash;
use crate::render::focus::FocusRegion;
use crate::render::layout::{display_width, scroll_offset, Layout, VisualRow};
use crate::render::numbers::NumberMode;
use crate::render::theme::Color as ThemeColor;
use crate::render::theme::Style as ThemeStyle;
use crate::render::StyledSpan;
use crate::text::cursor::Cursor;
use crate::tree::{Entry, FileTree, IconKind};

/// Rows the status line occupies when visible.
pub const STATUS_ROWS: u16 = 1;

pub fn render(frame: &mut Frame, app: &App) {
    let area = frame.area();
    // Recomputed every frame: an overlay that closed must stop withholding the
    // pictures it was covering.
    app.overlay.set(None);
    app.images.borrow_mut().clear();
    let cfg = &app.config;

    // Paint the theme background across the whole surface so a theme is
    // self-contained: a light theme stays light on a dark terminal (and vice
    // versa), instead of drawing its text onto the terminal's own background.
    let bg = app.theme.background.to_ratatui();
    frame.render_widget(Block::default().style(Style::default().bg(bg)), area);

    // The diff view takes over the whole surface, like help. Checked first
    // because a reader who opened it is deciding about a file, and nothing
    // underneath is worth a partial repaint behind that.
    if let Some(view) = &app.diff {
        render_diff(frame, app, view, area);
        return;
    }
    // The help overlay takes over the whole surface when open.
    if let Some(help) = &app.help {
        render_help(frame, app, help, area);
        return;
    }

    // Split off a left column for the file tree, if open. It is chrome, not a
    // view onto a document, so it sits OUTSIDE the pane tree.
    let tw = tree_width(app, area);
    if let Some(tree) = &app.tree {
        let tree_rect = Rect { x: area.x, y: area.y, width: tw, height: area.height };
        render_tree(frame, app, tree, tree_rect);
    }
    let ea = Rect {
        x: area.x + tw,
        y: area.y,
        width: area.width.saturating_sub(tw),
        height: area.height,
    };

    // --- panes ---
    //
    // One rect per leaf of the layout tree. Each pane computes its own measure
    // and margins from its width, so a split is two narrower measures rather
    // than one measure clipped in half.
    let geo = app.layout.geometry(pane_area(app, area));
    let mut caret = None;
    for (id, rect) in &geo.panes {
        let Some(pane) = app.layout.pane(*id) else { continue };
        if let Some(pos) = render_pane(frame, app, pane, *rect, *id == app.focus_pane) {
            caret = Some(pos);
        }
    }
    for d in &geo.dividers {
        frame.render_widget(
            Block::default().style(
                Style::default()
                    .bg(app.theme.text_dim.to_ratatui())
                    .fg(app.theme.text_dim.to_ratatui()),
            ),
            *d,
        );
    }

    // --- status line ---
    //
    // One for the whole window, not one per pane: it is a transient flash, and
    // repeating it beside itself would be noise.
    if cfg.status.enabled {
        if let Some(status) = status_text(app) {
            let style = match app.flash.as_ref().map(|f| &f.kind) {
                Some(FlashKind::Error) => Style::default().fg(Color::Red),
                _ => Style::default().add_modifier(Modifier::DIM),
            };
            let lay = Layout::compute(&cfg.layout, ea.width, ea.height, STATUS_ROWS);
            let status_area = Rect {
                x: ea.x + lay.margin_left,
                y: ea.y + ea.height.saturating_sub(STATUS_ROWS),
                width: lay.measure,
                height: STATUS_ROWS,
            };
            // Elide rather than let ratatui cut the tail off silently. A
            // clipped message looks like a finished one, and the half that
            // gets lost is the end — which for an error is the half that says
            // what to do about it.
            let status = elide(&status, lay.measure as usize);
            let line = Line::from(Span::styled(status, style)).right_aligned();
            frame.render_widget(Paragraph::new(line), status_area);
        }
    }

    // --- caret ---
    //
    // The finder overlay outranks everything — it takes all input while it is
    // open. Otherwise: the tree owns the caret when it has focus (set in
    // `render_tree`), Command and Search modes put it in the spotlight box, and
    // failing all that it sits where the focused pane put it.
    let tree_focused = app.tree.as_ref().is_some_and(|t| t.focused);
    if let Some(finder) = &app.finder {
        render_finder(frame, app, finder, ea);
    } else if let Mode::Prompt(p) = &app.mode {
        // Above the tree, which is what asked the question.
        let prompt = prompt_label(app, p);
        render_command_box(frame, app, p.kind.title(), &prompt, &p.input, ea);
    } else if tree_focused {
        // caret set by render_tree
    } else if let Mode::Command(buf) = &app.mode {
        render_command_box(frame, app, " command ", ":", buf, ea);
    } else if let Mode::Search { query, reverse } = &app.mode {
        let prompt = if *reverse { "?" } else { "/" };
        render_command_box(frame, app, " search ", prompt, query, ea);
    } else if let Some(pos) = caret {
        frame.set_cursor_position(pos);
    }
}

/// The area the pane tree divides: the frame, less the tree sidebar and the row
/// the status line reserves. `App` asks for this too, so click routing and the
/// screen motions use the same geometry the renderer did.
pub fn pane_area(app: &App, area: Rect) -> Rect {
    let tw = tree_width(app, area);
    let reserved = if app.config.status.enabled { STATUS_ROWS } else { 0 };
    Rect {
        x: area.x + tw,
        y: area.y,
        width: area.width.saturating_sub(tw),
        height: area.height.saturating_sub(reserved),
    }
}

/// Draw one pane, returning where the caret goes if this is the focused one.
///
/// Concealment (build-order step 6). Each source line is turned into its
/// DISPLAY form: the cursor's line (and, in Visual, the whole selection)
/// renders raw 1:1; every other line has its markers hidden. Then:
///   active set (known) → wrap on display width → scroll offset
/// in that order, so a line re-expanding its markers as the cursor lands on it
/// never scrolls itself off screen (SPEC.md §6, "Reveal shift").
///
/// The parse and the wrap come from the document's cache; only the rows
/// actually on screen are turned into styled spans.
fn render_pane(
    frame: &mut Frame,
    app: &App,
    pane: &crate::render::pane::Pane,
    rect: Rect,
    focused: bool,
) -> Option<Position> {
    let cfg = &app.config;
    let bg = app.theme.background.to_ratatui();
    let doc = app.docs.get(pane.doc)?;

    // Nothing opened and nothing typed: draw the start screen instead of an
    // empty measure, and return no caret — there is nothing yet to point at,
    // and a block sitting on the artwork would be the only thing in the room.
    // The first keystroke makes `splash::active` false and the pane renders
    // normally from the very same frame.
    if splash::active(app) {
        splash::render(frame, app, rect);
        return None;
    }

    // The status line already has its row reserved out of `pane_area`.
    let mut lay = Layout::compute(&cfg.layout, rect.width, rect.height, 0);
    // Zero when numbers are off, or when the margin has no room for them —
    // `align = "left"`'s fixed 2-column margin, say — in which case the pane
    // simply goes without rather than drawing into the text.
    let numbers = app.numbers;
    lay.number_gutter = number_gutter_width(numbers, doc.buffer.line_count(), lay.margin_left);

    let mut cache = doc.cache.borrow_mut();
    cache.sync_doc(app, doc, lay.measure);

    // The focused pane follows the document's live cursor; every other pane
    // anchors on its OWN, clamped — an edit in another pane can have moved the
    // text out from under a saved position.
    let cursor = if focused {
        doc.buffer.cursor
    } else {
        let line = pane.cursor.line.min(doc.buffer.line_count().saturating_sub(1));
        Cursor::new(line, pane.cursor.col.min(doc.buffer.line_len(line)))
    };
    let (cursor_row, cursor_offset) = cache.locate(cursor.line, cursor.col);
    let top = scroll_offset(
        cursor_row,
        cache.total_rows(),
        &lay,
        &cfg.layout,
        cfg.editor.scroll_off,
        pane.scroll.get(),
        app.view,
    );
    // Persist the computed top, not just the value this frame drew: without
    // this, `scroll_offset`'s "stay put unless the cursor leaves the padded
    // zone" check always sees a stale baseline and re-derives from scratch
    // every frame, which reads as the viewport jumping around on navigation
    // instead of scrolling smoothly (SPEC.md §6, "Reveal shift").
    pane.scroll.set(top);

    let text_area = Rect {
        x: rect.x + lay.margin_left,
        y: rect.y + lay.top,
        width: lay.measure,
        height: lay.height,
    };

    // Rows of one line are contiguous, so one materialized DisplayLine serves
    // every row it wrapped into. Each row is drawn on its own so the active
    // line can hang its revealed markers into the reserved gutter.
    let mut current: Option<(usize, DisplayLine)> = None;
    for (i, row) in (top..top + lay.height as usize)
        .filter_map(|r| cache.row(r))
        .enumerate()
    {
        // Line spacing (SPEC.md §6): a row with no line behind it. It is
        // painted rather than skipped so it takes the pane's background —
        // skipping it would leave whatever the last frame drew there — and it
        // deliberately gets no fence slab or bar, because `spacer_rows` never
        // puts one inside a fence.
        if row.is_spacer() {
            let r = Rect { x: text_area.x, y: text_area.y + i as u16, width: lay.measure, height: 1 };
            frame.render_widget(Paragraph::new("").style(Style::default().bg(bg)), r);
            current = None;
            continue;
        }

        // A transcluded row has no text in this rope, so it is drawn from the
        // expansion the cache captured rather than from a `DisplayLine`.
        if let Some(index) = row.embedded() {
            let r = Rect {
                x: text_area.x,
                y: text_area.y + i as u16,
                width: lay.measure,
                height: 1,
            };
            render_embed_row(frame, app, &cache, row.line(), index, r, bg);
            current = None;
            continue;
        }
        let is_first_row = current.as_ref().is_none_or(|(l, _)| *l != row.line());
        if is_first_row {
            current = Some((row.line(), display_line_of(app, doc, &cache, row.line(), focused)));
        }
        let d = &current.as_ref().unwrap().1;
        let mut spans = window_spans(&d.text, &d.spans, row.start_col, row.end_col);
        let shift = gutter_shift(app, &cache, &lay, row.line(), row.start_col);
        // A wrapped list continuation is pushed right to sit under the item's
        // content; the cache already wrapped it at the narrower width (SPEC §6).
        let hang = hang_x(app, &cache, &lay, &row);
        let r = Rect {
            x: text_area.x - shift + hang,
            y: text_area.y + i as u16,
            width: lay.measure + shift - hang,
            height: 1,
        };
        // A fenced row's slab is painted by the ROW, not by its spans: the
        // spans stop where the code does, and SPEC §5.3 asks for a flat
        // background across the measure (SPEC §5.3).
        let fenced = in_fence(&cache, row.line());
        let row_bg = if fenced { app.theme.code_bg.to_ratatui() } else { bg };

        // `text_align` shapes how each row sits WITHIN the column — a
        // different axis from the column's own placement (`layout.align`,
        // handled by `lay.margin_left` already). It never touches a fenced
        // code row (columns are code) or a table row (its `|`s are the
        // author's own layout, already left as `no_wrap`).
        let table = matches!(doc.blocks.kinds.get(row.line()), Some(BlockKind::Table));
        let is_last_row = row.end_col >= d.text.chars().count();
        let align = row_align(app.text_align, fenced || table, is_last_row);
        let mut alignment = None;
        match align {
            TextAlign::Left => {}
            TextAlign::Center => alignment = Some(Alignment::Center),
            TextAlign::Right => alignment = Some(Alignment::Right),
            TextAlign::Justified => {
                let row_text: String =
                    d.text.chars().skip(row.start_col).take(row.end_col - row.start_col).collect();
                let gaps = align::justify_gaps(&row_text, r.width);
                if !gaps.is_empty() {
                    spans = stretch_spans(spans, &gaps);
                }
            }
        }
        let mut line = Line::from(spans);
        if let Some(a) = alignment {
            line = line.alignment(a);
        }
        frame.render_widget(Paragraph::new(line).style(Style::default().bg(row_bg)), r);
        if fenced {
            render_fence_bar(frame, app, r);
        }
        // Shifted left by the SAME `shift` as the row's own text: on the
        // active line, revealed markers hang into the columns immediately
        // left of where the row now starts, so the number has to give up
        // that band and sit one further band left of it — never the same
        // columns, whatever `shift` turns out to be. When even that does not
        // fit the margin, the number is skipped for this one row rather than
        // drawn off the pane or over the markers.
        if lay.number_gutter > 0 && is_first_row && shift + lay.number_gutter <= lay.margin_left {
            let gutter = Rect {
                x: text_area.x - shift - lay.number_gutter,
                y: text_area.y + i as u16,
                width: lay.number_gutter - 1,
                height: 1,
            };
            render_line_number(frame, app, gutter, numbers, row.line(), cursor.line);
        }
    }

    render_scroll_hint(frame, app, rect, &text_area, top, cache.total_rows());

    // Read-only mode has no caret: every line is concealed, so a column in
    // the source does not name a cell on screen, and there is nothing to type.
    if !focused || app.view {
        return None;
    }
    let screen_row = cursor_row.saturating_sub(top);
    if screen_row >= lay.height as usize {
        return None;
    }
    let vr = cache.row(cursor_row);
    let row_start = vr.map(|r| r.start_col).unwrap_or(0);
    let row_end = vr.map(|r| r.end_col).unwrap_or(0);
    let hang = vr.map(|r| hang_x(app, &cache, &lay, &r)).unwrap_or(0);
    let line_text = doc.buffer.line_text(cursor.line);
    let prefix: String = line_text.chars().skip(row_start).take(cursor_offset).collect();
    let shift = gutter_shift(app, &cache, &lay, cursor.line, row_start);

    // The same alignment the render loop drew this row with, so the caret
    // lands where the text actually is under `Center`/`Right`/`Justified`.
    // The active line is always shown raw (never concealed), so `line_text`
    // above is exactly what that loop windowed for this row.
    let table = matches!(doc.blocks.kinds.get(cursor.line), Some(BlockKind::Table));
    let fenced = in_fence(&cache, cursor.line);
    let is_last_row = row_end >= line_text.chars().count();
    let align = row_align(app.text_align, fenced || table, is_last_row);
    let row_width = lay.measure + shift - hang;
    let extra = match align {
        TextAlign::Left => 0,
        TextAlign::Center | TextAlign::Right => {
            let row_text: String = line_text.chars().skip(row_start).take(row_end - row_start).collect();
            align::align_offset(align, display_width(&row_text), row_width)
        }
        TextAlign::Justified => {
            let row_text: String = line_text.chars().skip(row_start).take(row_end - row_start).collect();
            let gaps = align::justify_gaps(&row_text, row_width);
            align::justify_offset(&gaps, cursor_offset)
        }
    };
    let x = (text_area.x + display_width(&prefix) + hang + extra)
        .saturating_sub(shift)
        .min(rect.right().saturating_sub(1));
    Some(Position::new(x, text_area.y + screen_row as u16))
}

/// Draw one row of an expanded `![[…]]` (SPEC.md §14.3).
///
/// The border and the label wear `theme.text_dim` so the embed reads as a
/// quotation rather than as this document's own text — the reader needs to know
/// at a glance which words they can edit. An unresolved embed wears
/// `theme.error`, per §14.2.
fn render_embed_row(
    frame: &mut Frame,
    app: &App,
    cache: &RenderCache,
    line: usize,
    index: usize,
    rect: Rect,
    bg: ratatui::style::Color,
) {
    use crate::transclude::preview::Row;
    let Some(row) = cache
        .entry(line)
        .and_then(|e| e.embed.as_ref())
        .and_then(|x| x.rows.get(index))
    else {
        return;
    };
    let theme = &app.theme;
    let dim = ThemeStyle::fg(theme.text_dim).to_ratatui();
    let width = rect.width as usize;

    // A picture's box is drawn as an OUTLINE when the terminal cannot show
    // pixels, and as plain spaces when it can — there, the outline would only
    // be something for the image to cover up.
    let pixels = app.image_protocol != crate::image::Protocol::None;
    let spans: Vec<Span> = match row {
        Row::Image(pic) => {
            app.images.borrow_mut().push(crate::render::Placement {
                x: rect.x,
                y: rect.y,
                cols: pic.cols,
                rows: pic.rows,
                line,
                index,
            });
            if pixels {
                vec![Span::raw(" ".repeat(pic.cols as usize))]
            } else {
                let w = (pic.cols as usize).min(width).max(2);
                vec![Span::styled(
                    format!("\u{256d}{}\u{256e}", "\u{2500}".repeat(w - 2)),
                    dim,
                )]
            }
        }
        Row::Reserved => {
            if pixels {
                vec![Span::raw("")]
            } else {
                // The last reserved row closes the box, so the outline needs to
                // know where it ends — the expansion says.
                let (w, last) = cache
                    .entry(line)
                    .and_then(|e| e.embed.as_ref())
                    .map(|x| {
                        let w = match x.rows.first() {
                            Some(Row::Image(p)) => (p.cols as usize).min(width).max(2),
                            _ => width.max(2),
                        };
                        let last = !matches!(x.rows.get(index + 1), Some(Row::Reserved));
                        (w, last)
                    })
                    .unwrap_or((width.max(2), true));
                let (l, r) = if last { ('\u{2570}', '\u{256f}') } else { ('\u{2502}', '\u{2502}') };
                let fill = if last { "\u{2500}".repeat(w - 2) } else { " ".repeat(w - 2) };
                vec![Span::styled(format!("{l}{fill}{r}"), dim)]
            }
        }
        Row::Caption(text) => vec![Span::styled(elide(text, width), dim)],
        Row::Top(label) => {
            // `\u{256d} `, ` `, at least one rule cell, and `\u{256e}` are the fixed cost; a
            // label longer than what is left is elided rather than allowed to
            // push the closing corner off the screen.
            let room = width.saturating_sub(5);
            let label = elide(label, room);
            let head = format!("\u{256d} {label} ");
            let rule = "\u{2500}".repeat(width.saturating_sub(display_width(&head) as usize + 1));
            vec![Span::styled(format!("{head}{rule}\u{256e}"), dim)]
        }
        Row::Bottom => vec![Span::styled(
            format!(
                "\u{2570}{}\u{256f}",
                "\u{2500}".repeat(width.saturating_sub(2))
            ),
            dim,
        )],
        Row::Error(msg) => vec![Span::styled(
            msg.clone(),
            ThemeStyle::fg(theme.error).to_ratatui(),
        )],
        Row::Body(text, block) => {
            // Styled AND CONCEALED with the document's own rules. An embedded
            // line is never the active line — it is not in this rope at all —
            // so by SPEC §2 it always shows its finished form, and an embedded
            // `# Heading` must read as a heading rather than as its source.
            let md = &app.config.markdown;
            let inline = crate::render::markdown::inline::scan(text, md);
            let styled = crate::render::markdown::style_line_with(
                text,
                block.clone(),
                crate::text::buffer::Syntax::Markdown,
                theme,
                md,
                &inline,
            );
            let ctx = crate::render::conceal::ConcealCtx {
                glyphs: &app.config.glyphs,
                theme,
                measure: width as u16,
                tab_width: app.config.editor.tab_width,
            };
            let (shown, spans) = if app.config.layout.conceal {
                crate::render::conceal::ConcealMap::build(text, block, &inline, &ctx)
                    .render(text, &styled)
            } else {
                (text.clone(), styled)
            };
            let bordered = app.config.transclude.border && app.embed_mode.framed();
            let mut out = if bordered {
                vec![Span::styled("\u{2502} ".to_string(), dim)]
            } else {
                Vec::new()
            };
            out.extend(window_spans(&shown, &spans, 0, shown.chars().count()));
            // Pad to the closing bar so the box has a straight right edge. The
            // content was wrapped to fit between the bars, so this only ever
            // adds space — but it is measured in display cells, not chars, so a
            // CJK line does not push the edge out.
            if bordered {
                let used = 2 + display_width(&shown) as usize;
                out.push(Span::styled(
                    " ".repeat(width.saturating_sub(used + 2)) + " \u{2502}",
                    dim,
                ));
            }
            out
        }
    };
    frame.render_widget(
        Paragraph::new(Line::from(spans)).style(Style::default().bg(bg)),
        rect,
    );
}

/// Shorten `s` to at most `cells` display columns, marking the cut with `…`.
///
/// Counts DISPLAY width, not characters, so a CJK label is elided at the right
/// place rather than one that merely has the right number of chars.
fn elide(s: &str, cells: usize) -> String {
    if display_width(s) as usize <= cells {
        return s.to_string();
    }
    if cells <= 1 {
        return "\u{2026}".to_string();
    }
    let mut out = String::new();
    let mut w = 0usize;
    for c in s.chars() {
        let cw = display_width(&c.to_string()) as usize;
        if w + cw > cells - 1 {
            break;
        }
        out.push(c);
        w += cw;
    }
    out.push('\u{2026}');
    out
}

/// A continuation row's hanging indent, measured from the TEXT COLUMN.
///
/// `VisualRow::hanging` is the item's content column measured from the LINE's
/// own left edge — and a revealed line's left edge is `gutter_shift` columns to
/// the left of the text column. Subtracting that shift is what makes a wrapped
/// task line up under its own text instead of four columns right of it.
fn hang_x(app: &App, cache: &RenderCache, lay: &Layout, row: &VisualRow) -> u16 {
    if row.hanging == 0 {
        return 0;
    }
    let line_shift = gutter_shift(app, cache, lay, row.line(), 0);
    row.hanging.saturating_sub(line_shift).min(lay.measure)
}

/// Whether this line belongs to a fenced code block — its delimiters included,
/// so the slab and the bar run the block's whole height rather than stopping a
/// row short at each end.
fn in_fence(cache: &RenderCache, line: usize) -> bool {
    cache.entry(line).is_some_and(|e| {
        matches!(
            e.block,
            BlockKind::FenceOpen(_) | BlockKind::FenceBody { .. } | BlockKind::FenceClose
        )
    })
}

/// Columns the line-number gutter reserves — digits for the largest number it
/// could show, plus one column of air before the text — zero when numbers are
/// off, or when the margin has no room for them, so a narrow pane (or
/// `align = "left"`'s fixed 2-column margin) simply goes without rather than
/// drawing into the text.
fn number_gutter_width(mode: NumberMode, line_count: usize, margin_left: u16) -> u16 {
    if !mode.is_on() {
        return 0;
    }
    let digits = line_count.max(1).to_string().len() as u16;
    if digits < margin_left { digits + 1 } else { 0 }
}

/// The line-number gutter, right-aligned against the text column with one
/// blank column of air before it. Only the row that STARTS a buffer line
/// gets one — a wrapped continuation carries no number, the way a reader
/// wrapping their eyes down a paragraph in Vim finds it blank too.
fn render_line_number(frame: &mut Frame, app: &App, gutter: Rect, mode: NumberMode, line: usize, cursor_line: usize) {
    let n = if mode == NumberMode::Relative {
        line.abs_diff(cursor_line)
    } else {
        line + 1
    };
    let color = if line == cursor_line { app.theme.text } else { app.theme.text_dim };
    let style = Style::default()
        .fg(color.to_ratatui())
        .bg(app.theme.background.to_ratatui());
    let digits = gutter.width as usize;
    frame.render_widget(Paragraph::new(Span::styled(format!("{n:>digits$}"), style)), gutter);
}

/// The colored left gutter bar beside a fenced row (SPEC.md §5.3).
///
/// It hangs in the LEFT MARGIN, one column outside the measure, for the same
/// reason `stable_gutter` puts revealed markers there: a bar inside the measure
/// would cost the code a column and move it relative to the prose around it.
/// Nothing is concealed to make room, so it needs no conceal map and the active
/// line keeps its 1:1 source mapping.
fn render_fence_bar(frame: &mut Frame, app: &App, row: Rect) {
    let glyph = &app.config.glyphs.fence_bar;
    if glyph.is_empty() || row.x == 0 {
        return;
    }
    let style = Style::default()
        .fg(app.theme.fence_bar.to_ratatui())
        .bg(app.theme.background.to_ratatui());
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(glyph.clone(), style))),
        Rect { x: row.x - 1, y: row.y, width: 1, height: 1 },
    );
}

/// The 1-column vertical position indicator in the right margin (SPEC.md §6).
///
/// Not a scrollbar: no trough, no arrows, and it is ABSENT whenever the whole
/// document fits on screen — there is nothing to convey then, and a permanent
/// rail is exactly the chrome SPEC §1 rules out. It appears only once the text
/// overflows, which makes it read as information rather than furniture.
///
/// It sits at the pane's own right edge, so in a split each pane answers for
/// itself, and the thumb covers the visible fraction of the document.
fn render_scroll_hint(
    frame: &mut Frame,
    app: &App,
    rect: Rect,
    text_area: &Rect,
    top: usize,
    total: usize,
) {
    let glyph = &app.config.glyphs.scroll_hint;
    let height = text_area.height as usize;
    if !app.config.layout.scroll_hint || glyph.is_empty() || total <= height || height == 0 {
        return;
    }
    // A wide pane has margin to spare; a pane narrowed until the margin is gone
    // would have the hint sitting on the text, so it yields instead.
    if rect.right() <= text_area.right() {
        return;
    }

    // Thumb length is the visible fraction, floored at one row so a very long
    // document still shows something. Its offset spreads the remaining rows
    // over the scrollable range, so the last screenful lands flush at the
    // bottom instead of a row short.
    let len = ((height * height) / total).max(1).min(height);
    let span = total - height; // non-zero: the overflow test above guarantees it
    let offset = (top.min(span) * (height - len) + span / 2) / span;

    let style = Style::default().fg(app.theme.text_dim.to_ratatui());
    let thumb: Vec<Line> = (0..len)
        .map(|_| Line::from(Span::styled(glyph.clone(), style)))
        .collect();
    frame.render_widget(
        Paragraph::new(thumb),
        Rect {
            x: rect.right() - 1,
            y: text_area.y + offset as u16,
            width: 1,
            height: len as u16,
        },
    );
}

/// Columns to hang a revealed line's markers into, left of the text column.
///
/// `layout.stable_gutter`: the active line renders raw, so `## ` reappears and
/// would push its own text three columns right. Drawing that line shifted left
/// by exactly the width the markers took back keeps the BODY text in the same
/// column whether the line is active or not — zero horizontal jitter as the
/// cursor moves through a document (SPEC.md §6, "Reveal shift").
///
/// Only the first row of a line shifts: a wrapped continuation carries no
/// markers, so it already sits where it belongs.
fn gutter_shift(app: &App, cache: &RenderCache, lay: &Layout, line: usize, start_col: usize) -> u16 {
    if !app.config.layout.stable_gutter
        || !cache.conceal_on()
        || cache.is_concealed(line)
        || start_col != 0
    {
        return 0;
    }
    let Some(entry) = cache.entry(line) else {
        return 0;
    };
    entry.cmap.leading_shift(&entry.source).min(lay.margin_left)
}

/// The tree pane width for this frame (0 when closed), capped to half the width.
fn tree_width(app: &App, area: Rect) -> u16 {
    if app.tree.is_some() {
        crate::tree::WIDTH.min(area.width / 2)
    } else {
        0
    }
}

/// Draw the file-tree pane: a scrollable list with a right separator, the
/// selected row highlighted, and (when focused) the caret on that row.
fn render_tree(frame: &mut Frame, app: &App, tree: &FileTree, rect: Rect) {
    let theme = &app.theme;
    let block = Block::default()
        .borders(Borders::RIGHT)
        .border_style(Style::default().fg(theme.text_dim.to_ratatui()))
        .style(Style::default().bg(theme.background.to_ratatui()));
    let inner = block.inner(rect);
    frame.render_widget(Clear, rect);
    frame.render_widget(block, rect);
    if inner.width == 0 || inner.height == 0 {
        return;
    }

    let h = inner.height as usize;
    let len = tree.entries.len();
    let start = if len <= h {
        0
    } else {
        tree.selected.saturating_sub(h / 2).min(len - h)
    };
    let width = inner.width as usize;

    let mut lines: Vec<Line> = Vec::with_capacity(h);
    for (i, e) in tree.entries.iter().enumerate().skip(start).take(h) {
        lines.push(tree_row(app, tree, e, i == tree.selected, width));
    }
    frame.render_widget(
        Paragraph::new(lines).style(Style::default().bg(theme.background.to_ratatui())),
        inner,
    );

    if tree.focused {
        let row = tree.selected.saturating_sub(start);
        frame.set_cursor_position(Position::new(inner.x, inner.y + row as u16));
    }
}

/// One tree row: `│  ├╴  name`, Neo-tree style — the guide columns its
/// ancestors still occupy, an elbow into this entry, its icon, and the name.
///
/// Everything is padded out to the pane width so the selected row's background
/// covers it end to end. Names too long for the pane are cut, not wrapped: a
/// tree row is one line by definition.
fn tree_row<'a>(app: &App, tree: &FileTree, e: &Entry, selected: bool, width: usize) -> Line<'a> {
    let theme = &app.theme;
    let glyphs = &app.config.glyphs;
    let nerd = glyphs.nerd_fonts;

    let sel_bg = |s: Style| {
        if selected {
            s.bg(theme.selection.to_ratatui())
        } else {
            s
        }
    };

    // --- the guide columns, then the elbow into this row ---
    let mut prefix = String::new();
    for &running in &e.guides {
        prefix.push_str(if running { "│ " } else { "  " });
    }
    if e.depth > 0 {
        prefix.push_str(if e.last { "└╴" } else { "├╴" });
    }

    // --- the icon: open/closed folder, or the file type's own glyph ---
    let (icon, icon_color) = if e.is_dir {
        let open = tree.is_expanded(&e.path);
        let glyph = match (nerd, open) {
            (true, true) => glyphs.folder_open.as_str(),
            (true, false) => glyphs.folder.as_str(),
            (false, true) => "▾",
            (false, false) => "▸",
        };
        (glyph.to_string(), theme.link)
    } else if nerd {
        let (glyph, kind) = crate::tree::file_icon(&e.name);
        (glyph.to_string(), icon_color(theme, kind))
    } else {
        // Without a Nerd Font a file gets no glyph, but still needs the column
        // the sibling directories' arrows take, or the names zigzag.
        (" ".to_string(), theme.text_dim)
    };

    let mut name_style = Style::default().fg(if e.is_dir { theme.link } else { theme.text }.to_ratatui());
    if e.is_dir {
        name_style = name_style.add_modifier(Modifier::BOLD);
    }

    // --- assemble, truncating the NAME (never the guides) to fit ---
    let fixed = prefix.chars().count() + icon.chars().count() + 1;
    let room = width.saturating_sub(fixed);
    let name: String = if e.name.chars().count() > room {
        e.name.chars().take(room).collect()
    } else {
        e.name.clone()
    };
    let pad = width.saturating_sub(fixed + name.chars().count());

    Line::from(vec![
        Span::styled(
            prefix,
            sel_bg(Style::default().fg(theme.text_dim.to_ratatui()).add_modifier(Modifier::DIM)),
        ),
        Span::styled(icon, sel_bg(Style::default().fg(icon_color.to_ratatui()))),
        Span::styled(" ", sel_bg(Style::default())),
        Span::styled(name, sel_bg(name_style)),
        Span::styled(" ".repeat(pad), sel_bg(Style::default())),
    ])
}

/// Draw the `:diff` conflict view: the buffer on the left, the file on the
/// right, aligned row for row.
///
/// The alignment is already computed (`diff::align`), so this only has to place
/// it: one screen row per `diff::Row`, a filler bar where a side has no line,
/// and the whole line coloured the way `git diff` colours it. Both columns read
/// the SAME scroll offset, which is what makes them stay in step without any
/// notion of bound scrolling.
fn render_diff(frame: &mut Frame, app: &App, view: &crate::diff::DiffView, area: Rect) {
    use crate::diff::Row;

    let theme = &app.theme;
    let accent = theme.link.to_ratatui();
    let dim = theme.text_dim.to_ratatui();
    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(accent))
        .style(Style::default().bg(theme.background.to_ratatui()))
        .title(Span::styled(
            format!(" diff: {} ", view.name),
            Style::default().fg(accent).add_modifier(Modifier::BOLD),
        ))
        .title_bottom(
            Line::from(Span::styled(
                " Tab cycle · n p difference · l f b all · w commit · q abort ",
                Style::default().fg(dim),
            ))
            .right_aligned(),
        );
    let inner = block.inner(area);
    frame.render_widget(Clear, area);
    frame.render_widget(block, area);
    if inner.width < 8 || inner.height < 2 {
        return;
    }

    // A header row naming the sides, then the rows themselves. The divider
    // takes one cell, so the two halves split what is left.
    let side = (inner.width as usize - 1) / 2;
    let right_w = inner.width as usize - 1 - side;
    let head = Rect { height: 1, ..inner };
    let body = Rect {
        y: inner.y + 1,
        height: inner.height - 1,
        ..inner
    };

    let pad = |s: String, w: usize| -> String {
        let mut out = elide(&s, w);
        let used = display_width(&out) as usize;
        out.push_str(&" ".repeat(w.saturating_sub(used)));
        out
    };
    frame.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled(pad(" live — in the editor".into(), side), Style::default().fg(dim)),
            Span::styled("│", Style::default().fg(dim)),
            Span::styled(pad(" file — on disk".into(), right_w), Style::default().fg(dim)),
        ])),
        head,
    );

    // The filler bar: a row where this side has no line at all. Drawn rather
    // than left blank, so a reader can tell "nothing here" from "an empty line
    // here" — which in Markdown is a meaningful difference.
    let filler = |w: usize| "\u{2504}".repeat(w);
    let current = view.align.hunks.get(view.hunk).cloned();

    let mut lines: Vec<Line> = Vec::with_capacity(body.height as usize);
    for i in 0..body.height as usize {
        let row_index = view.scroll + i;
        let Some(row) = view.align.rows.get(row_index) else {
            break;
        };
        let (colour, marks) = match row {
            Row::Same { .. } => (theme.text.to_ratatui(), (' ', ' ')),
            Row::Changed { .. } => (theme.diff_change.to_ratatui(), ('~', '~')),
            Row::Added { .. } => (theme.diff_add.to_ratatui(), (' ', '+')),
            Row::Removed { .. } => (theme.diff_remove.to_ratatui(), ('-', ' ')),
        };
        // The divider carries BOTH facts at once: its glyph points at the side
        // this difference keeps, and its colour says whether this is the
        // difference `n` / `p` last landed on. Two columns of chrome for that
        // would cost more width than the text can spare.
        let here = current.as_ref().is_some_and(|h| h.contains(&row_index));
        let chosen = view.side_at(row_index);
        let bar = match chosen {
            Some(s) => Span::styled(
                s.glyph().to_string(),
                match here {
                    true => Style::default().fg(accent).add_modifier(Modifier::BOLD),
                    false => Style::default().fg(dim),
                },
            ),
            None => Span::styled("│".to_string(), Style::default().fg(dim)),
        };

        // A side that loses the merge is DIMMED, so the surviving document can
        // be read straight down the screen. `Both` dims neither, which is why
        // "both kept" needs no visual vocabulary of its own.
        let keeps = |mine: bool| match chosen {
            None => true,
            Some(crate::diff::Side::Both) => true,
            Some(crate::diff::Side::Live) => mine,
            Some(crate::diff::Side::File) => !mine,
        };
        let text = |line: Option<usize>,
                    from: &[String],
                    mark: char,
                    w: usize,
                    live: bool|
         -> Span<'static> {
            match line {
                Some(n) => Span::styled(
                    pad(format!("{mark}{}", from.get(n).cloned().unwrap_or_default()), w),
                    match keeps(live) {
                        true => Style::default().fg(colour),
                        false => Style::default().fg(dim).add_modifier(Modifier::CROSSED_OUT),
                    },
                ),
                None => Span::styled(filler(w), Style::default().fg(dim)),
            }
        };
        lines.push(Line::from(vec![
            text(row.left(), &view.mine, marks.0, side, true),
            bar,
            text(row.right(), &view.theirs, marks.1, right_w, false),
        ]));
    }
    frame.render_widget(Paragraph::new(lines), body);
}

/// Draw the `:help` overlay: a near-full-screen bordered panel with the scrolled
/// help text and a hint in the title bar.
fn render_help(frame: &mut Frame, app: &App, help: &Help, area: Rect) {
    let theme = &app.theme;
    let margin = 2u16;
    let rect = Rect {
        x: area.x + margin,
        y: area.y + margin.min(area.height / 4),
        width: area.width.saturating_sub(margin * 2).max(10),
        height: area.height.saturating_sub(margin * 2).max(3),
    };

    let accent = theme.link.to_ratatui();
    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(accent))
        .style(Style::default().bg(theme.background.to_ratatui()))
        .title(Span::styled(
            format!(" help: {} ", help.title),
            Style::default().fg(accent).add_modifier(Modifier::BOLD),
        ))
        .title_bottom(
            Line::from(Span::styled(
                " j/k scroll · q close ",
                Style::default().fg(theme.text_dim.to_ratatui()),
            ))
            .right_aligned(),
        );
    let inner = block.inner(rect);

    frame.render_widget(Clear, rect);
    frame.render_widget(block, rect);

    let view_h = inner.height as usize;
    let max_scroll = help.lines.len().saturating_sub(view_h);
    let scroll = help.scroll.min(max_scroll) as u16;
    let lines: Vec<Line> = help
        .lines
        .iter()
        .map(|l| Line::from(Span::styled(l.clone(), Style::default().fg(theme.text.to_ratatui()))))
        .collect();
    frame.render_widget(Paragraph::new(lines).scroll((scroll, 0)), inner);
}

/// The first and last buffer lines visible IN THE FOCUSED PANE, recomputing the
/// same geometry the renderer uses. Drives the `H`/`M`/`L` screen motions.
pub fn visible_line_range(app: &App, area: Rect) -> Option<(usize, usize)> {
    let cfg = &app.config;
    let rect = focused_rect(app, area)?;
    let lay = Layout::compute(&cfg.layout, rect.width, rect.height, 0);

    let mut cache = app.cache.borrow_mut();
    cache.sync(app, lay.measure);

    let (cursor_row, _) = cache.locate(app.buffer.cursor.line, app.buffer.cursor.col);
    let top = scroll_offset(
        cursor_row,
        cache.total_rows(),
        &lay,
        &cfg.layout,
        cfg.editor.scroll_off,
        app.scroll_hint(),
        app.view,
    );
    let first = cache.row(top)?.line();
    let last_row = (top + lay.height as usize)
        .min(cache.total_rows())
        .saturating_sub(1);
    let last = cache.row(last_row)?.line();
    Some((first, last))
}

/// The rect the focused pane occupies.
fn focused_rect(app: &App, area: Rect) -> Option<Rect> {
    app.layout
        .geometry(pane_area(app, area))
        .panes
        .into_iter()
        .find(|(id, _)| *id == app.focus_pane)
        .map(|(_, r)| r)
}

/// Which pane a screen position falls in, if any.
pub fn pane_at(app: &App, area: Rect, col: u16, row: u16) -> Option<crate::render::pane::PaneId> {
    app.layout
        .geometry(pane_area(app, area))
        .panes
        .into_iter()
        .find(|(_, r)| col >= r.x && col < r.right() && row >= r.y && row < r.bottom())
        .map(|(id, _)| id)
}

/// Map a screen position (a mouse click) back to a buffer `Cursor`, recomputing
/// the same geometry the renderer used. Returns `None` when the click is outside
/// the text area. Inverts the clicked line's conceal map so a click on a
/// concealed line lands on the right source column.
///
/// The caller is expected to have focused the clicked pane first (`pane_at`),
/// so this reads the focused pane's geometry and document.
pub fn locate_click(app: &App, area: Rect, col: u16, row: u16) -> Option<Cursor> {
    locate(app, area, col, row, false)
}

/// `locate_click` for a position reached mid-drag: outside the text area it
/// clamps to the nearest edge rather than refusing. A selection dragged past
/// the top or bottom of the pane should go on extending to the row the pointer
/// is level with — freezing at the last cell that happened to be inside reads
/// as the drag having broken.
pub fn locate_drag(app: &App, area: Rect, col: u16, row: u16) -> Option<Cursor> {
    locate(app, area, col, row, true)
}

fn locate(app: &App, area: Rect, col: u16, row: u16, clamp: bool) -> Option<Cursor> {
    let cfg = &app.config;
    let rect = focused_rect(app, area)?;
    // A click outside the pane — in the tree sidebar, say — is not a position.
    if !clamp && (col < rect.x || col >= rect.right() || row < rect.y || row >= rect.bottom()) {
        return None;
    }
    let col = col.clamp(rect.x, rect.right().saturating_sub(1));
    let row = row.clamp(rect.y, rect.bottom().saturating_sub(1));
    let ex = rect.x;
    let lay = Layout::compute(&cfg.layout, rect.width, rect.height, 0);

    let mut cache = app.cache.borrow_mut();
    cache.sync(app, lay.measure);

    let (cursor_row, _) = cache.locate(app.buffer.cursor.line, app.buffer.cursor.col);
    let top = scroll_offset(
        cursor_row,
        cache.total_rows(),
        &lay,
        &cfg.layout,
        cfg.editor.scroll_off,
        app.scroll_hint(),
        app.view,
    );

    if lay.height == 0 {
        return None;
    }
    let screen_row = if row < rect.y + lay.top {
        if !clamp {
            return None;
        }
        0
    } else {
        (row - rect.y - lay.top) as usize
    };
    let last = lay.height as usize - 1;
    if screen_row > last && !clamp {
        return None;
    }
    let screen_row = screen_row.min(last);
    // Dragging below the end of a short document lands past the last row; that
    // is the end of the text, not a miss.
    let vr = match cache.row(top + screen_row) {
        Some(vr) => vr,
        None if clamp => cache.row(cache.total_rows().checked_sub(1)?)?,
        None => return None,
    };
    let line = vr.line();

    // A click on transcluded content has no column to land on — that text is
    // in another file. It selects the `![[…]]` line that produced it, which is
    // the only thing here the reader can actually edit.
    if !vr.editable {
        return Some(Cursor::new(line, 0));
    }

    // The active line may hang its markers into the gutter, so it starts that
    // many columns to the left of the text column.
    let entry = cache.entry(line)?;
    let concealed = cache.is_concealed(line);
    let shift = gutter_shift(app, &cache, &lay, line, vr.start_col);
    let hang = hang_x(app, &cache, &lay, &vr);
    let raw_click_x = (col + shift).saturating_sub(ex + lay.margin_left + hang);

    // Undo whatever offset `text_align` drew this row with, so the click
    // still lands on the character under the pointer rather than wherever
    // `Left` would have put it.
    let table = matches!(app.blocks.kinds.get(line), Some(BlockKind::Table));
    let fenced = in_fence(&cache, line);
    let display_text = if concealed { entry.cmap.display_text(&entry.source) } else { entry.source.clone() };
    let is_last_row = vr.end_col >= display_text.chars().count();
    let align = row_align(app.text_align, fenced || table, is_last_row);
    let row_width = lay.measure + shift - hang;
    let click_x = match align {
        TextAlign::Left => raw_click_x,
        TextAlign::Center | TextAlign::Right => {
            let row_text: String =
                display_text.chars().skip(vr.start_col).take(vr.end_col - vr.start_col).collect();
            raw_click_x.saturating_sub(align::align_offset(align, display_width(&row_text), row_width))
        }
        TextAlign::Justified => {
            let row_text: String =
                display_text.chars().skip(vr.start_col).take(vr.end_col - vr.start_col).collect();
            let gaps = align::justify_gaps(&row_text, row_width);
            align::unstretch_col(&gaps, raw_click_x)
        }
    };
    let display_col = vr.start_col as u16 + click_x;

    let len = entry.source.chars().count();
    let src_col = if concealed {
        entry.cmap.source_col(&entry.source, display_col).min(len)
    } else {
        (display_col as usize).min(len)
    };

    Some(Cursor::new(line, src_col))
}

/// A centered floating input for `:` commands — the spotlight box. Drawn last,
/// over a `Clear`ed rect, owning no source↔screen mapping, so it never touches
/// the concealment machinery. SPEC.md §6 (command entry).
fn render_command_box(
    frame: &mut Frame,
    app: &App,
    title: &str,
    prompt: &str,
    buf: &str,
    area: Rect,
) {
    let theme = &app.theme;

    // Wide enough for what it has to say. A `:` box is 60 columns; a prompt
    // asking "delete notes/ and 12 entries? (y/N)" needs its own question to
    // fit, or the thing being deleted scrolls out of view.
    let wanted = 60.max(display_width(prompt) + display_width(buf) + 4);
    let width = wanted.min(area.width.saturating_sub(4)).max(20);
    let height = 3u16;
    let x = area.x + area.width.saturating_sub(width) / 2;
    // Upper third — spotlight placement, clear of the text the user was editing.
    let y = area.y + (area.height / 3).min(area.height.saturating_sub(height));
    let rect = Rect { x, y, width, height };
    app.overlay.set(Some(rect));

    let accent = spotlight_accent(app);
    let block = spotlight_block(app, accent, title);
    let inner = block.inner(rect);

    frame.render_widget(Clear, rect);
    frame.render_widget(block, rect);

    let line = Line::from(vec![
        Span::styled(prompt.to_string(), Style::default().fg(accent.to_ratatui())),
        Span::styled(
            buf.to_string(),
            Style::default()
                .fg(theme.text.to_ratatui())
                .add_modifier(Modifier::BOLD),
        ),
    ]);
    frame.render_widget(Paragraph::new(line), inner);

    // Caret after the typed text, clamped inside the box. Measured from the
    // prompt's own width — it is one cell for `:` and a whole question for a
    // tree prompt.
    let cx = (inner.x + display_width(prompt) + display_width(buf))
        .min(inner.x + inner.width.saturating_sub(1));
    frame.set_cursor_position(Position::new(cx, inner.y));
}

/// What a tree prompt asks, in words. The path is shown RELATIVE to the tree
/// root — an absolute path in a 60-column box is mostly directories the reader
/// already knows they are in.
fn prompt_label(app: &App, p: &Prompt) -> String {
    let shown = |path: &std::path::Path| {
        app.tree
            .as_ref()
            .map(|t| t.relative(path))
            .unwrap_or_else(|| path.display().to_string())
    };
    match &p.kind {
        PromptKind::Create => format!("{}/", shown(&p.target)),
        PromptKind::Rename => "name: ".to_string(),
        PromptKind::Move => "to: ".to_string(),
        PromptKind::Export { format, justify } => {
            let mode = if *justify { " (justified)" } else { "" };
            format!("{}{mode} to: ", format.name())
        }
        PromptKind::Delete { entries } => {
            let what = shown(&p.target);
            // The count is the point: `d` on a directory row takes everything
            // under it, and the number is the only warning of that.
            if *entries > 1 {
                format!("delete {what} and {} entries inside? (y/N) ", entries - 1)
            } else {
                format!("delete {what}? (y/N) ")
            }
        }
    }
}

/// A spotlight box is the focus while it's open, so it renders bright — an
/// accent border and title against the dimmed buffer behind it — turning to the
/// error color when a flash is up.
fn spotlight_accent(app: &App) -> ThemeColor {
    match app.flash.as_ref().map(|f| &f.kind) {
        Some(FlashKind::Error) => app.theme.error,
        _ => app.theme.link,
    }
}

fn spotlight_block<'a>(app: &App, accent: ThemeColor, title: &'a str) -> Block<'a> {
    let bold_accent = Style::default()
        .fg(accent.to_ratatui())
        .add_modifier(Modifier::BOLD);
    Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(bold_accent)
        .style(Style::default().bg(app.theme.background.to_ratatui()))
        .title(Span::styled(title, bold_accent))
}

/// The fuzzy finder overlay (`<leader>ff`): the spotlight box with the query on
/// its first row and the matching paths listed under it, matched characters
/// picked out in the accent color. Like the command box it is drawn last over a
/// `Clear`ed rect and owns no source↔screen mapping.
fn render_finder(frame: &mut Frame, app: &App, finder: &Finder, area: Rect) {
    let theme = &app.theme;
    let accent = spotlight_accent(app);
    let width = 60u16.min(area.width.saturating_sub(4)).max(20);
    let inner_w = width.saturating_sub(2) as usize;

    // --- query row: `> typed`, with the match count right-aligned ---
    let typed = format!("> {}", finder.query);
    let count = format!(
        "{}/{}{}",
        finder.matches.len(),
        finder.file_count(),
        if finder.truncated { "+" } else { "" }
    );
    let gap = inner_w.saturating_sub(typed.chars().count() + count.chars().count());
    let mut lines = vec![Line::from(vec![
        Span::styled("> ", Style::default().fg(accent.to_ratatui())),
        Span::styled(
            finder.query.clone(),
            Style::default()
                .fg(theme.text.to_ratatui())
                .add_modifier(Modifier::BOLD),
        ),
        Span::raw(" ".repeat(gap)),
        Span::styled(
            count,
            Style::default()
                .fg(theme.text_dim.to_ratatui())
                .add_modifier(Modifier::DIM),
        ),
    ])];

    // --- result rows, scrolled to keep the selection in view ---
    let len = finder.matches.len();
    let shown = len.min(VISIBLE_ROWS);
    let start = if len <= VISIBLE_ROWS {
        0
    } else {
        finder.selected.saturating_sub(VISIBLE_ROWS / 2).min(len - VISIBLE_ROWS)
    };
    for i in start..start + shown {
        let Some((rel, positions)) = finder.row(i) else {
            continue;
        };
        lines.push(result_line(app, rel, positions, i == finder.selected, inner_w));
    }
    if len == 0 {
        lines.push(Line::from(Span::styled(
            "  no matching files",
            Style::default()
                .fg(theme.text_dim.to_ratatui())
                .add_modifier(Modifier::DIM),
        )));
    }

    let height = (lines.len() as u16 + 2).min(area.height);
    let x = area.x + area.width.saturating_sub(width) / 2;
    // Upper third, like the command box — the results grow downward from there.
    let y = area.y + (area.height / 3).min(area.height.saturating_sub(height));
    let rect = Rect { x, y, width, height };
    app.overlay.set(Some(rect));

    let block = spotlight_block(app, accent, " find ");
    let inner = block.inner(rect);
    frame.render_widget(Clear, rect);
    frame.render_widget(block, rect);
    frame.render_widget(Paragraph::new(lines), inner);

    let cx = (inner.x + 2 + display_width(&finder.query)).min(inner.x + inner.width.saturating_sub(1));
    frame.set_cursor_position(Position::new(cx, inner.y));
}

/// One result row: the path padded to the box width (so the selection's
/// background covers the whole row), with the query's matched characters in the
/// accent color. A path too long for the box loses its HEAD, not its tail —
/// the file name is the part you are reading.
fn result_line<'a>(
    app: &App,
    rel: &str,
    positions: &[usize],
    selected: bool,
    width: usize,
) -> Line<'a> {
    let theme = &app.theme;
    let accent = spotlight_accent(app);

    let base = if selected {
        Style::default()
            .fg(theme.text.to_ratatui())
            .bg(theme.selection.to_ratatui())
    } else {
        Style::default().fg(theme.text_dim.to_ratatui())
    };
    let hit = base.fg(accent.to_ratatui()).add_modifier(Modifier::BOLD);

    // Marker, then the same file-type icon the tree draws — read from the FILE
    // NAME, not the whole relative path, or a dotted directory would decide it.
    let mut spans = vec![Span::styled(if selected { "▸ " } else { "  " }, base)];
    let mut lead = 2;
    if app.config.glyphs.nerd_fonts {
        let name = rel.rsplit_once('/').map(|(_, n)| n).unwrap_or(rel);
        let (glyph, kind) = crate::tree::file_icon(name);
        spans.push(Span::styled(
            format!("{glyph} "),
            base.fg(icon_color(theme, kind).to_ratatui()),
        ));
        lead += 2;
    }

    // The path fills what is left; too long, and it loses its head, not the
    // file name at the end.
    let avail = width.saturating_sub(lead);
    let chars: Vec<char> = rel.chars().collect();
    let (skipped, elided) = if chars.len() > avail && avail > 1 {
        (chars.len() - (avail - 1), true)
    } else {
        (0, false)
    };
    if elided {
        spans.push(Span::styled("…", base));
    }
    for (i, c) in chars.iter().enumerate().skip(skipped) {
        let style = if positions.contains(&i) { hit } else { base };
        spans.push(Span::styled(c.to_string(), style));
    }
    let drawn = lead + usize::from(elided) + (chars.len() - skipped);
    spans.push(Span::styled(" ".repeat(width.saturating_sub(drawn)), base));
    Line::from(spans)
}

/// The theme color a file-type icon wears. Shared by the tree and the finder so
/// one file reads the same in both.
fn icon_color(theme: &crate::render::theme::Theme, kind: IconKind) -> ThemeColor {
    match kind {
        IconKind::Prose => theme.headings[0],
        IconKind::Code => theme.code,
        IconKind::Data => theme.tag,
        IconKind::Media => theme.wiki_link,
        IconKind::Plain => theme.text_dim,
    }
}


/// One source line's rendered form: the display string plus styled spans over
/// it. For an active or conceal-disabled line the text equals the source; for a
/// concealed line the markers are gone and the spans are re-indexed onto the
/// shorter string.
struct DisplayLine {
    text: String,
    spans: Vec<StyledSpan>,
}

/// Turn one cached line into its display form for THIS frame: the parse comes
/// from the cache, and everything frame-local — focus dim, the command-box dim,
/// search matches, the Visual selection — is overlaid on a copy of it.
///
/// The overlays are applied in SOURCE coordinates, before concealment remaps
/// them, which is what lets a search match inside `**bold**` land on the right
/// display column with no coordinate arithmetic here.
fn display_line_of(
    app: &App,
    doc: &crate::app::BufferState,
    cache: &RenderCache,
    line: usize,
    focused: bool,
) -> DisplayLine {
    // Overlays that follow the CURSOR (focus dim, the Visual selection) apply
    // only in the focused pane; ones that follow the TEXT (search matches)
    // apply wherever that text is shown. `doc` is what tells the two apart when
    // the same document is open in several panes.
    let _ = doc;
    let Some(entry) = cache.entry(line) else {
        return DisplayLine {
            text: String::new(),
            spans: Vec::new(),
        };
    };
    let source = &entry.source;
    let mut styled = entry.styled.clone();

    // Focus mode dims everything outside the current paragraph/sentence. It
    // follows the CURSOR, so it belongs to the focused pane only. Applied in
    // SOURCE coordinates so concealment's remap carries it through, and to both
    // active and concealed lines alike. SPEC.md §6.
    if let Some(region) = app.focus_region.as_ref().filter(|_| focused) {
        apply_focus_dim(&mut styled, source.chars().count(), region, line);
    }

    // While a spotlight box is open — command, search, or the finder — dim the
    // whole buffer behind it so the box reads as the focus of attention.
    if matches!(app.mode, Mode::Command(_) | Mode::Search { .. }) || app.finder.is_some() {
        overlay_dim(&mut styled, 0..source.chars().count());
    }

    // A search match is a property of the TEXT, so it lights up in every pane
    // showing this document.
    // Highlight every search match on this line (source coords, pre-conceal).
    if let Some(search) = &app.search {
        let needle: Vec<char> = search.pattern.chars().collect();
        let hay: Vec<char> = source.chars().collect();
        let mut i = 0;
        while let Some(pos) = find_sub(&hay, &needle, i) {
            overlay_bg(&mut styled, pos..pos + needle.len(), app.theme.search_match);
            i = pos + needle.len();
        }
    }

    // Raw 1:1 when the line is active, when the user turned concealment off, or
    // for non-Markdown buffers — the SPEC §2 invariant plus its escape hatch.
    // The cache settled that when it built this frame's row index.
    if !cache.is_concealed(line) {
        // A Visual selection paints its background over the raw text.
        if let Some((s, e)) = selection_cols(app, line, source.chars().count()).filter(|_| focused) {
            overlay_bg(&mut styled, s..e, app.theme.selection);
        }
        return DisplayLine {
            text: source.clone(),
            spans: styled,
        };
    }

    let (text, spans) = entry.cmap.render(source, &styled);
    DisplayLine { text, spans }
}

/// The selected char columns on `line`, if a Visual selection covers it.
/// VisualLine selects the whole line; Visual is inclusive of the cursor char.
fn selection_cols(app: &App, line: usize, len: usize) -> Option<(usize, usize)> {
    if !matches!(app.mode, Mode::Visual | Mode::VisualLine) {
        return None;
    }
    let anchor = app.anchor?;
    let cursor = app.buffer.cursor;
    let (lo, hi) = if (anchor.line, anchor.col) <= (cursor.line, cursor.col) {
        (anchor, cursor)
    } else {
        (cursor, anchor)
    };
    if line < lo.line || line > hi.line {
        return None;
    }
    if matches!(app.mode, Mode::VisualLine) {
        return Some((0, len));
    }
    let start = if line == lo.line { lo.col } else { 0 };
    let end = if line == hi.line { hi.col + 1 } else { len };
    Some((start.min(len), end.min(len)))
}

/// Repaint the background of `range` (char columns) across the line's spans,
/// splitting spans at the boundaries. Keeps the cover gap-free.
fn overlay_bg(spans: &mut Vec<StyledSpan>, range: std::ops::Range<usize>, bg: ThemeColor) {
    overlay(spans, range, |style| style.bg = bg);
}

/// De-emphasize `range` with the faint attribute, KEEPING its colors — so focus
/// mode dims a paragraph's intensity without flattening its syntax highlighting.
fn overlay_dim(spans: &mut Vec<StyledSpan>, range: std::ops::Range<usize>) {
    overlay(spans, range, |style| style.attrs.dim = true);
}

/// Apply a style tweak to the char columns in `range`, splitting spans at the
/// boundaries so the cover stays gap-free and non-overlapping.
fn overlay(
    spans: &mut Vec<StyledSpan>,
    range: std::ops::Range<usize>,
    tweak: impl Fn(&mut crate::render::theme::Style),
) {
    if range.start >= range.end {
        return;
    }
    let mut out = Vec::with_capacity(spans.len() + 2);
    for sp in spans.drain(..) {
        let (s, e) = (sp.range.start, sp.range.end);
        let a = range.start.max(s);
        let b = range.end.min(e);
        if a >= b {
            out.push(sp);
            continue;
        }
        if s < a {
            out.push(StyledSpan { range: s..a, style: sp.style });
        }
        let mut mid = sp.style;
        tweak(&mut mid);
        out.push(StyledSpan { range: a..b, style: mid });
        if b < e {
            out.push(StyledSpan { range: b..e, style: sp.style });
        }
    }
    *spans = out;
}

/// First index at or after `from` where `needle` occurs in `hay` (empty needle
/// never matches).
fn find_sub(hay: &[char], needle: &[char], from: usize) -> Option<usize> {
    if needle.is_empty() || needle.len() > hay.len() || from > hay.len() - needle.len() {
        return None;
    }
    (from..=hay.len() - needle.len()).find(|&i| hay[i..i + needle.len()] == needle[..])
}

/// Faintly de-emphasize the source columns of `line` that fall outside the
/// focus region, keeping their colors.
fn apply_focus_dim(spans: &mut Vec<StyledSpan>, len: usize, region: &FocusRegion, line: usize) {
    if line < region.start.line || line > region.end.line {
        overlay_dim(spans, 0..len);
        return;
    }
    let keep_start = if line == region.start.line { region.start.col } else { 0 };
    let keep_end = if line == region.end.line { region.end.col.min(len) } else { len };
    if keep_start > 0 {
        overlay_dim(spans, 0..keep_start.min(len));
    }
    if keep_end < len {
        overlay_dim(spans, keep_end..len);
    }
}

/// Clip a line's styled spans to one visual row's char window and lower them to
/// ratatui spans, pulling display text from the source. Spans arrive ordered,
/// gap-free, and non-overlapping, so the clip preserves those properties.
/// The alignment a row actually draws with: `Left` when it is not eligible —
/// a fenced code line (its columns are code) or a table row (its `|`s are the
/// author's own layout, already left as `no_wrap`) — or when `Justified`
/// would apply to a paragraph's own LAST row, which stays ragged by
/// definition. That last exception is the one thing that turns "stretch
/// every line" into "justified".
fn row_align(align: TextAlign, ineligible: bool, is_last_row: bool) -> TextAlign {
    if ineligible || (align == TextAlign::Justified && is_last_row) {
        return TextAlign::Left;
    }
    align
}

/// Insert the extra spaces `align::justify_gaps` computed, splitting a span at
/// each gap so the inserted padding carries no style of its own — the words
/// on either side keep exactly the style they already had.
fn stretch_spans(spans: Vec<Span<'static>>, gaps: &[(usize, u16)]) -> Vec<Span<'static>> {
    let mut out = Vec::with_capacity(spans.len() + gaps.len());
    let mut idx = 0usize;
    let mut next_gap = 0usize;
    for span in spans {
        let mut buf = String::new();
        for ch in span.content.chars() {
            buf.push(ch);
            idx += 1;
            if next_gap < gaps.len() && idx == gaps[next_gap].0 + 1 {
                out.push(Span::styled(std::mem::take(&mut buf), span.style));
                out.push(Span::raw(" ".repeat(gaps[next_gap].1 as usize)));
                next_gap += 1;
            }
        }
        if !buf.is_empty() {
            out.push(Span::styled(buf, span.style));
        }
    }
    out
}

fn window_spans(source: &str, styled: &[StyledSpan], start: usize, end: usize) -> Vec<Span<'static>> {
    let chars: Vec<char> = source.chars().collect();
    let end = end.min(chars.len());
    let mut out = Vec::new();
    for sp in styled {
        let s = sp.range.start.max(start);
        let e = sp.range.end.min(end);
        if s >= e {
            continue;
        }
        let text: String = chars[s..e].iter().collect();
        out.push(Span::styled(text, sp.style.to_ratatui()));
    }
    out
}

/// The status line is hidden by default and appears only transiently — after a
/// save, a mode change, or an error — then fades. Command entry has its own
/// spotlight box (`render_command_box`), so it is not echoed here. SPEC.md §6.
fn status_text(app: &App) -> Option<String> {
    if matches!(app.mode, Mode::Command(_) | Mode::Search { .. }) || app.finder.is_some() {
        return None;
    }

    let flash = app.flash.as_ref()?;
    if let Some(text) = flash.text.as_ref() {
        return Some(text.clone());
    }

    let mut parts: Vec<String> = Vec::new();
    for item in &app.config.status.show {
        match item.as_str() {
            // The conflict marker rides on the FILENAME rather than being its
            // own `[status] show` item: it is a fact about this file, and it
            // must not be switchable off by a preference about the modified
            // dot. `elide` in `render` still bounds the whole line.
            "file" => {
                let mut name = app.buffer.display_name();
                let marker = &app.config.glyphs.conflict;
                if app.buffer.conflict && !marker.is_empty() {
                    name.push(' ');
                    name.push_str(marker);
                }
                parts.push(name);
            }
            "modified" if app.buffer.modified => parts.push(app.config.glyphs.modified.clone()),
            "position" => parts.push(format!(
                "{}:{}",
                app.buffer.cursor.line + 1,
                app.buffer.cursor.col + 1
            )),
            "words" => parts.push(format!("{} words", app.buffer.word_count())),
            _ => {}
        }
    }

    if parts.is_empty() {
        None
    } else {
        Some(parts.join("  ·  "))
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::App;
    use crate::config::Config;
    use crate::render::markdown::block::BlockCache;
    use crate::render::theme::Color;
    use crate::text::cursor::Cursor;
    use ratatui::backend::TestBackend;
    use ratatui::Terminal;

    fn app_with(text: &str) -> App {
        let mut app = App::new(Config::default(), None, None).unwrap();
        pin_theme(&mut app);
        app.buffer.insert_str(Cursor::new(0, 0), text);
        app.blocks = BlockCache::build(&app.buffer);
        app
    }

    /// Give the app the palette AS AUTHORED, instead of the one the developer's
    /// terminal happens to support.
    ///
    /// `App::new` builds its theme with `Theme::from_config`, which ends in
    /// `adapt(detect_depth())` — a read of `COLORTERM` and `TERM`. Several
    /// tests below assert that two roles render in DIFFERENT colors, and that
    /// is only true of the authored palette: downgraded to 16 colors, distinct
    /// RGB roles legitimately collapse onto the same slot, and `assert_ne!`
    /// fails with the two sides printing identically. A renderer test must test
    /// the renderer, not the terminal it is being run from.
    fn pin_theme(app: &mut App) {
        let theme = crate::render::theme::Theme::authored(&app.config.theme).unwrap();
        app.theme = theme;
    }

    fn render_to(app: &App, w: u16, h: u16) -> ratatui::buffer::Buffer {
        let mut terminal = Terminal::new(TestBackend::new(w, h)).unwrap();
        terminal.draw(|f| render(f, app)).unwrap();
        terminal.backend().buffer().clone()
    }

    /// The rows of a drawn frame, trimmed — what the reader actually sees.
    fn rows(buf: &ratatui::buffer::Buffer) -> Vec<String> {
        (0..buf.area.height)
            .map(|y| {
                (0..buf.area.width)
                    .map(|x| buf[(x, y)].symbol())
                    .collect::<String>()
                    .trim_end()
                    .to_string()
            })
            .collect()
    }

    /// Highlighting survives the whole draw path — the conceal render, the
    /// window into the row, the slab painted under it — and not just the cache.
    #[test]
    fn a_highlighted_fence_reaches_the_screen() {
        let app = app_with("```rust\nlet s = \"hi\";\n```\n");
        let buf = render_to(&app, 80, 12);

        let row = (0..buf.area.height)
            .find(|y| (0..buf.area.width).any(|x| buf[(x, *y)].symbol() == "l"))
            .expect("the body line is on screen");
        let colors: Vec<ratatui::style::Color> = (0..buf.area.width)
            .map(|x| &buf[(x, row)])
            .filter(|c| !c.symbol().trim().is_empty())
            .map(|c| c.fg)
            .collect();

        assert!(colors.contains(&app.theme.syntax_keyword.to_ratatui()), "`let` is a keyword");
        assert!(colors.contains(&app.theme.syntax_string.to_ratatui()), "`\"hi\"` is a string");
        // The slab runs the full measure regardless.
        let bg = app.theme.code_bg.to_ratatui();
        assert!((0..buf.area.width).filter(|x| buf[(*x, row)].bg == bg).count() >= 40);
    }

    /// Line spacing reaches the SCREEN: a blank row between the lines of a
    /// paragraph, and no second one after the blank line that separates two.
    #[test]
    fn line_spacing_draws_air_between_lines() {
        let mut app = app_with("alpha\nbravo\n\ncharlie\n");
        app.config.layout.line_spacing = 1;
        let drawn = rows(&render_to(&app, 60, 16));
        let row_of = |word: &str| drawn.iter().position(|r| r.trim() == word).expect(word);

        // One row of air inside the paragraph, two at the paragraph break — the
        // blank line's own row plus the spacing of the line above it. That is
        // the whole argument for suppressing spacing after a blank line: the
        // break stays bigger than the line gap without being twice it.
        assert_eq!(row_of("bravo") - row_of("alpha"), 2);
        assert_eq!(row_of("charlie") - row_of("bravo"), 3);
    }

    /// The whole flow paints without panicking and applies heading color.
    #[test]
    fn heading_line_gets_heading_style() {
        let app = app_with("# Title\n\nbody text\n");
        let buf = render_to(&app, 80, 12);

        let heading = app.theme.headings[0].to_ratatui();
        let painted_heading = buf.content().iter().any(|c| {
            c.symbol().chars().any(|ch| ch.is_alphabetic()) && c.fg == heading
        });
        assert!(painted_heading, "expected a heading-colored glyph on screen");
    }

    /// A `#` marker is dimmed, distinct from its heading body.
    #[test]
    fn heading_marker_is_dimmed() {
        let app = app_with("# Title\n");
        let buf = render_to(&app, 80, 6);
        let dim = Color::None; // marker fg is text_dim, never the terminal default
        let hash = buf
            .content()
            .iter()
            .find(|c| c.symbol() == "#")
            .expect("hash marker should be on screen");
        assert_eq!(hash.fg, app.theme.text_dim.to_ratatui());
        assert_ne!(hash.fg, dim.to_ratatui());
    }

    fn row_text(buf: &ratatui::buffer::Buffer, y: u16) -> String {
        (0..buf.area().width)
            .map(|x| buf[(x, y)].symbol().to_string())
            .collect::<String>()
            .trim_end()
            .to_string()
    }

    /// An ORDINAL is content, not markup — it is the one list marker
    /// concealment never hides, so dimming it the way a `-` is dimmed left a
    /// numbered list hard to read. It wears the bullet's color instead.
    #[test]
    fn an_ordinal_reads_as_loud_as_a_bullet() {
        // The cursor sits on line 0, so every list line below renders concealed.
        let mut app = app_with("intro\n\n- bulleted\n1. numbered\n2. second\n10. ten\n");

        let bullet = app.theme.list_bullet.to_ratatui();
        let dim = app.theme.text_dim.to_ratatui();
        let check = |buf: &ratatui::buffer::Buffer, ch: &str| {
            let pos = (0..buf.area().height)
                .flat_map(|y| (0..buf.area().width).map(move |x| (x, y)))
                .find(|p| buf[*p].symbol() == ch)
                .unwrap_or_else(|| panic!("{ch:?} should be on screen"));
            let cell = &buf[pos];
            assert_eq!(cell.fg, bullet, "{ch:?} should wear the bullet color");
            assert_ne!(cell.fg, dim, "{ch:?} should not be a dimmed marker");
            assert!(
                !cell.modifier.contains(Modifier::DIM),
                "{ch:?} should not carry the DIM attribute either"
            );
        };

        let buf = render_to(&app, 60, 24);
        for ch in ["1", "2", "0", "."] {
            check(&buf, ch);
        }
        // …and it matches the bullet it sits beside.
        assert_eq!(buf[(0..buf.area().height)
            .flat_map(|y| (0..buf.area().width).map(move |x| (x, y)))
            .find(|p| buf[*p].symbol() == "\u{2022}")
            .expect("a concealed bullet")]
            .fg, bullet);

        // The ACTIVE line renders raw, and the ordinal must hold up there too —
        // that is the line being edited, and the one the reader is looking at.
        app.buffer.cursor = Cursor::new(3, 0);
        app.active = crate::render::conceal::ActiveSet { start: 3, end: 3 };
        let buf = render_to(&app, 60, 24);
        for ch in ["1", "."] {
            check(&buf, ch);
        }
    }

    /// A scratch vault, and an app editing its composition file.
    fn composition(body: &str, frag: &str) -> (std::path::PathBuf, App) {
        use std::sync::atomic::{AtomicUsize, Ordering};
        static N: AtomicUsize = AtomicUsize::new(0);
        let t = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let n = N.fetch_add(1, Ordering::Relaxed);
        let d = std::env::temp_dir().join(format!("shoin-fx-{t}-{n}"));
        std::fs::create_dir_all(&d).unwrap();
        std::fs::write(d.join("frag.md"), frag).unwrap();
        let note = d.join("note.md");
        std::fs::write(&note, body).unwrap();

        let mut app = App::new(Config::default(), Some(note), None).unwrap();
        pin_theme(&mut app);
        app.embed_mode = crate::transclude::Mode::Short;
        app.refresh_blocks();
        (d, app)
    }

    /// SPEC §14.3: an `![[…]]` line draws its target in place…
    #[test]
    fn an_embed_expands_where_it_sits() {
        let (d, app) = composition("top\n\n![[frag]]\n\ntail\n", "# Frag\n\nfragment body\n");
        let rows: Vec<String> = (0..24).map(|y| row_text(&render_to(&app, 80, 24), y)).collect();
        let all = rows.join("\n");

        assert!(all.contains("fragment body"), "the target is drawn");
        assert!(all.contains("frag"), "…under its label");
        assert!(!all.contains("![["), "and its source is not");
        // The composition's own text still surrounds it, in order.
        let top = rows.iter().position(|r| r.contains("top")).unwrap();
        let body = rows.iter().position(|r| r.contains("fragment body")).unwrap();
        let tail = rows.iter().position(|r| r.contains("tail")).unwrap();
        assert!(top < body && body < tail);
        std::fs::remove_dir_all(&d).ok();
    }

    /// …and shows its RAW source when the cursor is on it, exactly as
    /// `**bold**` does. This is the §2 invariant applied to embeds, and it is
    /// what keeps the cursor from ever being inside transcluded text.
    #[test]
    fn the_active_embed_line_shows_its_source() {
        let (d, mut app) = composition("top\n\n![[frag]]\n", "fragment body\n");
        app.buffer.cursor = Cursor::new(2, 0);
        app.active = crate::render::conceal::ActiveSet { start: 2, end: 2 };

        let buf = render_to(&app, 80, 24);
        let all: String = (0..24).map(|y| row_text(&buf, y)).collect::<Vec<_>>().join("\n");
        assert!(all.contains("![[frag]]"), "the cursor's line is raw");
        assert!(!all.contains("fragment body"), "so it is not expanded");
        std::fs::remove_dir_all(&d).ok();
    }

    /// Embedded markdown is never the active line, so it always shows its
    /// finished form — an embedded `# Heading` reads as a heading.
    #[test]
    fn embedded_markdown_is_concealed_like_any_other_line() {
        // The embed must not be on line 0 — that is where the cursor starts,
        // and the active line renders raw by §2.
        let (d, app) = composition("top\n![[frag]]\n", "# Frag title\n\nwith **bold** in it\n");
        let buf = render_to(&app, 80, 24);
        let all: String = (0..24).map(|y| row_text(&buf, y)).collect::<Vec<_>>().join("\n");

        assert!(all.contains("Frag title"));
        assert!(!all.contains("# Frag title"), "the heading marker is concealed");
        assert!(all.contains("bold") && !all.contains("**bold**"));
        std::fs::remove_dir_all(&d).ok();
    }

    /// Turning preview off puts the source back, and the row count with it.
    #[test]
    fn embed_preview_is_a_toggle() {
        let (d, mut app) = composition("top\n![[frag]]\n", "alpha\nbeta\ngamma\n");
        let rows_on = {
            let mut c = app.cache.borrow_mut();
            c.sync(&app, 40);
            c.total_rows()
        };
        app.embed_mode = crate::transclude::Mode::Off;
        let rows_off = {
            let mut c = app.cache.borrow_mut();
            c.sync(&app, 40);
            c.total_rows()
        };
        assert!(rows_on > rows_off, "expanding adds rows: {rows_on} vs {rows_off}");

        let all: String = (0..24)
            .map(|y| row_text(&render_to(&app, 80, 24), y))
            .collect::<Vec<_>>()
            .join("\n");
        assert!(!all.contains("alpha"), "the target is not drawn with preview off");
        // The line is inactive, so it still CONCEALS its `[[ ]]` markers like
        // any other wiki link — off means "not expanded", not "not styled".
        assert!(all.contains("frag"));
        std::fs::remove_dir_all(&d).ok();
    }

    /// The diff view draws both versions on one row, and a FILLER where a side
    /// has no line at all. The filler is the load-bearing part: without it the
    /// two columns drift apart and the alignment is decoration.
    #[test]
    fn the_diff_view_draws_both_sides_with_fillers() {
        let mut app = app_with("keep\nmine\ntail\n");
        app.diff = Some(crate::diff::DiffView::new(
            0,
            "notes.md".into(),
            vec!["keep".into(), "mine".into(), "tail".into()],
            vec!["keep".into(), "theirs".into(), "extra".into(), "tail".into()],
            None,
        ));

        let buf = render_to(&app, 80, 24);
        let rows: Vec<String> = (0..24).map(|y| row_text(&buf, y)).collect();
        let screen = rows.join("\n");

        assert!(screen.contains("diff: notes.md"), "titled:\n{screen}");
        assert!(screen.contains("live") && screen.contains("file — on disk"), "{screen}");

        // The edited line: both versions on ONE row, in that order.
        let changed = rows
            .iter()
            .find(|r| r.contains("mine") && r.contains("theirs"))
            .expect("the changed line shows both sides:\n{screen}");
        assert!(
            changed.find("mine") < changed.find("theirs"),
            "buffer on the left: {changed:?}"
        );

        // The inserted line exists only on the right, so its row carries a
        // filler bar on the left and the text on the right.
        let added = rows
            .iter()
            .find(|r| r.contains("extra"))
            .expect("the added line is on screen");
        assert!(
            added.contains('\u{2504}'),
            "the buffer side is filled, not blank: {added:?}"
        );

        // Nothing of the document underneath leaks through the takeover.
        assert!(!screen.contains("words"), "no status line behind it:\n{screen}");
    }

    /// The merge selection has to be VISIBLE, or the reader is committing a
    /// document they cannot read. Two things carry it: the losing side is struck
    /// out, and the divider glyph points at the side that wins.
    #[test]
    fn the_diff_view_shows_which_side_wins() {
        use crate::diff::Side;
        use ratatui::style::Modifier;

        let mut app = app_with("x\n");
        app.diff = Some(crate::diff::DiffView::new(
            0,
            "notes.md".into(),
            vec!["keep".into(), "mine".into(), "tail".into()],
            vec!["keep".into(), "theirs".into(), "tail".into()],
            None,
        ));

        // Find the row carrying both versions, and a cell inside each column.
        let probe = |app: &App| -> (String, bool, bool) {
            let buf = render_to(app, 60, 12);
            let y = (0..12)
                .find(|y| row_text(&buf, *y).contains("mine"))
                .expect("the changed row is on screen");
            let row = row_text(&buf, y);
            let struck = |needle: &str| -> bool {
                let at = row.find(needle).expect("column text present") as u16;
                buf[(at, y)].modifier.contains(Modifier::CROSSED_OUT)
            };
            // The divider is the one cell that is neither column's text.
            let bar = row
                .chars()
                .find(|c| matches!(c, '\u{25c0}' | '\u{25b6}' | '\u{25c6}'))
                .map(String::from)
                .unwrap_or_default();
            (bar, struck("mine"), struck("theirs"))
        };

        app.diff.as_mut().unwrap().set_all(Side::Live);
        let (bar, mine_out, theirs_out) = probe(&app);
        assert_eq!(bar, "\u{25c0}", "the glyph points left, at live");
        assert!(!mine_out, "the surviving side reads normally");
        assert!(theirs_out, "and the losing side is struck out");

        app.diff.as_mut().unwrap().set_all(Side::File);
        let (bar, mine_out, theirs_out) = probe(&app);
        assert_eq!(bar, "\u{25b6}", "and right, at file");
        assert!(mine_out);
        assert!(!theirs_out);

        // Both kept needs no visual vocabulary of its own: nothing is struck.
        app.diff.as_mut().unwrap().set_all(Side::Both);
        let (bar, mine_out, theirs_out) = probe(&app);
        assert_eq!(bar, "\u{25c6}");
        assert!(!mine_out && !theirs_out, "both survive, so neither is struck");
    }

    /// The conflict marker reaches the status line, riding on the FILENAME so a
    /// reader who trimmed `[status] show` down cannot switch it off by accident.
    ///
    /// It is only ever drawn where it means something: a conflict exists solely
    /// on a modified buffer, since a clean one is reloaded instead of flagged.
    #[test]
    fn a_conflicted_file_is_marked_on_the_status_line() {
        let mut app = app_with("hi\n");
        app.buffer.path = Some(std::path::PathBuf::from("notes.md"));
        // A flash whose text is `None` is what asks for the DEFAULT status
        // content (file, position, words) — `status_text` shows nothing at all
        // without one, which is how `touch_status` works.
        let default_content = || crate::app::Flash {
            text: None,
            kind: crate::app::FlashKind::Info,
            expires_at: std::time::Instant::now() + std::time::Duration::from_secs(60),
        };
        app.flash = Some(default_content());

        let clean = status_text(&app).unwrap_or_default();
        assert!(clean.contains("notes.md"), "got: {clean:?}");
        assert!(
            !clean.contains(&app.config.glyphs.conflict),
            "nothing to warn about yet: {clean:?}"
        );

        app.buffer.conflict = true;
        let marked = status_text(&app).unwrap_or_default();
        assert!(
            marked.contains(&format!("notes.md {}", app.config.glyphs.conflict)),
            "the marker sits with the name: {marked:?}"
        );

        // Empty turns it off, the way every other glyph does.
        app.config.glyphs.conflict = String::new();
        let off = status_text(&app).unwrap_or_default();
        assert!(off.contains("notes.md"), "{off:?}");
        assert_eq!(off.trim_end(), off, "and leaves no dangling space");
    }

    /// A status message too long for the measure is ELIDED, not silently cut.
    /// The end is the half that gets lost, and for an error that is the half
    /// saying what to do about it — so the reader has to be able to see that
    /// something was dropped.
    #[test]
    fn an_overlong_status_says_it_was_cut() {
        let mut app = app_with("hi\n");
        // Set the flash directly: `notify` is private, and what is under test
        // is the RENDERING of an over-long one, not how it got there.
        app.flash = Some(crate::app::Flash {
            text: Some("x".repeat(400)),
            kind: crate::app::FlashKind::Error,
            expires_at: std::time::Instant::now() + std::time::Duration::from_secs(60),
        });

        let buf = render_to(&app, 60, 10);
        let rows: Vec<String> = (0..10).map(|y| row_text(&buf, y)).collect();
        let status = rows
            .iter()
            .find(|r| r.contains('x'))
            .expect("the message is on screen");
        assert!(status.contains('\u{2026}'), "elided: {status:?}");
        let lay = Layout::compute(&app.config.layout, 60, 10 - STATUS_ROWS, 0);
        assert!(
            display_width(status.trim()) as usize <= lay.measure as usize,
            "and inside the measure: {status:?}"
        );
    }

    /// `transclude.border` promises a "labelled box", and a box has four sides.
    /// It used to have three: the rules ran to the measure and the body rows
    /// stopped wherever their text did, which read as a broken frame.
    #[test]
    fn the_embed_box_closes_on_every_row() {
        let (d, app) = composition(
            "top\n![[frag]]\n",
            "# Frag\n\nshort\n\na much longer line of prose that has to wrap at least once\n",
        );
        let buf = render_to(&app, 80, 24);
        let lay = Layout::compute(&app.config.layout, 80, 24 - STATUS_ROWS, 0);
        let right = lay.margin_left + lay.measure - 1;
        let left = lay.margin_left;

        let mut corners = (0, 0);
        let mut bars = 0;
        for y in 0..24 {
            let l = buf[(left, y)].symbol().to_string();
            let r = buf[(right, y)].symbol().to_string();
            match l.as_str() {
                "\u{256d}" => {
                    corners.0 += 1;
                    assert_eq!(r, "\u{256e}", "the top rule must close");
                }
                "\u{2570}" => {
                    corners.1 += 1;
                    assert_eq!(r, "\u{256f}", "the bottom rule must close");
                }
                "\u{2502}" => {
                    bars += 1;
                    assert_eq!(r, "\u{2502}", "every body row must reach the right bar");
                }
                _ => {}
            }
        }
        assert_eq!(corners, (1, 1), "one box");
        assert!(bars >= 4, "and its body rows, got {bars}");
        std::fs::remove_dir_all(&d).ok();
    }

    /// A label longer than the box elides rather than pushing the corner off.
    #[test]
    fn a_long_label_is_elided_not_overflowed() {
        // `composition` writes `frag.md`; give it the long name too, so the
        // link resolves before the first parse rather than after it.
        let (d, app) = composition(
            "top\n![[a-name-far-too-long-to-fit-inside-a-narrow-measure-at-all]]\n",
            "body\n",
        );
        std::fs::copy(
            d.join("frag.md"),
            d.join("a-name-far-too-long-to-fit-inside-a-narrow-measure-at-all.md"),
        )
        .unwrap();

        let buf = render_to(&app, 50, 20);
        let lay = Layout::compute(&app.config.layout, 50, 20 - STATUS_ROWS, 0);
        let right = lay.margin_left + lay.measure - 1;
        let top = (0..20)
            .find(|y| buf[(lay.margin_left, *y)].symbol() == "\u{256d}")
            .expect("a box");
        assert_eq!(buf[(right, top)].symbol(), "\u{256e}", "the corner survives");
        let text: String = (0..50).map(|x| buf[(x, top)].symbol()).collect();
        assert!(text.contains('\u{2026}'), "the label is elided: {text:?}");
        std::fs::remove_dir_all(&d).ok();
    }

    /// A click on transcluded text selects the line that produced it — there is
    /// no column in this rope to land on.
    #[test]
    fn clicking_an_embed_selects_its_source_line() {
        let (d, app) = composition("top\n![[frag]]\n", "aaa\nbbb\n");
        let area = Rect { x: 0, y: 0, width: 80, height: 24 };
        let _ = render_to(&app, 80, 24);

        let rows: Vec<String> = (0..24).map(|y| row_text(&render_to(&app, 80, 24), y)).collect();
        let y = rows.iter().position(|r| r.contains("bbb")).unwrap() as u16;
        let got = locate_click(&app, area, 40, y).expect("a position");
        assert_eq!(got.line, 1, "the `![[frag]]` line");
        assert_eq!(got.col, 0);
        std::fs::remove_dir_all(&d).ok();
    }

    /// SPEC §6: a wrapped list item's continuation lines up under the item's
    /// content, not back at the left margin.
    #[test]
    fn a_wrapped_list_item_hangs_under_its_content() {
        let long = "- ".to_string() + &"word ".repeat(30);
        let mut app = app_with(&(long + "\n"));
        app.config.layout.measure = 30;
        let buf = render_to(&app, 60, 24);

        let rows: Vec<String> = (0..24).map(|y| row_text(&buf, y)).collect();
        let first = rows.iter().position(|r| r.contains("word")).unwrap();
        let indent = |s: &str| s.len() - s.trim_start().len();
        // The bullet's content column, and where the next row starts.
        let content = rows[first].find("word").unwrap();
        assert_eq!(indent(&rows[first + 1]), content, "continuation hangs");
        assert!(
            rows[first + 1].trim_start().starts_with("word"),
            "…and it is the item's own text"
        );
    }

    /// Prose must NOT hang — there is no content column to line up under.
    #[test]
    fn a_wrapped_paragraph_does_not_hang() {
        let mut app = app_with(&("word ".repeat(30) + "\n"));
        app.config.layout.measure = 30;
        let buf = render_to(&app, 60, 24);
        let rows: Vec<String> = (0..24).map(|y| row_text(&buf, y)).collect();
        let first = rows.iter().position(|r| r.contains("word")).unwrap();
        let indent = |s: &str| s.len() - s.trim_start().len();
        assert_eq!(indent(&rows[first]), indent(&rows[first + 1]));
    }

    /// `hanging_indent = false` goes back to a flush continuation.
    #[test]
    fn hanging_indent_honors_its_setting() {
        let long = "- ".to_string() + &"word ".repeat(30);
        let mut app = app_with(&(long + "\n"));
        app.config.layout.measure = 30;
        app.config.layout.hanging_indent = false;
        let buf = render_to(&app, 60, 24);
        let rows: Vec<String> = (0..24).map(|y| row_text(&buf, y)).collect();
        let first = rows.iter().position(|r| r.contains("word")).unwrap();
        let indent = |s: &str| s.len() - s.trim_start().len();
        assert_eq!(indent(&rows[first]), indent(&rows[first + 1]), "flush again");
    }

    /// SPEC §5.3: a fenced body sits on a FLAT code background — across the
    /// whole measure, not just as far as the code happens to reach — with a
    /// colored bar in the margin one column to its left.
    #[test]
    fn fenced_code_gets_a_slab_and_a_gutter_bar() {
        let app = app_with("intro\n\n```rust\nfn x() {}\n```\n\nafter\n");
        let buf = render_to(&app, 80, 24);
        let lay = Layout::compute(&app.config.layout, 80, 24 - STATUS_ROWS, 0);
        let bar_x = lay.margin_left - 1;

        let bar = app.theme.fence_bar.to_ratatui();
        let rows: Vec<u16> = (0..buf.area().height)
            .filter(|y| buf[(bar_x, *y)].symbol() == "\u{258a}" && buf[(bar_x, *y)].fg == bar)
            .collect();
        assert_eq!(rows.len(), 3, "a bar on the fence open, body and close rows");

        // The body row's background reaches the far edge of the measure, well
        // past the end of `fn x() {}`.
        let body = rows[1];
        let code_bg = app.theme.code_bg.to_ratatui();
        let last = lay.margin_left + lay.measure - 1;
        assert_eq!(buf[(last, body)].bg, code_bg, "slab spans the whole measure");
        assert_ne!(
            buf[(bar_x, body)].bg,
            code_bg,
            "the bar hangs in the margin, outside the slab"
        );
        // Prose either side is untouched.
        assert_ne!(buf[(last, rows[0] - 1)].bg, code_bg);
        assert_ne!(buf[(bar_x, rows[2] + 1)].symbol(), "\u{258a}");
    }

    /// An empty `fence_bar` turns the bar off without disturbing the slab —
    /// the same "empty glyph means off" rule the indent guides follow.
    #[test]
    fn an_empty_fence_bar_glyph_draws_nothing() {
        let mut app = app_with("```\ncode\n```\n");
        app.config.glyphs.fence_bar = String::new();
        let buf = render_to(&app, 80, 24);
        let lay = Layout::compute(&app.config.layout, 80, 24 - STATUS_ROWS, 0);
        let bar_x = lay.margin_left - 1;
        let painted = (0..buf.area().height)
            .any(|y| buf[(bar_x, y)].fg == app.theme.fence_bar.to_ratatui());
        assert!(!painted, "no bar should be drawn");
    }

    /// Rows in the last column carrying the scroll-hint glyph.
    fn hint_rows(buf: &ratatui::buffer::Buffer) -> Vec<u16> {
        let x = buf.area().width - 1;
        (0..buf.area().height)
            .filter(|y| buf[(x, *y)].symbol() == "\u{2590}")
            .collect()
    }

    /// A document that fits shows no indicator at all — it is information, not
    /// furniture (SPEC §6: "no scrollbar").
    #[test]
    fn scroll_hint_is_absent_when_the_document_fits() {
        let app = app_with("one\ntwo\nthree\n");
        let buf = render_to(&app, 80, 24);
        assert!(hint_rows(&buf).is_empty(), "short document should show no hint");
    }

    /// Overflow makes it appear, and it tracks the scroll position: at the top
    /// of the document the thumb is at the top, at the end it reaches the
    /// bottom row of the text area.
    #[test]
    fn scroll_hint_tracks_the_scroll_position() {
        let text: String = (0..200).map(|i| format!("line {i}\n")).collect();
        let mut app = app_with(&text);

        let buf = render_to(&app, 80, 24);
        let top_rows = hint_rows(&buf);
        assert!(!top_rows.is_empty(), "long document should show a hint");

        let lay = Layout::compute(&app.config.layout, 80, 24 - STATUS_ROWS, 0);
        assert_eq!(top_rows[0], lay.top, "thumb starts at the first text row");

        app.buffer.cursor = Cursor::new(199, 0);
        let buf = render_to(&app, 80, 24);
        let bottom_rows = hint_rows(&buf);
        assert!(!bottom_rows.is_empty());
        assert_eq!(
            *bottom_rows.last().unwrap(),
            lay.top + lay.height - 1,
            "thumb ends flush with the last text row"
        );
        assert!(bottom_rows[0] > top_rows[0], "thumb moved down");
        assert_eq!(bottom_rows.len(), top_rows.len(), "thumb keeps its length");
    }

    /// `Pane::scroll` is a `Cell` written back on every render specifically so
    /// `scroll_offset` sees the ACTUAL last-drawn top rather than a stale one.
    /// Without that write-back, a step that stays inside the padded view would
    /// still re-derive `top` from scratch each frame and the screen would
    /// scroll on every keystroke instead of staying put — the viewport
    /// "jumping around" on ordinary navigation.
    #[test]
    fn scroll_does_not_move_on_a_step_that_stays_inside_the_padded_view() {
        let text: String = (0..200).map(|i| format!("line {i}\n")).collect();
        let mut app = app_with(&text);

        let lay = Layout::compute(&app.config.layout, 80, 24 - STATUS_ROWS, 0);
        let height = lay.height as usize;
        let pad = (app.config.editor.scroll_off as usize).min(height.saturating_sub(1) / 2);

        // Step the cursor down one row per render, the way real keystrokes
        // drive it, past the point scrolling kicks in, with a little slack.
        let settle_row = height + pad + 3;
        for line in 0..=settle_row {
            app.buffer.cursor = Cursor::new(line, 0);
            render_to(&app, 80, 24);
        }
        let top_before = app.scroll_hint();
        assert!(top_before > 0, "should have scrolled by now");

        // One step up, still well inside the padded view: the top must not move.
        app.buffer.cursor = Cursor::new(settle_row - 1, 0);
        render_to(&app, 80, 24);
        assert_eq!(
            app.scroll_hint(),
            top_before,
            "scroll jumped on a move that stayed on screen"
        );
    }

    /// Turning it off leaves the margin clean.
    #[test]
    fn scroll_hint_honors_its_setting() {
        let text: String = (0..200).map(|i| format!("line {i}\n")).collect();
        let mut app = app_with(&text);
        app.config.layout.scroll_hint = false;
        let buf = render_to(&app, 80, 24);
        assert!(hint_rows(&buf).is_empty(), "disabled hint should not paint");
    }

    /// `layout.numbers` off (the default) draws no gutter at all — the text
    /// sits exactly where the margin alone puts it.
    #[test]
    fn numbers_off_draws_no_gutter() {
        let app = app_with("hello\n");
        assert_eq!(app.numbers, NumberMode::Off);
        let lay = Layout::compute(&app.config.layout, 80, 24 - STATUS_ROWS, 0);
        let buf = render_to(&app, 80, 24);
        let rows = rows(&buf);
        assert_eq!(
            rows[lay.top as usize].find("hello"),
            Some(lay.margin_left as usize)
        );
    }

    /// Absolute numbers the source line, 1-indexed, only on the row where
    /// each line begins.
    #[test]
    fn absolute_numbers_the_source_line_one_indexed() {
        let mut app = app_with("one\ntwo\nthree\n");
        app.numbers = NumberMode::Absolute;
        let lay = Layout::compute(&app.config.layout, 80, 24 - STATUS_ROWS, 0);
        let buf = render_to(&app, 80, 24);
        let rows = rows(&buf);
        let top = lay.top as usize;
        assert!(rows[top].contains("1 one"), "{:?}", rows[top]);
        assert!(rows[top + 1].contains("2 two"), "{:?}", rows[top + 1]);
        assert!(rows[top + 2].contains("3 three"), "{:?}", rows[top + 2]);
    }

    /// Relative numbers read `0` at the cursor's own line and count outward
    /// both ways, the way `relativenumber` does.
    #[test]
    fn relative_numbers_read_zero_at_the_cursor_and_count_outward() {
        let mut app = app_with("a\nb\nc\nd\ne\n");
        app.numbers = NumberMode::Relative;
        app.buffer.cursor = Cursor::new(2, 0); // "c"
        let lay = Layout::compute(&app.config.layout, 80, 24 - STATUS_ROWS, 0);
        let buf = render_to(&app, 80, 24);
        let rows = rows(&buf);
        let top = lay.top as usize;
        assert!(rows[top].contains("2 a"), "{:?}", rows[top]);
        assert!(rows[top + 1].contains("1 b"), "{:?}", rows[top + 1]);
        assert!(rows[top + 2].contains("0 c"), "{:?}", rows[top + 2]);
        assert!(rows[top + 3].contains("1 d"), "{:?}", rows[top + 3]);
        assert!(rows[top + 4].contains("2 e"), "{:?}", rows[top + 4]);
    }

    /// Only the row a line STARTS on gets a number; a wrapped continuation
    /// stays blank, the way Vim leaves the rest of a wrapped line's gutter.
    #[test]
    fn a_wrapped_continuation_row_shows_no_number() {
        let mut app = app_with(&format!("{}\n", "a".repeat(30)));
        app.config.layout.measure = 10;
        app.numbers = NumberMode::Absolute;
        let lay = Layout::compute(&app.config.layout, 80, 24 - STATUS_ROWS, 0);
        let buf = render_to(&app, 80, 24);
        let rows = rows(&buf);
        let top = lay.top as usize;
        assert!(rows[top].trim_start().starts_with('1'), "{:?}", rows[top]);
        assert!(
            !rows[top + 1].trim_start().starts_with(|c: char| c.is_ascii_digit()),
            "continuation row should carry no number: {:?}",
            rows[top + 1]
        );
    }

    /// A margin with no room for the gutter — `align = "left"`'s fixed
    /// 2 columns, with a document that needs 2 digits — goes without rather
    /// than drawing into the text, the same "no room, no draw" `fence_bar`
    /// already uses.
    #[test]
    fn numbers_with_no_room_in_the_margin_draw_nothing() {
        let text: String = (0..15).map(|i| format!("line {i}\n")).collect();
        let mut app = app_with(&text);
        app.config.layout.align = "left".into();
        app.numbers = NumberMode::Absolute;
        let lay = Layout::compute(&app.config.layout, 80, 24 - STATUS_ROWS, 0);
        let buf = render_to(&app, 80, 24);
        let rows = rows(&buf);
        assert_eq!(
            rows[lay.top as usize].find("line 0"),
            Some(lay.margin_left as usize),
            "text sits exactly at the margin, nothing squeezed in ahead of it"
        );
    }

    /// The active line renders its heading markers raw, which normally hangs
    /// them left into the margin (`gutter_shift`). With numbers on, the
    /// number has to give up that same band — it shifts one band further
    /// left, in lockstep with the row, so the two sit side by side rather
    /// than fighting for the same columns (regression: they used to overlap,
    /// since only the row shifted and the number stayed put).
    #[test]
    fn a_revealed_heading_and_its_number_shift_together_without_overlapping() {
        let mut app = app_with("### Title\nmore\n");
        app.numbers = NumberMode::Absolute;
        app.buffer.cursor = Cursor::new(0, 0); // on the heading: it renders raw
        // A wide terminal, so the margin has room for both the reveal shift
        // and the gutter — the case the narrower one below does NOT have.
        let lay = Layout::compute(&app.config.layout, 120, 24 - STATUS_ROWS, 0);
        let gutter = number_gutter_width(NumberMode::Absolute, app.buffer.line_count(), lay.margin_left);
        assert!(gutter > 0, "test needs the number gutter to actually be reserved");
        let buf = render_to(&app, 120, 24);
        let row = &rows(&buf)[lay.top as usize];
        let heading_at = row.find("### Title").expect("the heading is drawn whole, not clipped");
        let digit_at = row
            .find(|c: char| c.is_ascii_digit())
            .expect("there was room for the number too, not just the heading");
        assert!(digit_at < heading_at, "number and markers overlapped: {row:?}");
    }

    /// When shifting the number clear of the markers would push it out of the
    /// margin entirely, the number is left off that ONE row rather than drawn
    /// over the heading or off the pane — the heading itself stays whole, and
    /// every other row keeps its own number.
    #[test]
    fn a_crowded_margin_drops_the_number_rather_than_overlap_the_heading() {
        let mut app = app_with("### Title\nmore\n");
        app.numbers = NumberMode::Absolute;
        app.buffer.cursor = Cursor::new(0, 0);
        // The default measure against an 80-column terminal leaves a 4-column
        // margin — room for the `### ` shift alone, or the gutter alone, but
        // not both together.
        let lay = Layout::compute(&app.config.layout, 80, 24 - STATUS_ROWS, 0);
        let buf = render_to(&app, 80, 24);
        let rows = rows(&buf);
        let top = lay.top as usize;
        assert!(rows[top].contains("### Title"), "the heading is whole: {:?}", rows[top]);
        assert!(rows[top + 1].trim_start().starts_with('2'), "the next row keeps its own number: {:?}", rows[top + 1]);
    }

    /// The cursor's line renders raw; the line below has its `#` concealed.
    /// This is the SPEC §2 invariant, exercised through the full frame.
    #[test]
    fn concealment_reveals_only_the_active_line() {
        let mut app = app_with("# One\n## Two\n");
        // Cursor starts on line 0.
        let buf = render_to(&app, 60, 8);
        let joined: String = (0..buf.area().height).map(|y| row_text(&buf, y)).collect();
        assert!(joined.contains("# One"), "active line 0 should be raw");
        assert!(joined.contains("Two"), "line 1 should be present");
        assert!(!joined.contains("## Two"), "inactive line 1 should hide its ##");

        // Move the cursor to line 1; now IT is raw and line 0 conceals.
        app.buffer.cursor = Cursor::new(1, 0);
        app.active = crate::render::conceal::ActiveSet::compute(&app.mode, &app.buffer.cursor, None);
        let buf = render_to(&app, 60, 8);
        let joined: String = (0..buf.area().height).map(|y| row_text(&buf, y)).collect();
        assert!(joined.contains("## Two"), "active line 1 should be raw");
        assert!(!joined.contains("# One"), "inactive line 0 should hide its #");
        assert!(joined.contains("One"), "line 0 text should remain");
    }

    /// Indent guides (SPEC §5.4) are a conceal op like any other, so they show
    /// on inactive lines and give way to the raw source under the cursor —
    /// the same bargain every marker makes.
    #[test]
    fn indent_guides_show_on_inactive_lines_only() {
        let mut app = app_with("- top\n    - nested\n");
        let buf = render_to(&app, 60, 12);
        let joined: String = (0..buf.area().height).map(|y| row_text(&buf, y)).collect();
        // One level at the default tab_width of 4: the guide takes the first
        // space, the marker becomes a hollow sub-bullet, "nested" never moves.
        assert!(joined.contains("│   ◦ nested"), "guide on the inactive line: {joined:?}");

        // The guide's color comes from the styled spans `indent::apply` colored
        // by depth, not from the conceal op — a plain Replace inherits.
        let (x, y) = (0..buf.area().height)
            .find_map(|y| {
                (0..buf.area().width).find(|&x| buf[(x, y)].symbol() == "│").map(|x| (x, y))
            })
            .expect("a guide glyph on screen");
        assert_eq!(buf[(x, y)].fg, app.theme.indent_colors[0].to_ratatui());

        // Cursor onto the nested line: it renders raw, guides included.
        app.buffer.cursor = Cursor::new(1, 0);
        app.active = crate::render::conceal::ActiveSet::compute(&app.mode, &app.buffer.cursor, None);
        let buf = render_to(&app, 60, 12);
        let joined: String = (0..buf.area().height).map(|y| row_text(&buf, y)).collect();
        assert!(joined.contains("    - nested"), "active line is its source");
        assert!(!joined.contains("│"), "…so no guide glyph anywhere: {joined:?}");
    }

    /// Paragraph focus dims text outside the cursor's paragraph.
    #[test]
    fn focus_mode_dims_other_paragraphs() {
        use crate::render::focus::{FocusMode, FocusRegion};
        let mut app = app_with("# Title\n\nbody words\n");
        app.focus = FocusMode::Paragraph; // cursor on line 0 -> region = line 0
        app.focus_region = FocusRegion::compute(&app.buffer, app.focus);
        let buf = render_to(&app, 60, 8);

        // A glyph from the out-of-focus paragraph is faint but keeps its color.
        let b = buf
            .content()
            .iter()
            .find(|c| c.symbol() == "b")
            .expect("'body words' should be on screen");
        assert!(
            b.modifier.contains(ratatui::style::Modifier::DIM),
            "out-of-focus text should be faint"
        );
        assert_eq!(b.fg, app.theme.text.to_ratatui(), "…but keep its syntax color");
    }

    /// Opening the command box dims the buffer behind it.
    #[test]
    fn command_mode_dims_the_buffer() {
        let mut app = app_with("hello there\n\nmore text\n");
        app.mode = Mode::Command(String::new());
        let buf = render_to(&app, 60, 20); // tall, so the box clears rows below the text
        let h = buf
            .content()
            .iter()
            .find(|c| c.symbol() == "h")
            .expect("body text on screen");
        assert!(
            h.modifier.contains(ratatui::style::Modifier::DIM),
            "buffer text should be dimmed behind the command box"
        );
    }

    /// The tree draws Neo-tree guide lines: a `├╴` elbow on each row, `└╴` on
    /// the last sibling, and a `│` column running down past a subtree whose
    /// parent still has siblings below it.
    #[test]
    fn tree_rows_draw_guides_and_icons() {
        let t = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let dir = std::env::temp_dir().join(format!("shoin-frame-tree-{t}"));
        std::fs::create_dir_all(dir.join("sub")).unwrap();
        std::fs::write(dir.join("sub").join("deep.md"), "").unwrap();
        std::fs::write(dir.join("zeta.md"), "").unwrap();

        let mut app = app_with("hi\n");
        let mut tree = crate::tree::FileTree::open(dir.clone());
        tree.selected = tree.entries.iter().position(|e| e.name == "sub").unwrap();
        tree.activate(); // expand it
        app.tree = Some(tree);

        let buf = render_to(&app, 80, 10);
        let rows: Vec<String> = (0..4).map(|y| row_text(&buf, y)).collect();
        assert!(rows[1].starts_with("├╴"), "sub is not the last sibling: {:?}", rows[1]);
        assert!(rows[2].starts_with("│ └╴"), "deep.md hangs under sub: {:?}", rows[2]);
        assert!(rows[3].starts_with("└╴"), "zeta.md closes the tree: {:?}", rows[3]);

        // The markdown file's icon is colored as prose, not left plain.
        let icon_x = rows[3].chars().position(|c| c == '\u{f48a}').expect("markdown icon");
        assert_eq!(
            buf[(icon_x as u16, 3)].fg,
            app.theme.headings[0].to_ratatui(),
            "a .md file gets the prose-colored icon"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    /// `nerd_fonts = false` must not paint Private Use Area glyphs at anyone
    /// whose font has no icons — directories fall back to plain arrows.
    #[test]
    fn tree_without_nerd_fonts_uses_arrows() {
        let t = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let dir = std::env::temp_dir().join(format!("shoin-frame-ascii-{t}"));
        std::fs::create_dir_all(dir.join("sub")).unwrap();
        std::fs::write(dir.join("zeta.md"), "").unwrap();

        let mut app = app_with("hi\n");
        app.config.glyphs.nerd_fonts = false;
        app.tree = Some(crate::tree::FileTree::open(dir.clone()));

        let buf = render_to(&app, 80, 10);
        let joined: String = (0..4).map(|y| row_text(&buf, y)).collect();
        assert!(joined.contains("▸ sub"), "a collapsed dir gets an arrow: {joined:?}");
        assert!(joined.contains("zeta.md"));
        assert!(
            !joined.chars().any(|c| ('\u{e000}'..='\u{f8ff}').contains(&c)),
            "no Private Use Area glyphs: {joined:?}"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    /// The finder overlay draws its query, its match count, and the matching
    /// paths — with the matched characters picked out in the accent color.
    #[test]
    fn finder_overlay_lists_matches_and_highlights_them() {
        let t = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let dir = std::env::temp_dir().join(format!("shoin-frame-finder-{t}"));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("alpha.md"), "").unwrap();
        std::fs::write(dir.join("beta.md"), "").unwrap();

        let mut app = app_with("hello there\n");
        let mut finder = crate::finder::Finder::open(dir.clone());
        finder.push_char('b');
        app.finder = Some(finder);

        let buf = render_to(&app, 60, 20);
        let joined: String = (0..buf.area().height).map(|y| row_text(&buf, y)).collect();
        assert!(joined.contains("find"), "the box is titled");
        assert!(joined.contains("> b"), "the query is echoed");
        assert!(joined.contains("1/2"), "matched / total files");
        assert!(joined.contains("beta.md"), "the match is listed");
        assert!(!joined.contains("alpha.md"), "the non-match is filtered out");

        // Result rows carry the same file-type icon the tree draws.
        let row = (0..buf.area().height)
            .find(|&y| row_text(&buf, y).contains("beta.md"))
            .expect("result row");
        let icon_x = row_text(&buf, row)
            .chars()
            .position(|c| c == '\u{f48a}')
            .expect("markdown icon on the result row");
        assert_eq!(
            buf[(icon_x as u16, row)].fg,
            app.theme.headings[0].to_ratatui(),
            "colored by type, like the tree"
        );

        // The matched 'b' of "beta.md" renders in the accent color, its
        // neighbours do not.
        let accent = app.theme.link.to_ratatui();
        // Char position, not byte: the row starts with a multi-byte "▸".
        let x = row_text(&buf, row).chars().position(|c| c == 'b').unwrap() as u16;
        assert_eq!(buf[(x, row)].fg, accent, "matched char is accented");
        assert_ne!(buf[(x + 1, row)].fg, accent, "the rest of the path is not");
        std::fs::remove_dir_all(&dir).ok();
    }

    /// A split draws both panes, each measuring its own width, with a divider
    /// between them — and only the focused one shows its raw (active) line.
    #[test]
    fn a_split_renders_two_panes_side_by_side() {
        let mut app = app_with("# Title\n\nbody text here\n");
        app.split_pane_for_test(true);

        let buf = render_to(&app, 100, 24);
        let rows: Vec<String> = (0..24).map(|y| row_text(&buf, y)).collect();
        let with_body: Vec<&String> = rows.iter().filter(|r| r.contains("body text here")).collect();
        assert_eq!(with_body.len(), 1, "one row, holding the text twice");
        let line = with_body[0];
        assert_eq!(line.matches("body text here").count(), 2, "once per pane: {line:?}");

        // The divider column is painted with the dim color, and nothing else is
        // drawn over it.
        let geo = app.layout.geometry(pane_area(&app, Rect { x: 0, y: 0, width: 100, height: 24 }));
        assert_eq!(geo.dividers.len(), 1);
        let x = geo.dividers[0].x;
        assert_eq!(buf[(x, 5)].bg, app.theme.text_dim.to_ratatui());

        // Panes have their own cursors, but CONCEALMENT is still per document:
        // the row index lives in its render cache, so the focused pane's active
        // line renders raw in both. Panes showing DIFFERENT documents do
        // diverge — the background one has no cursor, so it conceals
        // throughout.
        let heading_row = rows.iter().find(|r| r.contains("Title")).expect("the heading");
        assert_eq!(heading_row.matches("# Title").count(), 2, "{heading_row:?}");
    }

    /// A left-click maps back to the buffer line it landed on.
    #[test]
    fn click_maps_to_the_clicked_line() {
        let app = app_with("# One\n\nsecond paragraph here\n");
        let area = Rect { x: 0, y: 0, width: 60, height: 12 };
        // Row lay.top is line 0; two rows down is the (blank) line 1; three is 2.
        assert_eq!(locate_click(&app, area, 8, 2).map(|c| c.line), Some(0));
        assert_eq!(locate_click(&app, area, 8, 4).map(|c| c.line), Some(2));
        // Above the text area → no position.
        assert!(locate_click(&app, area, 8, 0).is_none());
    }

    /// A drag that wanders out of the text area clamps to the nearest edge
    /// instead of refusing, so a selection dragged off the top or the bottom
    /// goes on extending to the row the pointer is level with.
    #[test]
    fn a_drag_clamps_to_the_text_area() {
        let app = app_with("# One\n\nsecond paragraph here\n");
        let area = Rect { x: 0, y: 0, width: 60, height: 12 };
        // The row a click refuses is the first line to a drag.
        assert_eq!(locate_drag(&app, area, 8, 0).map(|c| c.line), Some(0));
        // Past the last row, and off the right edge of it: the end of the text.
        let end = locate_drag(&app, area, 59, 11).expect("a position");
        let last = app.buffer.rope.len_lines() - 1;
        assert_eq!(end.line, last, "the last line");
        // Left of the pane clamps back to its first column.
        assert_eq!(locate_drag(&app, area, 0, 2).map(|c| c.col), Some(0));
    }

    /// The theme background fills the whole surface, so a theme renders on its
    /// own background rather than the terminal's.
    #[test]
    fn theme_background_is_painted() {
        let app = app_with("hello world\n");
        let buf = render_to(&app, 40, 6);
        let bg = app.theme.background.to_ratatui();
        assert!(
            buf.content().iter().all(|c| c.bg == bg),
            "every cell should carry the theme background"
        );
    }

    /// `layout.stable_gutter`: a heading's TEXT stays in the same column
    /// whether the cursor is on it (markers revealed) or not (concealed).
    #[test]
    fn a_stable_gutter_keeps_revealed_text_in_place() {
        let mut app = app_with("# Title\n\nbody\n");
        // Where the heading's "T" sits, anywhere on screen (padding moves rows).
        let column_of = |buf: &ratatui::buffer::Buffer| -> Option<u16> {
            (0..buf.area().height)
                .flat_map(|y| (0..buf.area().width).map(move |x| (x, y)))
                .find(|(x, y)| buf[(*x, *y)].symbol() == "T")
                .map(|(x, _)| x)
        };
        let has_hash = |buf: &ratatui::buffer::Buffer| -> bool {
            (0..buf.area().height)
                .flat_map(|y| (0..buf.area().width).map(move |x| (x, y)))
                .any(|(x, y)| buf[(x, y)].symbol() == "#")
        };

        // Cursor elsewhere: the heading is concealed, "Title" at the margin.
        app.buffer.cursor = Cursor::new(2, 0);
        app.active = crate::render::conceal::ActiveSet { start: 2, end: 2 };
        let concealed = render_to(&app, 60, 24);

        // Cursor on the heading: "## " comes back, into the gutter.
        app.buffer.cursor = Cursor::new(0, 0);
        app.active = crate::render::conceal::ActiveSet { start: 0, end: 0 };
        let revealed = render_to(&app, 60, 24);

        assert_eq!(column_of(&concealed), column_of(&revealed));
        assert!(column_of(&concealed).is_some(), "the heading should be drawn");
        assert!(
            has_hash(&revealed),
            "the markers should be on screen, just left of the text"
        );

        // Off, the text moves with its markers — the behavior being avoided.
        app.config.layout.stable_gutter = false;
        let unstable = render_to(&app, 60, 24);
        assert_ne!(column_of(&concealed), column_of(&unstable));
    }

    /// A warm cache must paint exactly what a cold one paints. This is the
    /// backstop for the whole incremental design: edit, scroll and reveal, then
    /// compare the frame against the same state rendered from an empty cache.
    #[test]
    fn a_warm_cache_paints_what_a_cold_one_does() {
        let mut app = app_with("# Title\n\nsome **bold** prose here\n\n- one\n- two\n\n> quoted\n");
        let _ = render_to(&app, 60, 12);

        // Edit, move, and re-render — the cache follows all of it.
        app.buffer.insert_str(Cursor::new(2, 4), " more");
        app.buffer.insert_str(Cursor::new(4, 0), "- inserted\n");
        app.refresh_blocks();
        app.buffer.cursor = Cursor::new(5, 2);
        app.active = crate::render::conceal::ActiveSet { start: 5, end: 5 };
        let warm = render_to(&app, 60, 12);

        *app.cache.borrow_mut() = RenderCache::default();
        let cold = render_to(&app, 60, 12);
        assert_eq!(warm, cold);
    }

    /// `layout.conceal = false` renders every line raw (the escape hatch).
    #[test]
    fn conceal_disabled_keeps_all_markers() {
        let mut app = app_with("# One\n## Two\n");
        app.config.layout.conceal = false;
        let buf = render_to(&app, 60, 8);
        let joined: String = (0..buf.area().height).map(|y| row_text(&buf, y)).collect();
        assert!(joined.contains("# One"));
        assert!(joined.contains("## Two"), "conceal off: line 1 keeps its ##");
    }

    /// A table row's `|` columns are laid out by its author, not by wrapping —
    /// a row wider than the measure stays one row, clipped at the edge, rather
    /// than breaking onto ragged continuation lines that no longer align.
    #[test]
    fn a_wide_table_row_does_not_wrap() {
        let md = "| Name | Description | Owner |\n|---|---|---|\n| alpha | a long description that will not fit in a narrow measure | bob |\n";
        let app = app_with(md);
        let buf = render_to(&app, 40, 12);
        let text = rows(&buf);
        assert!(
            text.iter().any(|r| r.contains("| alpha | a long description")),
            "the row's start is on screen, unbroken: {text:?}"
        );
        assert!(
            !text.iter().any(|r| r.trim() == "bob |"),
            "the row's tail must not have wrapped onto its own line: {text:?}"
        );
    }

    /// `text_align` shapes how a row sits WITHIN the column — a different axis
    /// from `layout.align`, which places the column itself (untouched here).
    /// The default is `left`: a short row stays flush against the column's
    /// own left edge, exactly where it always drew.
    #[test]
    fn left_is_the_default_and_leaves_a_short_row_flush() {
        let app = app_with("hi\n");
        assert_eq!(app.text_align, TextAlign::Left);
        let drawn = rows(&render_to(&app, 80, 8));
        let row = drawn.iter().find(|r| r.trim() == "hi").expect("hi is on screen");
        let margin_left = (80u16 - app.config.layout.measure) / 2;
        let leading = row.chars().take_while(|c| *c == ' ').count() as u16;
        assert_eq!(leading, margin_left, "flush against the column's left edge");
    }

    /// `Center` centers a short (unwrapped) row inside the measure — the same
    /// offset ratatui's own `Line::centered` would compute, since that is
    /// exactly what draws it.
    #[test]
    fn center_align_centers_a_short_row_in_the_measure() {
        let mut app = app_with("hi\n");
        app.config.layout.measure = 20;
        app.text_align = TextAlign::Center;
        let drawn = rows(&render_to(&app, 80, 8));
        let row = drawn.iter().find(|r| r.trim() == "hi").expect("hi is on screen");
        let margin_left = (80u16 - 20) / 2;
        let leading = row.chars().take_while(|c| *c == ' ').count() as u16;
        assert_eq!(leading, margin_left + 9, "(20/2) - (2/2) columns in from the edge");
    }

    /// `Right` pushes a short row flush against the measure's own right edge.
    #[test]
    fn right_align_pushes_a_short_row_to_the_measures_right_edge() {
        let mut app = app_with("hi\n");
        app.config.layout.measure = 20;
        app.text_align = TextAlign::Right;
        let drawn = rows(&render_to(&app, 80, 8));
        let row = drawn.iter().find(|r| r.trim() == "hi").expect("hi is on screen");
        let margin_left = (80u16 - 20) / 2;
        let leading = row.chars().take_while(|c| *c == ' ').count() as u16;
        assert_eq!(leading, margin_left + 18, "20 - 2 columns in from the edge");
    }

    /// `Justified` stretches every wrapped row of a paragraph to fill the
    /// measure exactly, EXCEPT the paragraph's own last row, which stays
    /// ragged — the one thing that tells "justified" apart from "stretch
    /// every line", and why a reader can still tell where the paragraph ends.
    #[test]
    fn justified_stretches_every_row_but_the_last() {
        let mut app = app_with("aaa bbb ccc ddd\n");
        app.config.layout.measure = 10;
        app.text_align = TextAlign::Justified;
        let drawn = rows(&render_to(&app, 80, 8));
        let margin_left = (80u16 - 10) / 2;
        let pad = " ".repeat(margin_left as usize);

        let first = drawn.iter().find(|r| r.trim_start().starts_with("aaa")).expect("first row");
        assert_eq!(first, &format!("{pad}aaa    bbb"), "stretched flush to the measure");

        let last = drawn.iter().find(|r| r.trim_start().starts_with("ccc")).expect("last row");
        assert_eq!(last, &format!("{pad}ccc ddd"), "the last row stays ragged");
    }

    /// A short paragraph that never wraps has no "last row" distinct from its
    /// only row, so `Justified` leaves it exactly as `Left` would draw it —
    /// there is nothing to stretch it against.
    #[test]
    fn justified_leaves_an_unwrapped_row_ragged() {
        let mut app = app_with("aaa bbb\n");
        app.config.layout.measure = 20;
        app.text_align = TextAlign::Justified;
        let drawn = rows(&render_to(&app, 80, 8));
        let row = drawn.iter().find(|r| r.contains("aaa")).expect("on screen");
        assert!(row.trim_end().ends_with("aaa bbb"), "single space, not stretched: {row:?}");
    }

    /// A fenced code row is code, not prose: `text_align` never touches it,
    /// even set to `Justified`, which would otherwise mangle indentation and
    /// inter-token spacing.
    #[test]
    fn fenced_code_ignores_text_align() {
        let mut app = app_with("```\nfn  x()  {}\n```\n");
        app.config.layout.measure = 40;
        app.text_align = TextAlign::Justified;
        let drawn = rows(&render_to(&app, 80, 8));
        let row = drawn.iter().find(|r| r.contains("fn")).expect("code line on screen");
        assert!(row.contains("fn  x()  {}"), "spacing untouched: {row:?}");
    }
}