perfectstar2k 0.4.0

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

use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::DefaultTerminal;

use crate::block::adjust_pos;
use crate::buffer::wrap_segments;
use crate::config::Config;
use crate::export::docx::DocxExporter;
use crate::export::epub::EpubExporter;
use crate::export::html::{HtmlExporter, PlainTextExporter};
use crate::export::{CompiledDoc, Exporter};
use crate::history::{Edit, EditGroup, EditKind};
use crate::keymap::{self, Cmd, Prefix};
use crate::killring::{KillRing, PutCycle};
use crate::normalize;
use crate::outline;
use crate::pane::Pane;
use crate::project::Project;
use crate::projsearch;
use crate::recovery::{self, Journal};
use crate::rtf;
use crate::search::{ReplacePhase, ReplaceState, SearchState};
use crate::spellcheck;
use crate::stats::{DailyHistory, DocStats, GoalKind, SessionGoal};
use crate::theme::Theme;
use crate::ui;

const JUMP_STACK_MAX: usize = 32;

/// What a text-input prompt is collecting (^KW, ^KR).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputAction {
    WriteBlock,
    ReadFile,
    ExportClean,
    ExportManuscript,
    ExportDocx,
    ExportEpub,
    ExportHtml,
    ExportProjectDocx,
    ExportProjectEpub,
    ExportProjectHtml,
    WrapMargin,
    /// ^OK with one window: filename to open in the second window.
    OpenSplit,
    /// A replacement destination offered after a normal save fails.
    SaveAs,
    /// ^PN: path for new project manifest (.pstarproj file) to create.
    ProjectNew,
    /// ^PP: project manifest path (.pstarproj file) to open.
    ProjectOpen,
    /// ^PA: file path to add to the project.
    ProjectAddDoc,
    /// Set a session word goal (e.g. "500" for 500 words).
    SetGoal,
    /// Project-wide search query (^PS).
    ProjectSearch,
    /// Project-wide replace: "find|replace" format (^PW).
    ProjectReplace,
}

/// What the keyboard is currently driving.
pub enum Mode {
    Normal,
    /// Quit with unsaved changes? (y/N)
    ConfirmAbandon,
    /// A newer crash journal is available for the active document.
    ConfirmRecover,
    Search(SearchState),
    Replace(ReplaceState),
    Input {
        label: String,
        value: String,
        action: InputAction,
    },
    /// The command palette / searchable help (Esc or F1).
    Palette {
        query: String,
        selected: usize,
    },
    /// The outline: jump between Markdown headings (^QO).
    Outline {
        entries: Vec<outline::Entry>,
        query: String,
        selected: usize,
    },
    /// The binder: project document list (^PB).
    Binder {
        entries: Vec<BinderEntry>,
        selected: usize,
    },
    /// Daily writing history overlay (R2.5, task 4.4).
    Stats,
    /// Project-wide search results (R6, task 5.1).
    ProjectSearch {
        query: String,
        results: Vec<projsearch::Match>,
        selected: usize,
        /// Whether to enter replace mode after search.
        replace_with: Option<String>,
    },
}

/// An entry in the binder panel, with display information for a project document.
#[derive(Debug, Clone)]
pub struct BinderEntry {
    /// Index into the project's manifest.docs.
    pub idx: usize,
    /// Display title.
    pub title: String,
    /// Word count (None if not yet computed or file missing).
    pub word_count: Option<usize>,
    /// Whether the file exists on disk.
    pub exists: bool,
}

struct PendingRecovery {
    pane: usize,
    text: String,
}

pub struct App {
    /// The editing windows (one or two, stacked). Per-document state —
    /// buffer, cursor, undo, blocks, bookmarks — lives in each `Pane`.
    pub panes: Vec<Pane>,
    /// Which pane has the keyboard.
    pub active: usize,
    pub theme: Theme,
    /// Showing the startup splash; any keypress dismisses it and is
    /// otherwise discarded (never typed into the document).
    pub splash: bool,
    pub status_msg: Option<String>,
    pub mode: Mode,
    pub prefix: Option<(Prefix, Instant)>,
    /// Shared across panes on purpose: cut in one window, put in the other.
    pub kill: KillRing,
    put_cycle: Option<PutCycle>,
    /// Last accepted search, for ^L — global so a search made in one window
    /// can be repeated in the other.
    pub last_search: Option<String>,
    /// Reveal Codes split pane (^OD).
    pub reveal: bool,
    pub menu_delay: Duration,
    /// 0 = clean screen, 1 = delayed menus, 2 = menus + hint bar.
    pub help_level: u8,
    pub overtype: bool,
    pub wrap: bool,
    pub wrap_margin: usize,
    pub spell: spellcheck::Spellchecker,
    pub spell_enabled: bool,
    /// Keep the cursor's line pinned at a fixed row (view_rows / 2) and
    /// scroll the document under it, instead of only scrolling at the edges.
    pub typewriter: bool,
    /// Body font for `^KM` manuscript RTF export.
    pub manuscript_font: rtf::ManuscriptFont,
    /// Idle autosave; zero disables manuscript autosave (recovery remains on).
    autosave: Duration,
    /// Maximum timestamped rolling backups retained per saved document.
    backup_depth: usize,
    /// Metadata root for crash journals and the distinct `backups/` tree.
    backup_root: Option<PathBuf>,
    /// One plain-text crash journal per pane, kept index-aligned with `panes`.
    recovery_journals: Vec<Journal>,
    /// Recovery text is loaded before prompting so a disappearing record can
    /// never strand the only copy between detection and confirmation.
    pending_recovery: Option<PendingRecovery>,
    /// Keyboard macro (^QM record, ^QJ play).
    macro_keys: Vec<KeyEvent>,
    pub recording: bool,
    playing: bool,
    quit: bool,
    /// The loaded project (book-scale manuscript). None when editing a bare
    /// file; Some when a .pstarproj manifest has been opened (R1, task 1.2).
    pub project: Option<Project>,
    /// Cached prose statistics for the active document (R2, task 4.1).
    pub doc_stats: DocStats,
    /// Whether the always-on word count is shown in the status line.
    pub show_word_count: bool,
    /// Session writing goal (R2.3).
    pub goal: Option<SessionGoal>,
    /// Goal-reached notification was already shown this goal.
    goal_notified: bool,
    /// Per-day words-written history for the active document.
    pub daily_history: DailyHistory,
    /// Word count at start of this editing session (for daily delta).
    session_start_words: usize,
}

/// `App` dereferences to the active pane, so the whole editing engine —
/// movement, editing, undo, marks — reads and writes `self.cursor`,
/// `self.buf`, etc. and always operates on the focused window. Deliberate
/// use of deref-to-owned-state: the alternative is threading a pane index
/// through two hundred call sites for the same result.
impl std::ops::Deref for App {
    type Target = Pane;
    fn deref(&self) -> &Pane {
        &self.panes[self.active]
    }
}

impl std::ops::DerefMut for App {
    fn deref_mut(&mut self) -> &mut Pane {
        &mut self.panes[self.active]
    }
}

impl App {
    pub fn new(path: Option<PathBuf>) -> io::Result<Self> {
        let pane = Pane::open(path)?;
        let recovery_journal = Journal::new(pane.buf.path.as_deref());
        let config = Config::load();
        let initial_stats = DocStats::from_rope(&pane.buf.rope);
        let daily_history = DailyHistory::load(pane.buf.path.as_deref());
        let start_words = initial_stats.words;
        let mut app = App {
            panes: vec![pane],
            active: 0,
            theme: config.theme(),
            splash: true,
            status_msg: None,
            mode: Mode::Normal,
            prefix: None,
            kill: KillRing::new(),
            put_cycle: None,
            last_search: None,
            reveal: false,
            menu_delay: Duration::from_millis(config.menu_delay_ms),
            help_level: config.help_level.min(2),
            overtype: false,
            wrap: config.wrap,
            wrap_margin: config.wrap_margin,
            spell: spellcheck::Spellchecker::load(),
            spell_enabled: config.spellcheck,
            typewriter: config.typewriter,
            manuscript_font: config.manuscript_font(),
            autosave: Duration::from_secs(config.autosave_secs),
            backup_depth: config.backup_depth,
            backup_root: crate::paths::recovery(),
            recovery_journals: vec![recovery_journal],
            pending_recovery: None,
            macro_keys: Vec::new(),
            recording: false,
            playing: false,
            quit: false,
            project: None, // R1.8: backward compat — no project at bare-file launch
            doc_stats: initial_stats,
            show_word_count: true,
            goal: None,
            goal_notified: false,
            daily_history,
            session_start_words: start_words,
        };
        app.offer_recovery_for_active();
        Ok(app)
    }

    /// Effective wrap width for the active pane, if soft wrap is on.
    pub fn wrap_width(&self) -> Option<usize> {
        self.wrap_width_of(self)
    }

    /// Effective wrap width for a given pane, if soft wrap is on.
    pub fn wrap_width_of(&self, pane: &Pane) -> Option<usize> {
        if !self.wrap {
            return None;
        }
        let w = if self.wrap_margin == 0 {
            pane.view_cols
        } else {
            self.wrap_margin.min(pane.view_cols)
        };
        Some(w.max(1))
    }

    pub fn run(&mut self, terminal: &mut DefaultTerminal) -> io::Result<()> {
        while !self.quit {
            terminal.draw(|f| ui::draw(f, self))?;
            if event::poll(Duration::from_millis(100))? {
                match event::read()? {
                    Event::Key(k) if k.kind != KeyEventKind::Release => self.handle_key(k),
                    _ => {}
                }
            } else {
                self.maybe_autosave();
            }
        }
        self.clear_clean_recovery();
        // Persist daily words-written delta before exiting (R2.5).
        let delta = self.doc_stats.words as i64 - self.session_start_words as i64;
        self.daily_history.record_delta(delta);
        let _ = self.daily_history.save();
        for pane in &self.panes {
            pane.save_session();
        }
        Ok(())
    }

    /// The existing idle callback is also the recovery throttle: each edit is
    /// journaled at most once, before a manuscript autosave is attempted.
    fn maybe_autosave(&mut self) {
        let deadline = self.autosave;
        let backup_depth = self.backup_depth;
        let backup_root = self.backup_root.clone();
        let mut autosaved = false;
        let mut warnings = Vec::new();
        let (panes, journals) = (&mut self.panes, &mut self.recovery_journals);

        for (pane, journal) in panes.iter_mut().zip(journals.iter_mut()) {
            if !pane.buf.dirty {
                continue;
            }

            if let Err(error) = journal.write_if_changed(&pane.buf.rope, pane.last_edit) {
                warnings.push(format!("Recovery write failed: {error}"));
            }

            if !deadline.is_zero()
                && pane.buf.path.is_some()
                && pane.last_edit.elapsed() >= deadline
            {
                match pane.buf.save() {
                    Ok(()) => {
                        autosaved = true;
                        if let Err(error) = write_backup_after_save(
                            backup_root.as_deref(),
                            pane.buf.path.as_deref(),
                            backup_depth,
                        ) {
                            warnings.push(format!("Rolling backup failed: {error}"));
                        }
                        if let Err(error) = journal.clear() {
                            warnings.push(format!("Recovery cleanup failed: {error}"));
                        }
                    }
                    Err(error) => {
                        // The buffer remains dirty and its successfully-written
                        // journal remains available for crash recovery.
                        warnings.push(format!("Autosave failed: {error}"));
                    }
                }
            }
        }

        if !warnings.is_empty() {
            self.status_msg = Some(warnings.join("; "));
        } else if autosaved {
            self.status_msg = Some(String::from("Autosaved"));
        }

        // Debounced full recount to correct any drift (R2.7).
        if self.doc_stats.needs_recount() {
            self.doc_stats
                .full_recount(&self.panes[self.active].buf.rope);
        }

        // Check session goal progress (R2.4).
        if let Some(ref mut goal) = self.goal {
            if !goal.reached && goal.is_met(self.doc_stats.words) {
                goal.reached = true;
                if !self.goal_notified {
                    self.goal_notified = true;
                    let (current, target) = goal.progress(self.doc_stats.words);
                    self.status_msg = Some(format!(
                        "Goal reached! {current}/{target} {}",
                        match goal.kind {
                            GoalKind::Words => "words",
                            GoalKind::Minutes => "minutes",
                        }
                    ));
                }
            }
        }
    }

    fn clear_clean_recovery(&mut self) {
        for (pane, journal) in self.panes.iter().zip(self.recovery_journals.iter_mut()) {
            if !pane.buf.dirty {
                let _ = journal.clear();
            }
        }
    }

    fn offer_recovery_for_active(&mut self) {
        let pane = self.active;
        match self.recovery_journals[pane].recoverable_text() {
            Ok(Some(text)) => {
                self.pending_recovery = Some(PendingRecovery { pane, text });
                self.mode = Mode::ConfirmRecover;
                // Recovery is more urgent than the decorative startup splash:
                // the first key must answer the prompt rather than be discarded.
                self.splash = false;
            }
            Ok(None) => {}
            Err(error) => {
                // Preserve unreadable data for manual recovery instead of
                // deleting or overwriting the only possible copy.
                self.status_msg = Some(format!("Recovery record unreadable: {error}"));
            }
        }
    }

    fn answer_recovery_prompt(&mut self, restore: bool) {
        let Some(pending) = self.pending_recovery.take() else {
            self.mode = Mode::Normal;
            self.status_msg = Some(String::from("Recovery record is no longer available"));
            return;
        };
        self.active = pending.pane;
        self.mode = Mode::Normal;

        if restore {
            let old_len = self.buf.len_chars();
            let cursor_after = self.cursor.min(pending.text.chars().count());
            self.apply_edit(0, old_len, &pending.text, EditKind::Other, cursor_after);
            self.history.break_group();
            self.status_msg = Some(String::from("Recovered unsaved changes; save to keep them"));
        } else {
            self.status_msg = Some(match self.recovery_journals[pending.pane].clear() {
                Ok(()) => String::from("Recovery declined"),
                Err(error) => format!("Recovery declined; cleanup failed: {error}"),
            });
        }
    }

    /// The query whose matches should be highlighted in the text area.
    pub fn active_query(&self) -> Option<&str> {
        match &self.mode {
            Mode::Search(s) if !s.query.is_empty() => Some(&s.query),
            Mode::Replace(r) if matches!(r.phase, ReplacePhase::Confirm(_)) => Some(&r.find),
            _ => None,
        }
    }

    // --- key dispatch -----------------------------------------------------

    fn handle_key(&mut self, key: KeyEvent) {
        if self.splash {
            self.splash = false;
            return;
        }
        self.status_msg = None;

        if self.recording && !self.playing {
            self.macro_keys.push(key);
        }

        if let Some((prefix, _)) = self.prefix.take() {
            self.handle_prefixed(prefix, key);
            return;
        }

        // Any keystroke that isn't (potentially) part of a ^KP chord ends a
        // put-cycle.
        if !is_prefix_key(&key) {
            self.put_cycle = None;
        }

        match &mut self.mode {
            Mode::ConfirmAbandon => {
                let yes = matches!(key.code, KeyCode::Char('y') | KeyCode::Char('Y'));
                self.mode = Mode::Normal;
                if yes {
                    self.close_or_quit();
                }
            }
            Mode::ConfirmRecover => match key.code {
                KeyCode::Char('y') | KeyCode::Char('Y') => self.answer_recovery_prompt(true),
                KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Enter | KeyCode::Esc => {
                    self.answer_recovery_prompt(false)
                }
                _ => {}
            },
            Mode::Search(_) => self.handle_search_key(key),
            Mode::Replace(_) => self.handle_replace_key(key),
            Mode::Input { .. } => self.handle_input_key(key),
            Mode::Palette { .. } => self.handle_palette_key(key),
            Mode::Outline { .. } => self.handle_outline_key(key),
            Mode::Binder { .. } => self.handle_binder_key(key),
            Mode::Stats => self.mode = Mode::Normal,
            Mode::ProjectSearch { .. } => self.handle_project_search_key(key),
            Mode::Normal => self.handle_normal_key(key),
        }
    }

    fn handle_normal_key(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        match key.code {
            KeyCode::Char(c) if ctrl => {
                let c = c.to_ascii_lowercase();
                match c {
                    'k' => self.prefix = Some((Prefix::K, Instant::now())),
                    'q' => self.prefix = Some((Prefix::Q, Instant::now())),
                    'o' => self.prefix = Some((Prefix::O, Instant::now())),
                    'p' => self.prefix = Some((Prefix::P, Instant::now())),
                    _ => {
                        if let Some(cmd) = keymap::lookup_bare(c) {
                            self.execute(cmd);
                        }
                    }
                }
            }
            KeyCode::Up => self.execute(Cmd::Up),
            KeyCode::Down => self.execute(Cmd::Down),
            KeyCode::Left => self.execute(Cmd::Left),
            KeyCode::Right => self.execute(Cmd::Right),
            KeyCode::PageUp => self.execute(Cmd::PageUp),
            KeyCode::PageDown => self.execute(Cmd::PageDown),
            KeyCode::Home => self.execute(Cmd::LineStart),
            KeyCode::End => self.execute(Cmd::LineEnd),
            KeyCode::Insert => self.execute(Cmd::ToggleInsert),
            KeyCode::F(1) => self.execute(Cmd::Palette),
            KeyCode::Esc => self.execute(Cmd::Palette),
            KeyCode::Backspace => self.execute(Cmd::DeleteLeft),
            KeyCode::Delete => self.execute(Cmd::DeleteRight),
            KeyCode::Enter => self.insert_text("\n", EditKind::Other),
            KeyCode::Tab => self.insert_text("\t", EditKind::InsertChar),
            KeyCode::Char(c) => self.insert_text(&c.to_string(), EditKind::InsertChar),
            _ => {}
        }
    }

    fn handle_palette_key(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let Mode::Palette { query, selected } = &mut self.mode else {
            return;
        };
        let entries = keymap::filtered_entries(query);
        match key.code {
            KeyCode::Esc => self.mode = Mode::Normal,
            KeyCode::Up => *selected = selected.saturating_sub(1),
            KeyCode::Down => *selected = (*selected + 1).min(entries.len().saturating_sub(1)),
            KeyCode::Char('e') if ctrl => *selected = selected.saturating_sub(1),
            KeyCode::Char('x') if ctrl => {
                *selected = (*selected + 1).min(entries.len().saturating_sub(1))
            }
            KeyCode::Backspace => {
                query.pop();
                *selected = 0;
            }
            KeyCode::Enter => {
                let cmd = entries.get(*selected).map(|e| e.0);
                self.mode = Mode::Normal;
                if let Some(cmd) = cmd {
                    self.execute(cmd);
                }
            }
            KeyCode::Char(c) if !ctrl => {
                query.push(c);
                *selected = 0;
            }
            _ => {}
        }
    }

    /// The outline: jump between Markdown headings, filtered by title.
    fn handle_outline_key(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let Mode::Outline {
            entries,
            query,
            selected,
        } = &mut self.mode
        else {
            return;
        };
        let matches: Vec<usize> = entries
            .iter()
            .enumerate()
            .filter(|(_, e)| {
                query.is_empty() || e.title.to_lowercase().contains(&query.to_lowercase())
            })
            .map(|(i, _)| i)
            .collect();
        match key.code {
            KeyCode::Esc => self.mode = Mode::Normal,
            KeyCode::Up => *selected = selected.saturating_sub(1),
            KeyCode::Down => *selected = (*selected + 1).min(matches.len().saturating_sub(1)),
            KeyCode::Char('e') if ctrl => *selected = selected.saturating_sub(1),
            KeyCode::Char('x') if ctrl => {
                *selected = (*selected + 1).min(matches.len().saturating_sub(1))
            }
            KeyCode::Backspace => {
                query.pop();
                *selected = 0;
            }
            KeyCode::Enter => {
                let target = matches.get(*selected).map(|&i| entries[i].char_pos);
                self.mode = Mode::Normal;
                if let Some(pos) = target {
                    self.long_jump(pos);
                }
            }
            KeyCode::Char(c) if !ctrl => {
                query.push(c);
                *selected = 0;
            }
            _ => {}
        }
    }

    /// The binder: project document list with navigation (^PB, task 1.3).
    fn handle_binder_key(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let Mode::Binder { entries, selected } = &mut self.mode else {
            return;
        };
        let num_entries = entries.len();
        match key.code {
            KeyCode::Esc => self.mode = Mode::Normal,
            KeyCode::Up => *selected = selected.saturating_sub(1),
            KeyCode::Down => *selected = (*selected + 1).min(num_entries.saturating_sub(1)),
            KeyCode::Char('e') if ctrl => *selected = selected.saturating_sub(1),
            KeyCode::Char('x') if ctrl => {
                *selected = (*selected + 1).min(num_entries.saturating_sub(1))
            }
            KeyCode::Enter => {
                // Open the selected document in the active pane.
                // R1.3: session restore is automatic via Pane::open.
                if let Some(entry) = entries.get(*selected) {
                    if !entry.exists {
                        self.status_msg = Some(format!("File missing: {}", entry.title));
                        return;
                    }
                    // Get the document path from the project.
                    if let Some(ref project) = self.project {
                        if let Some(doc) = project.manifest.docs.get(entry.idx) {
                            let path = doc.path.clone();
                            self.mode = Mode::Normal;
                            // Open the document in the active pane.
                            // This replaces the current pane's buffer and restores its session.
                            match crate::pane::Pane::open(Some(path)) {
                                Ok(pane) => {
                                    let journal = Journal::new(pane.buf.path.as_deref());
                                    self.panes[self.active] = pane;
                                    self.recovery_journals[self.active] = journal;
                                    self.status_msg = Some(format!("Opened: {}", doc.title));
                                }
                                Err(e) => {
                                    self.status_msg = Some(format!("Failed to open: {e}"));
                                }
                            }
                        }
                    }
                }
            }
            // Handle ^P prefix commands while in binder mode.
            KeyCode::Char('p') if ctrl => {
                self.prefix = Some((Prefix::P, Instant::now()));
            }
            _ => {}
        }
    }

    fn handle_prefixed(&mut self, prefix: Prefix, key: KeyEvent) {
        let code = match key.code {
            KeyCode::Char(c) => Some(c.to_ascii_lowercase()),
            _ => None,
        };
        match code {
            Some(d) if d.is_ascii_digit() => {
                let slot = d as usize - '0' as usize;
                match prefix {
                    Prefix::K => self.set_bookmark(slot),
                    Prefix::Q => self.jump_bookmark(slot),
                    Prefix::O | Prefix::P => {
                        self.status_msg = Some(String::from("Unknown command"))
                    }
                }
            }
            Some(c) => match keymap::lookup_prefixed(prefix, c) {
                Some(cmd) => self.execute(cmd),
                None => {
                    self.status_msg = Some(format!("Unknown command {}{c}", prefix_caret(prefix)))
                }
            },
            None if key.code == KeyCode::Esc => {}
            None => self.status_msg = Some(String::from("Unknown command")),
        }
    }

    fn execute(&mut self, cmd: Cmd) {
        if cmd != Cmd::Undo {
            self.history.break_chain();
        }
        if cmd != Cmd::Put {
            self.put_cycle = None;
        }
        match cmd {
            Cmd::Up => self.move_vertical(-1),
            Cmd::Down => self.move_vertical(1),
            Cmd::Left => self.set_cursor(self.buf.prev_grapheme(self.cursor)),
            Cmd::Right => self.set_cursor(self.buf.next_grapheme(self.cursor)),
            Cmd::WordLeft => self.set_cursor(self.buf.word_left(self.cursor)),
            Cmd::WordRight => self.set_cursor(self.buf.word_right(self.cursor)),
            Cmd::ScrollUp => self.scroll(-1),
            Cmd::ScrollDown => self.scroll(1),
            Cmd::PageUp => self.page(-1),
            Cmd::PageDown => self.page(1),
            Cmd::LineStart => self.set_cursor(self.buf.line_start(self.buf.line_of(self.cursor))),
            Cmd::LineEnd => self.set_cursor(self.buf.line_end(self.buf.line_of(self.cursor))),
            Cmd::ScreenTop => self.move_to_screen_row(0),
            Cmd::ScreenBottom => self.move_to_screen_row(self.view_rows.saturating_sub(1)),
            Cmd::DocStart => self.long_jump(0),
            Cmd::DocEnd => self.long_jump(self.buf.len_chars()),
            Cmd::SentenceBack => self.set_cursor(self.buf.sentence_back(self.cursor)),
            Cmd::SentenceFwd => self.set_cursor(self.buf.sentence_fwd(self.cursor)),
            Cmd::ParaBack => self.set_cursor(self.buf.para_back(self.cursor)),
            Cmd::ParaFwd => self.set_cursor(self.buf.para_fwd(self.cursor)),
            Cmd::PrevPosition => self.jump_back(),
            Cmd::Outline => {
                let entries = outline::scan(&self.buf);
                if entries.is_empty() {
                    self.status_msg = Some(String::from("No headings in this document"));
                } else {
                    self.mode = Mode::Outline {
                        entries,
                        query: String::new(),
                        selected: 0,
                    };
                }
            }
            Cmd::NextMisspelling => {
                if !self.spell_enabled {
                    self.status_msg = Some(String::from("Spellcheck is off (^OS to enable)"));
                } else if let Some(pos) = self.find_next_misspelling() {
                    self.long_jump(pos);
                } else {
                    self.status_msg = Some(String::from("No misspelled words found"));
                }
            }

            Cmd::DeleteRight => self.delete_right(),
            Cmd::DeleteLeft => self.delete_left(),
            Cmd::DeleteWordRight => {
                self.delete_range(self.cursor, self.buf.word_right(self.cursor), true)
            }
            Cmd::DeleteLine => self.delete_line(),
            Cmd::DeleteToLineEnd => self.delete_range(
                self.cursor,
                self.buf.line_end(self.buf.line_of(self.cursor)),
                true,
            ),
            Cmd::InsertBlankLine => self.insert_blank_line(),
            Cmd::TransposeWords => self.transpose_words(),
            Cmd::TransposeChars => self.transpose_chars(),
            Cmd::Undo => self.undo(),

            Cmd::FindIncremental => {
                self.history.break_group();
                self.mode = Mode::Search(SearchState::new(self.cursor));
            }
            Cmd::FindReplace => {
                self.history.break_group();
                self.mode = Mode::Replace(ReplaceState::new());
            }
            Cmd::FindNext => self.find_next(),

            Cmd::BlockBegin => {
                self.blocks.begin = Some(self.cursor);
                self.blocks.hidden = false;
                self.status_msg = Some(String::from("Block begin set"));
            }
            Cmd::BlockEnd => {
                self.blocks.end = Some(self.cursor);
                self.blocks.hidden = false;
                self.status_msg = Some(String::from("Block end set"));
            }
            Cmd::BlockCopy => self.block_copy(),
            Cmd::BlockMove => self.block_move(),
            Cmd::BlockDelete => self.block_delete(),
            Cmd::BlockWrite => {
                if self.blocks.range().is_some() {
                    self.mode = Mode::Input {
                        label: String::from("Write block to file"),
                        value: String::new(),
                        action: InputAction::WriteBlock,
                    };
                } else {
                    self.status_msg = Some(String::from("No block marked"));
                }
            }
            Cmd::BlockRead => {
                self.mode = Mode::Input {
                    label: String::from("Read file"),
                    value: String::new(),
                    action: InputAction::ReadFile,
                };
            }
            Cmd::BlockHide => {
                if self.blocks.range().is_some() {
                    self.blocks.hidden = !self.blocks.hidden;
                } else {
                    self.status_msg = Some(String::from("No block marked"));
                }
            }
            Cmd::BlockPrev => {
                if !self.blocks.toggle_previous() {
                    self.status_msg = Some(String::from("No previous block"));
                }
            }
            Cmd::Put => self.put(),
            Cmd::JumpBlockBegin => match self.blocks.begin {
                Some(p) => self.long_jump(p.min(self.buf.len_chars())),
                None => self.status_msg = Some(String::from("No block begin")),
            },
            Cmd::JumpBlockEnd => match self.blocks.end {
                Some(p) => self.long_jump(p.min(self.buf.len_chars())),
                None => self.status_msg = Some(String::from("No block end")),
            },
            Cmd::JumpBlockSource => match self.blocks.source {
                Some(p) => self.long_jump(p.min(self.buf.len_chars())),
                None => self.status_msg = Some(String::from("Block has not been moved")),
            },

            Cmd::Save => self.save(),
            Cmd::SaveExit => {
                self.save();
                if !self.buf.dirty {
                    self.close_or_quit();
                }
            }
            Cmd::Quit => {
                if self.buf.dirty {
                    self.mode = Mode::ConfirmAbandon;
                } else {
                    self.close_or_quit();
                }
            }
            Cmd::OtherWindow => {
                if self.panes.len() == 1 {
                    self.mode = Mode::Input {
                        label: String::from("Open in second window"),
                        value: String::new(),
                        action: InputAction::OpenSplit,
                    };
                } else {
                    self.active = 1 - self.active;
                }
            }
            Cmd::CopyFromOther => self.copy_from_other(),
            Cmd::CycleTheme => self.theme = self.theme.next(),
            Cmd::RevealCodes => self.reveal = !self.reveal,
            Cmd::ExportClean => {
                self.mode = Mode::Input {
                    label: String::from("Export to file (notes stripped)"),
                    value: String::new(),
                    action: InputAction::ExportClean,
                };
            }
            Cmd::ExportManuscript => {
                self.mode = Mode::Input {
                    label: String::from("Export manuscript RTF to file"),
                    value: String::new(),
                    action: InputAction::ExportManuscript,
                };
            }
            Cmd::ExportDocx => {
                self.mode = Mode::Input {
                    label: String::from("Export DOCX to file"),
                    value: String::new(),
                    action: InputAction::ExportDocx,
                };
            }
            Cmd::ExportEpub => {
                self.mode = Mode::Input {
                    label: String::from("Export EPUB to file"),
                    value: String::new(),
                    action: InputAction::ExportEpub,
                };
            }
            Cmd::ExportHtml => {
                self.mode = Mode::Input {
                    label: String::from("Export HTML to file"),
                    value: String::new(),
                    action: InputAction::ExportHtml,
                };
            }
            Cmd::ExportProjectDocx => {
                if self.project.is_some() {
                    self.mode = Mode::Input {
                        label: String::from("Export project DOCX to file"),
                        value: String::new(),
                        action: InputAction::ExportProjectDocx,
                    };
                } else {
                    self.status_msg = Some(String::from("No project loaded (^PP to open)"));
                }
            }
            Cmd::ExportProjectEpub => {
                if self.project.is_some() {
                    self.mode = Mode::Input {
                        label: String::from("Export project EPUB to file"),
                        value: String::new(),
                        action: InputAction::ExportProjectEpub,
                    };
                } else {
                    self.status_msg = Some(String::from("No project loaded (^PP to open)"));
                }
            }
            Cmd::ExportProjectHtml => {
                if self.project.is_some() {
                    self.mode = Mode::Input {
                        label: String::from("Export project HTML to file"),
                        value: String::new(),
                        action: InputAction::ExportProjectHtml,
                    };
                } else {
                    self.status_msg = Some(String::from("No project loaded (^PP to open)"));
                }
            }
            Cmd::ToggleWrap => {
                self.wrap = !self.wrap;
                self.left_col = 0;
                self.status_msg = Some(String::from(if self.wrap {
                    "Word wrap on"
                } else {
                    "Word wrap off"
                }));
            }
            Cmd::SetWrapMargin => {
                self.mode = Mode::Input {
                    label: String::from("Wrap margin in columns (0 = window width)"),
                    value: String::new(),
                    action: InputAction::WrapMargin,
                };
            }
            Cmd::ToggleInsert => {
                self.overtype = !self.overtype;
            }
            Cmd::CycleHelpLevel => {
                self.help_level = (self.help_level + 1) % 3;
                self.status_msg = Some(format!(
                    "Help level {}{}",
                    self.help_level,
                    match self.help_level {
                        0 => "clean screen",
                        1 => "delayed menus",
                        _ => "menus + hint bar",
                    }
                ));
            }
            Cmd::Palette => {
                self.mode = Mode::Palette {
                    query: String::new(),
                    selected: 0,
                };
            }
            Cmd::ToggleSpellcheck => {
                self.spell_enabled = !self.spell_enabled;
                self.status_msg = Some(String::from(if self.spell_enabled {
                    "Spellcheck on"
                } else {
                    "Spellcheck off"
                }));
            }
            Cmd::AddToDictionary => match self.word_at_cursor() {
                Some(w) => {
                    self.spell.learn(&w);
                    self.status_msg = Some(format!("Added \"{w}\" to personal dictionary"));
                }
                None => self.status_msg = Some(String::from("No word at cursor")),
            },
            Cmd::ToggleTypewriter => {
                self.typewriter = !self.typewriter;
                self.status_msg = Some(String::from(if self.typewriter {
                    "Typewriter scrolling on"
                } else {
                    "Typewriter scrolling off"
                }));
            }
            Cmd::MacroRecord => {
                if self.recording {
                    // Drop the ^Q,M chord that ended the recording.
                    let n = self.macro_keys.len();
                    self.macro_keys.truncate(n.saturating_sub(2));
                    self.recording = false;
                    self.status_msg =
                        Some(format!("Macro recorded ({} keys)", self.macro_keys.len()));
                } else {
                    self.macro_keys.clear();
                    self.recording = true;
                }
            }
            Cmd::MacroPlay => self.play_macro(),
            Cmd::ProjectNew => {
                self.mode = Mode::Input {
                    label: String::from("New project path (.pstarproj)"),
                    value: String::new(),
                    action: InputAction::ProjectNew,
                };
            }
            Cmd::ProjectOpen => {
                self.mode = Mode::Input {
                    label: String::from("Open project manifest (.pstarproj)"),
                    value: String::new(),
                    action: InputAction::ProjectOpen,
                };
            }
            Cmd::BinderToggle => {
                // Toggle binder panel (R1.2, task 1.3).
                // If already in binder mode, exit to normal. Otherwise, open the binder
                // if a project is loaded.
                if matches!(self.mode, Mode::Binder { .. }) {
                    self.mode = Mode::Normal;
                } else if let Some(ref project) = self.project {
                    // Build the binder entries.
                    let entries: Vec<BinderEntry> = project
                        .manifest
                        .docs
                        .iter()
                        .enumerate()
                        .map(|(idx, doc)| BinderEntry {
                            idx,
                            title: doc.title.clone(),
                            word_count: project.doc_word_count(idx),
                            exists: project.doc_exists(idx),
                        })
                        .collect();
                    self.mode = Mode::Binder {
                        entries,
                        selected: 0,
                    };
                } else {
                    self.status_msg = Some(String::from("No project loaded (^PP to open)"));
                }
            }
            Cmd::BinderMoveUp => self.binder_move_up(),
            Cmd::BinderMoveDown => self.binder_move_down(),
            Cmd::ProjectAddDoc => {
                if self.project.is_some() {
                    self.mode = Mode::Input {
                        label: String::from("Add document to project (file path)"),
                        value: String::new(),
                        action: InputAction::ProjectAddDoc,
                    };
                } else {
                    self.status_msg = Some(String::from("No project loaded (^PP to open)"));
                }
            }
            Cmd::ProjectRemoveDoc => self.project_remove_doc(),
            Cmd::WordCount => {
                self.show_word_count = !self.show_word_count;
                self.status_msg = Some(String::from(if self.show_word_count {
                    "Word count on"
                } else {
                    "Word count off"
                }));
            }
            Cmd::SetGoal => {
                self.mode = Mode::Input {
                    label: String::from("Session goal (words, e.g. 500)"),
                    value: String::new(),
                    action: InputAction::SetGoal,
                };
            }
            Cmd::StatsOverlay => {
                if matches!(self.mode, Mode::Stats) {
                    self.mode = Mode::Normal;
                } else {
                    self.mode = Mode::Stats;
                }
            }
            Cmd::ProjectFind => {
                if self.project.is_some() {
                    self.mode = Mode::Input {
                        label: String::from("Project search"),
                        value: String::new(),
                        action: InputAction::ProjectSearch,
                    };
                } else {
                    self.status_msg = Some(String::from("No project loaded (^PP to open)"));
                }
            }
            Cmd::ProjectReplace => {
                if self.project.is_some() {
                    self.mode = Mode::Input {
                        label: String::from("Project replace (find|replace)"),
                        value: String::new(),
                        action: InputAction::ProjectReplace,
                    };
                } else {
                    self.status_msg = Some(String::from("No project loaded (^PP to open)"));
                }
            }
        }
        if !matches!(cmd, Cmd::Undo) && !is_edit_cmd(cmd) {
            self.history.break_group();
        }
    }

    // --- movement -----------------------------------------------------------

    fn goal(&mut self) -> usize {
        match self.goal_col {
            Some(g) => g,
            None => {
                let g = self.buf.visual_col(self.cursor);
                self.goal_col = Some(g);
                g
            }
        }
    }

    /// Move to `pos`, resetting the sticky column.
    fn set_cursor(&mut self, pos: usize) {
        self.cursor = pos.min(self.buf.len_chars());
        self.goal_col = None;
        self.ensure_visible();
    }

    /// Remember the current position on the jump ring.
    fn push_jump(&mut self) {
        let cursor = self.cursor;
        if self.jump_stack.last() != Some(&cursor) {
            self.jump_stack.push(cursor);
            if self.jump_stack.len() > JUMP_STACK_MAX {
                self.jump_stack.remove(0);
            }
        }
    }

    /// A jump the writer will want to return from (^QP).
    fn long_jump(&mut self, pos: usize) {
        self.push_jump();
        self.set_cursor(pos);
    }

    /// ^QP: go back to where you were; repeated presses walk the ring.
    fn jump_back(&mut self) {
        while let Some(p) = self.jump_stack.pop() {
            let cursor = self.cursor;
            if p != cursor && p <= self.buf.len_chars() {
                // Rotate: the position we're leaving goes to the bottom, so
                // repeated ^QP cycles rather than exhausts.
                self.jump_stack.insert(0, cursor);
                self.set_cursor(p);
                return;
            }
        }
        self.status_msg = Some(String::from("No previous position"));
    }

    fn move_vertical(&mut self, delta: isize) {
        let line = self.buf.line_of(self.cursor);
        let goal = self.goal();
        let last = self.buf.len_lines().saturating_sub(1);
        let target = line.saturating_add_signed(delta).min(last);
        self.cursor = self.buf.char_at_visual_col(target, goal);
        self.ensure_visible();
    }

    fn move_to_screen_row(&mut self, row: usize) {
        let goal = self.goal();
        let last = self.buf.len_lines().saturating_sub(1);
        let target = (self.top_line + row).min(last);
        self.cursor = self.buf.char_at_visual_col(target, goal);
        self.ensure_visible();
    }

    /// Scroll the view by one line; the cursor is dragged along only if it
    /// would leave the screen (WordStar ^W/^Z behavior).
    fn scroll(&mut self, delta: isize) {
        let last = self.buf.len_lines().saturating_sub(1);
        self.top_line = self.top_line.saturating_add_signed(delta).min(last);
        let line = self.buf.line_of(self.cursor);
        let goal = self.goal();
        let bottom = self.top_line + self.view_rows.saturating_sub(1);
        if line < self.top_line {
            self.cursor = self.buf.char_at_visual_col(self.top_line, goal);
        } else if line > bottom {
            self.cursor = self.buf.char_at_visual_col(bottom.min(last), goal);
        }
    }

    fn page(&mut self, dir: isize) {
        let step = self.view_rows.saturating_sub(1).max(1);
        let last = self.buf.len_lines().saturating_sub(1);
        let line = self.buf.line_of(self.cursor);
        let goal = self.goal();
        let target = line.saturating_add_signed(dir * step as isize).min(last);
        self.top_line = self
            .top_line
            .saturating_add_signed(dir * step as isize)
            .min(last);
        self.cursor = self.buf.char_at_visual_col(target, goal);
        self.ensure_visible();
    }

    /// Keep the cursor inside the viewport, adjusting scroll as needed.
    pub fn ensure_visible(&mut self) {
        if let Some(width) = self.wrap_width() {
            self.ensure_visible_wrapped(width);
            return;
        }
        let line = self.buf.line_of(self.cursor);
        if self.typewriter {
            // Pin the cursor's line at a fixed row; the document scrolls
            // under it instead of the cursor moving to the edge.
            self.top_line = line.saturating_sub(self.view_rows / 2);
        } else if line < self.top_line {
            self.top_line = line;
        } else {
            let bottom = self.top_line + self.view_rows.saturating_sub(1);
            if line > bottom {
                self.top_line = line - self.view_rows.saturating_sub(1);
            }
        }
        let vcol = self.buf.visual_col(self.cursor);
        if vcol < self.left_col {
            self.left_col = vcol;
        }
        let width = self.view_cols.max(1);
        if vcol >= self.left_col + width {
            self.left_col = vcol + 1 - width;
        }
    }

    fn ensure_visible_wrapped(&mut self, width: usize) {
        self.left_col = 0;
        let cline = self.buf.line_of(self.cursor);

        if self.typewriter {
            // Walk back from the cursor's own wrapped segment, accumulating
            // rows, until we've gone back far enough to center it.
            let target_row = self.view_rows / 2;
            let (seg_idx, _) = self.cursor_segment(width);
            let mut line = cline;
            let mut accumulated = seg_idx;
            while accumulated < target_row && line > 0 {
                line -= 1;
                accumulated += wrap_segments(&self.buf.line_text(line), width).len().max(1);
            }
            self.top_line = line;
            return;
        }

        if cline < self.top_line {
            self.top_line = cline;
            return;
        }
        // Every line occupies at least one row, so this is a safe floor.
        if cline >= self.top_line + self.view_rows {
            self.top_line = cline + 1 - self.view_rows;
        }
        // Scroll down until the cursor's wrapped row fits.
        while self.top_line < cline {
            let mut rows = 0usize;
            for line in self.top_line..cline {
                rows += wrap_segments(&self.buf.line_text(line), width).len();
                if rows >= self.view_rows {
                    break;
                }
            }
            let (seg_idx, _) = self.cursor_segment(width);
            if rows + seg_idx + 1 <= self.view_rows {
                break;
            }
            self.top_line += 1;
        }
    }

    /// The cursor's wrapped-segment index within its line and its visual
    /// column within that segment.
    pub fn cursor_segment(&self, width: usize) -> (usize, usize) {
        let cline = self.buf.line_of(self.cursor);
        let text = self.buf.line_text(cline);
        let off = self.cursor - self.buf.line_start(cline);
        let segs = wrap_segments(&text, width);
        let idx = segs
            .iter()
            .position(|&(s, e)| off >= s && off < e)
            .unwrap_or(segs.len().saturating_sub(1));
        let (s, _) = segs[idx.min(segs.len() - 1)];
        let vcol = crate::buffer::segment_vcol(&text, s, off);
        (idx, vcol)
    }

    fn play_macro(&mut self) {
        if self.recording {
            self.status_msg = Some(String::from("Can't play while recording"));
            return;
        }
        if self.playing {
            return; // no recursive playback
        }
        if self.macro_keys.is_empty() {
            self.status_msg = Some(String::from("No macro recorded"));
            return;
        }
        self.playing = true;
        for key in self.macro_keys.clone() {
            if self.quit {
                break;
            }
            self.handle_key(key);
        }
        self.playing = false;
    }

    // --- bookmarks ------------------------------------------------------------

    fn set_bookmark(&mut self, slot: usize) {
        self.bookmarks[slot] = Some(self.cursor);
        self.status_msg = Some(format!("Bookmark {slot} set"));
    }

    fn jump_bookmark(&mut self, slot: usize) {
        match self.bookmarks[slot] {
            Some(p) => self.long_jump(p.min(self.buf.len_chars())),
            None => self.status_msg = Some(format!("Bookmark {slot} not set")),
        }
    }

    // --- spellcheck -------------------------------------------------------------

    /// The word span touching the cursor — either it's inside one, or it
    /// sits right after one, as it does right after typing a word.
    fn word_at_cursor(&self) -> Option<String> {
        let line = self.buf.line_of(self.cursor);
        let line_start = self.buf.line_start(line);
        let text = self.buf.line_text(line);
        let offset = self.cursor - line_start;
        spellcheck::word_spans(&text)
            .into_iter()
            .find(|&(s, e)| s != e && offset >= s && offset <= e)
            .map(|(s, e)| text.chars().skip(s).take(e - s).collect())
    }

    /// ^QN: the char position of the next misspelled word strictly after the
    /// cursor, wrapping around the whole document if nothing is found first.
    /// Note (`..`) lines are skipped, matching what's rendered.
    fn find_next_misspelling(&self) -> Option<usize> {
        let total_lines = self.buf.len_lines();
        if total_lines == 0 {
            return None;
        }
        let start_line = self.buf.line_of(self.cursor);
        for offset in 0..=total_lines {
            let line = (start_line + offset) % total_lines;
            let text = self.buf.line_text(line);
            if normalize::is_note_line(&text) {
                continue;
            }
            let line_start = self.buf.line_start(line);
            for (s, e) in spellcheck::word_spans(&text) {
                let char_pos = line_start + s;
                if offset == 0 && char_pos <= self.cursor {
                    continue;
                }
                let word: String = text.chars().skip(s).take(e - s).collect();
                if !self.spell.check(&word) {
                    return Some(char_pos);
                }
            }
        }
        None
    }

    // --- editing (all mutations go through here, feeding history) -----------

    /// Mutate the rope and keep every mark in step. Returns the deleted text.
    fn apply_raw(&mut self, at: usize, del_chars: usize, insert: &str) -> String {
        let deleted = if del_chars > 0 {
            self.buf.delete(at..at + del_chars)
        } else {
            String::new()
        };
        if !insert.is_empty() {
            self.buf.insert(at, insert);
        }
        self.buf.dirty = true;
        let ins = insert.chars().count();
        self.blocks.adjust(at, del_chars, ins);
        for b in self.bookmarks.iter_mut() {
            if let Some(p) = *b {
                *b = Some(adjust_pos(p, at, del_chars, ins));
            }
        }
        for p in self.jump_stack.iter_mut() {
            *p = adjust_pos(*p, at, del_chars, ins);
        }
        self.last_edit = Instant::now();

        // Incremental stats update over the affected lines.
        let from_line = self.buf.line_of(at);
        let end_pos = at + insert.chars().count();
        let to_line = self
            .buf
            .line_of(end_pos.min(self.buf.len_chars().saturating_sub(1)))
            + 1;
        // Split borrow: access the rope through the pane vec index to avoid
        // conflicting borrows of self (Deref goes through panes[active]).
        let active = self.active;
        self.doc_stats
            .invalidate_lines(&self.panes[active].buf.rope, from_line, to_line);

        deleted
    }

    /// Replace `del_chars` chars at `at` with `insert`, record it, and move
    /// the cursor to `cursor_after`. Returns the deleted text.
    fn apply_edit(
        &mut self,
        at: usize,
        del_chars: usize,
        insert: &str,
        kind: EditKind,
        cursor_after: usize,
    ) -> String {
        let cursor_before = self.cursor;
        let deleted = self.apply_raw(at, del_chars, insert);
        self.history.record(
            Edit {
                at,
                deleted: deleted.clone(),
                inserted: insert.to_string(),
            },
            kind,
            cursor_before,
            cursor_after,
        );
        self.cursor = cursor_after;
        self.goal_col = None;
        self.ensure_visible();
        deleted
    }

    fn insert_text(&mut self, text: &str, kind: EditKind) {
        // Overtype: a typed character replaces the one under the cursor,
        // except at line end (never eats the newline).
        let del = if self.overtype && kind == EditKind::InsertChar && text != "\n" {
            let end = self.buf.next_grapheme(self.cursor);
            let line_end = self.buf.line_end(self.buf.line_of(self.cursor));
            if end > self.cursor && self.cursor < line_end {
                end - self.cursor
            } else {
                0
            }
        } else {
            0
        };
        self.apply_edit(
            self.cursor,
            del,
            text,
            if del > 0 { EditKind::Other } else { kind },
            self.cursor + text.chars().count(),
        );
    }

    /// ^N: open a new line at the cursor without moving (WordStar behavior).
    fn insert_blank_line(&mut self) {
        self.apply_edit(self.cursor, 0, "\n", EditKind::Other, self.cursor);
    }

    fn delete_left(&mut self) {
        if self.cursor == 0 {
            return;
        }
        let start = self.buf.prev_grapheme(self.cursor);
        self.apply_edit(start, self.cursor - start, "", EditKind::DeleteLeft, start);
    }

    fn delete_right(&mut self) {
        let end = self.buf.next_grapheme(self.cursor);
        if end > self.cursor {
            self.apply_edit(
                self.cursor,
                end - self.cursor,
                "",
                EditKind::Other,
                self.cursor,
            );
        }
    }

    /// Delete a range; with `kill`, the text joins the kill ring.
    fn delete_range(&mut self, from: usize, to: usize, kill: bool) {
        if to > from {
            let deleted = self.apply_edit(from, to - from, "", EditKind::Other, from);
            if kill {
                self.kill.push(deleted);
            }
        }
    }

    /// ^Y: delete the whole line including its terminator.
    fn delete_line(&mut self) {
        let line = self.buf.line_of(self.cursor);
        let start = self.buf.line_start(line);
        let end = if line + 1 < self.buf.len_lines() {
            self.buf.line_start(line + 1)
        } else {
            self.buf.len_chars()
        };
        self.delete_range(start, end, true);
    }

    /// ^QG: swap the graphemes on either side of the cursor and advance
    /// (Emacs C-t semantics).
    fn transpose_chars(&mut self) {
        let len = self.buf.len_chars();
        if self.cursor == 0 || self.cursor >= len {
            return;
        }
        let a_start = self.buf.prev_grapheme(self.cursor);
        let b_end = self.buf.next_grapheme(self.cursor);
        let a: String = self.buf.rope.slice(a_start..self.cursor).to_string();
        let b: String = self.buf.rope.slice(self.cursor..b_end).to_string();
        if a.contains('\n') || b.contains('\n') {
            return;
        }
        let swapped = format!("{b}{a}");
        self.apply_edit(a_start, b_end - a_start, &swapped, EditKind::Other, b_end);
    }

    /// ^QT: swap the word before the cursor with the word after it, leaving
    /// the cursor after the pair (Emacs M-t semantics).
    fn transpose_words(&mut self) {
        let mut a_end = self.cursor;
        while a_end > 0 && !is_word(self.buf.rope.char(a_end - 1)) {
            a_end -= 1;
        }
        let a_start = self.buf.word_left(a_end);
        if a_end == 0 || a_start == a_end {
            return;
        }
        let len = self.buf.len_chars();
        let mut b_start = self.cursor;
        while b_start < len && !is_word(self.buf.rope.char(b_start)) {
            b_start += 1;
        }
        let mut b_end = b_start;
        while b_end < len && is_word(self.buf.rope.char(b_end)) {
            b_end += 1;
        }
        if b_start >= b_end || b_start < a_end {
            return;
        }
        let a: String = self.buf.rope.slice(a_start..a_end).to_string();
        let mid: String = self.buf.rope.slice(a_end..b_start).to_string();
        let b: String = self.buf.rope.slice(b_start..b_end).to_string();
        let swapped = format!("{b}{mid}{a}");
        self.apply_edit(a_start, b_end - a_start, &swapped, EditKind::Other, b_end);
    }

    fn undo(&mut self) {
        let Some(group) = self.history.next_undo() else {
            self.status_msg = Some(String::from("Nothing to undo"));
            return;
        };
        let mut inv_edits = Vec::with_capacity(group.edits.len());
        for e in group.edits.iter().rev() {
            let ins_len = e.inserted.chars().count();
            self.apply_raw(e.at, ins_len, &e.deleted);
            inv_edits.push(e.inverse());
        }
        let inverse = EditGroup {
            edits: inv_edits,
            cursor_before: group.cursor_after,
            cursor_after: group.cursor_before,
        };
        self.cursor = group.cursor_before.min(self.buf.len_chars());
        self.goal_col = None;
        self.history.confirm_undo(inverse);
        self.ensure_visible();
    }

    // --- blocks & kill ring ---------------------------------------------------

    fn block_copy(&mut self) {
        let Some((b, e)) = self.blocks.range() else {
            self.status_msg = Some(String::from("No block marked"));
            return;
        };
        let text: String = self.buf.rope.slice(b..e).to_string();
        let len = e - b;
        let at = self.cursor;
        self.kill.push(text.clone());
        self.blocks.remember();
        self.apply_edit(at, 0, &text, EditKind::Other, at);
        // The marks moved with the edit; re-point them at the fresh copy and
        // remember where it came from.
        self.blocks.begin = Some(at);
        self.blocks.end = Some(at + len);
        self.blocks.source = Some(adjust_pos(b, at, 0, len));
        self.blocks.hidden = false;
    }

    fn block_move(&mut self) {
        let Some((b, e)) = self.blocks.range() else {
            self.status_msg = Some(String::from("No block marked"));
            return;
        };
        let at = self.cursor;
        if at >= b && at <= e {
            self.status_msg = Some(String::from("Cursor is inside the block"));
            return;
        }
        let text: String = self.buf.rope.slice(b..e).to_string();
        let len = e - b;
        let cursor_before = self.cursor;
        // Two edits, one undo group: delete the block, insert it at the
        // destination (in post-delete coordinates).
        let dest = if at > e { at - len } else { at };
        self.apply_raw(b, len, "");
        self.apply_raw(dest, 0, &text);
        self.history.record_group(
            vec![
                Edit {
                    at: b,
                    deleted: text.clone(),
                    inserted: String::new(),
                },
                Edit {
                    at: dest,
                    deleted: String::new(),
                    inserted: text,
                },
            ],
            cursor_before,
            dest,
        );
        self.blocks.remember();
        self.blocks.begin = Some(dest);
        self.blocks.end = Some(dest + len);
        self.blocks.source = Some(b.min(self.buf.len_chars()));
        self.blocks.hidden = false;
        self.set_cursor(dest);
    }

    fn block_delete(&mut self) {
        let Some((b, e)) = self.blocks.range() else {
            self.status_msg = Some(String::from("No block marked"));
            return;
        };
        self.delete_range(b, e, true);
        self.blocks.begin = None;
        self.blocks.end = None;
    }

    /// ^KP: put the newest clipping; pressed again immediately, swap it for
    /// the next older one (Emacs yank-pop).
    fn put(&mut self) {
        match self.put_cycle {
            Some(PutCycle { at, chars, index }) => {
                if self.kill.len() < 2 {
                    self.status_msg = Some(String::from("No older clippings"));
                    return;
                }
                let next = (index + 1) % self.kill.len();
                let text = self.kill.get(next).cloned().unwrap_or_default();
                let n = text.chars().count();
                self.apply_edit(at, chars, &text, EditKind::Other, at + n);
                self.put_cycle = Some(PutCycle {
                    at,
                    chars: n,
                    index: next,
                });
                self.status_msg = Some(format!("Clipping {}/{}", next + 1, self.kill.len()));
            }
            None => {
                let Some(text) = self.kill.top() else {
                    self.status_msg = Some(String::from("Nothing to put"));
                    return;
                };
                let at = self.cursor;
                let n = text.chars().count();
                self.apply_edit(at, 0, &text, EditKind::Other, at + n);
                self.put_cycle = Some(PutCycle {
                    at,
                    chars: n,
                    index: 0,
                });
            }
        }
    }

    // --- input prompts (^KW, ^KR) ----------------------------------------------

    fn handle_input_key(&mut self, key: KeyEvent) {
        let Mode::Input { value, action, .. } = &mut self.mode else {
            return;
        };
        let action = *action;
        match key.code {
            KeyCode::Esc => self.mode = Mode::Normal,
            KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => value.push(c),
            KeyCode::Backspace => {
                value.pop();
            }
            KeyCode::Enter => {
                let path = value.trim().to_string();
                self.mode = Mode::Normal;
                if path.is_empty() {
                    return;
                }
                match action {
                    InputAction::WriteBlock => self.write_block(&path),
                    InputAction::ReadFile => self.read_file(&path),
                    InputAction::ExportClean => self.export_clean(&path),
                    InputAction::ExportManuscript => self.export_manuscript(&path),
                    InputAction::ExportDocx => self.export_with(&DocxExporter, &path, "DOCX"),
                    InputAction::ExportEpub => self.export_with(&EpubExporter, &path, "EPUB"),
                    InputAction::ExportHtml => self.export_with(&HtmlExporter, &path, "HTML"),
                    InputAction::ExportProjectDocx => {
                        self.export_project(&DocxExporter, &path, "DOCX")
                    }
                    InputAction::ExportProjectEpub => {
                        self.export_project(&EpubExporter, &path, "EPUB")
                    }
                    InputAction::ExportProjectHtml => {
                        self.export_project(&HtmlExporter, &path, "HTML")
                    }
                    InputAction::SaveAs => self.save_as(&path),
                    InputAction::OpenSplit => self.open_split(&path),
                    InputAction::WrapMargin => match path.parse::<usize>() {
                        Ok(n) => {
                            self.wrap_margin = n;
                            self.wrap = true;
                            self.left_col = 0;
                            self.status_msg = Some(if n == 0 {
                                String::from("Wrapping at window width")
                            } else {
                                format!("Wrapping at column {n}")
                            });
                        }
                        Err(_) => self.status_msg = Some(String::from("Not a number")),
                    },
                    InputAction::ProjectOpen => self.open_project(&path),
                    InputAction::ProjectNew => self.new_project(&path),
                    InputAction::ProjectAddDoc => self.project_add_doc(&path),
                    InputAction::SetGoal => match path.parse::<usize>() {
                        Ok(n) if n > 0 => {
                            self.goal =
                                Some(SessionGoal::new(GoalKind::Words, n, self.doc_stats.words));
                            self.goal_notified = false;
                            self.status_msg = Some(format!("Goal set: {n} words this session"));
                        }
                        _ => {
                            self.status_msg =
                                Some(String::from("Enter a positive number of words"));
                        }
                    },
                    InputAction::ProjectSearch => self.run_project_search(&path, None),
                    InputAction::ProjectReplace => {
                        // Format: "find|replace"
                        if let Some((find, replace)) = path.split_once('|') {
                            let find = find.to_string();
                            let replace = replace.to_string();
                            self.run_project_search(&find, Some(replace));
                        } else {
                            self.status_msg =
                                Some(String::from("Format: search|replacement (separate with |)"));
                        }
                    }
                }
            }
            _ => {}
        }
    }

    fn write_block(&mut self, path: &str) {
        let Some((b, e)) = self.blocks.range() else {
            return;
        };
        let text: String = self.buf.rope.slice(b..e).to_string();
        match std::fs::write(path, &text) {
            Ok(()) => self.status_msg = Some(format!("Block written to {path}")),
            Err(err) => self.status_msg = Some(format!("Write failed: {err}")),
        }
    }

    /// ^KE: write a copy with note lines stripped. Markdown and punctuation
    /// remain unchanged for compatibility with the original command.
    fn export_clean(&mut self, path: &str) {
        let doc = CompiledDoc::from_buffer(&self.buf);
        self.finish_export(&PlainTextExporter, &doc, path, "Plain text", 0);
    }

    /// ^KM remains a current-document standard-manuscript export.
    fn export_manuscript(&mut self, path: &str) {
        let doc = CompiledDoc::from_buffer(&self.buf);
        let exporter = rtf::RtfExporter {
            font: self.manuscript_font,
        };
        self.finish_export(&exporter, &doc, path, "Manuscript", 0);
    }

    /// New professional formats export the loaded project when present,
    /// otherwise the active document. Project compilation supplies binder
    /// order and the manifest's selected separators.
    fn export_with<E: Exporter>(&mut self, exporter: &E, path: &str, format: &str) {
        let doc = CompiledDoc::from_buffer(&self.buf);
        self.finish_export(exporter, &doc, path, format, 0);
    }

    /// Project-scoped export: compiles all included docs in binder order.
    /// Refuses if any open buffer matching an included doc is dirty (unsaved
    /// edits would be silently lost), or if any included doc is unreadable
    /// (the output would be an incomplete book).
    fn export_project<E: Exporter>(&mut self, exporter: &E, path: &str, format: &str) {
        let Some(ref project) = self.project else {
            self.status_msg = Some(String::from("No project loaded (^PP to open)"));
            return;
        };

        // Check for dirty open buffers that are part of the compile set.
        for pane in &self.panes {
            if !pane.buf.dirty {
                continue;
            }
            if let Some(ref pane_path) = pane.buf.path {
                for entry in &project.manifest.docs {
                    if entry.include_in_compile && entry.path == *pane_path {
                        self.status_msg = Some(format!(
                            "{format} export aborted: \"{}\" has unsaved changes — save first (^KS)",
                            entry.title
                        ));
                        return;
                    }
                }
            }
        }

        let compiled = project.compile();

        // Block export if any included doc was unreadable (R7.8 — never
        // silently replace a good export with an incomplete book).
        if !compiled.skipped.is_empty() {
            let names: Vec<&str> = compiled.skipped.iter().map(|s| s.title.as_str()).collect();
            self.status_msg = Some(format!(
                "{format} export aborted: cannot read included document(s): {}",
                names.join(", ")
            ));
            return;
        }

        let doc = CompiledDoc::from_compiled(&compiled.text);
        self.finish_export(exporter, &doc, path, format, 0);
    }

    fn finish_export<E: Exporter>(
        &mut self,
        exporter: &E,
        doc: &CompiledDoc,
        path: &str,
        format: &str,
        _skipped: usize,
    ) {
        match exporter.export(doc, Path::new(path)) {
            Ok(()) => {
                self.status_msg = Some(format!("{format} exported to {path}"));
            }
            Err(err) => self.status_msg = Some(format!("{format} export failed: {err}")),
        }
    }

    fn read_file(&mut self, path: &str) {
        match std::fs::read_to_string(path) {
            Ok(text) => {
                let n = text.chars().count();
                let at = self.cursor;
                self.apply_edit(at, 0, &text, EditKind::Other, at + n);
                self.status_msg = Some(format!("Read {path}"));
            }
            Err(err) => self.status_msg = Some(format!("Read failed: {err}")),
        }
    }

    // --- search -------------------------------------------------------------

    fn handle_search_key(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let Mode::Search(state) = &mut self.mode else {
            return;
        };
        match key.code {
            KeyCode::Esc => {
                let origin = state.origin;
                self.mode = Mode::Normal;
                self.set_cursor(origin);
            }
            KeyCode::Enter => {
                if !state.query.is_empty() {
                    self.last_search = Some(state.query.clone());
                }
                let origin = state.origin;
                let landed = state.current;
                self.mode = Mode::Normal;
                if landed.is_some() && origin != self.cursor {
                    self.jump_stack.push(origin);
                    if self.jump_stack.len() > JUMP_STACK_MAX {
                        self.jump_stack.remove(0);
                    }
                }
            }
            KeyCode::Backspace => {
                state.query.pop();
                self.search_update(false);
            }
            KeyCode::Char(c) if ctrl && (c == 'l' || c == 'f') => self.search_update(true),
            KeyCode::Char(c) if !ctrl => {
                state.query.push(c);
                self.search_update(false);
            }
            _ => {}
        }
    }

    /// Re-run the incremental search. With `next`, look past the current match.
    fn search_update(&mut self, next: bool) {
        let Mode::Search(state) = &mut self.mode else {
            return;
        };
        if state.query.is_empty() {
            let origin = state.origin;
            state.current = None;
            self.cursor = origin;
            self.ensure_visible();
            return;
        }
        let from = match (next, state.current) {
            (true, Some(cur)) => cur + 1,
            _ => state.current.unwrap_or(state.origin).min(state.origin),
        };
        let query = state.query.clone();
        let found = self
            .buf
            .find(&query, from.min(self.buf.len_chars()), false)
            .or_else(|| {
                if next {
                    self.buf.find(&query, 0, false)
                } else {
                    None
                }
            });
        match found {
            Some(at) => {
                let wrapped = next && at < from;
                if let Mode::Search(state) = &mut self.mode {
                    state.wrapped = wrapped;
                    state.current = Some(at);
                }
                self.cursor = at;
                self.goal_col = None;
                self.ensure_visible();
                if wrapped {
                    self.status_msg = Some(String::from("Wrapped to top"));
                }
            }
            None => {
                if let Mode::Search(state) = &mut self.mode {
                    state.current = None;
                }
                self.status_msg = Some(format!("Not found: {query}"));
            }
        }
    }

    /// ^L: jump to the next occurrence of the last search.
    fn find_next(&mut self) {
        let Some(query) = self.last_search.clone() else {
            self.status_msg = Some(String::from("No previous search"));
            return;
        };
        let from = self.cursor + 1;
        match self
            .buf
            .find(&query, from.min(self.buf.len_chars()), false)
            .or_else(|| self.buf.find(&query, 0, false))
        {
            Some(at) => {
                if at < from {
                    self.status_msg = Some(String::from("Wrapped to top"));
                }
                self.long_jump(at);
            }
            None => self.status_msg = Some(format!("Not found: {query}")),
        }
    }

    // --- replace ------------------------------------------------------------

    fn handle_replace_key(&mut self, key: KeyEvent) {
        let Mode::Replace(state) = &mut self.mode else {
            return;
        };
        if key.code == KeyCode::Esc {
            let count = state.count;
            let started = matches!(state.phase, ReplacePhase::Confirm(_));
            self.mode = Mode::Normal;
            if started {
                self.status_msg = Some(format!("Replaced {count} occurrence(s)"));
            }
            return;
        }
        match state.phase {
            ReplacePhase::EnterFind | ReplacePhase::EnterWith | ReplacePhase::EnterOptions => {
                let field = match state.phase {
                    ReplacePhase::EnterFind => &mut state.find,
                    ReplacePhase::EnterWith => &mut state.with,
                    _ => &mut state.options,
                };
                match key.code {
                    KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
                        field.push(c)
                    }
                    KeyCode::Backspace => {
                        field.pop();
                    }
                    KeyCode::Enter => match state.phase {
                        ReplacePhase::EnterFind => {
                            if state.find.is_empty() {
                                self.mode = Mode::Normal;
                            } else {
                                state.phase = ReplacePhase::EnterWith;
                            }
                        }
                        ReplacePhase::EnterWith => state.phase = ReplacePhase::EnterOptions,
                        _ => {
                            self.last_search = Some(state.find.clone());
                            let start = if state.from_top() { 0 } else { self.cursor };
                            self.push_jump();
                            self.replace_advance(start);
                        }
                    },
                    _ => {}
                }
            }
            ReplacePhase::Confirm(at) => match key.code {
                KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
                    self.replace_at(at);
                }
                KeyCode::Char('n') | KeyCode::Char('N') => {
                    self.replace_advance(at + 1);
                }
                KeyCode::Char('a') | KeyCode::Char('A') => {
                    let Mode::Replace(state) = &mut self.mode else {
                        return;
                    };
                    state.options.push('n');
                    self.replace_at(at);
                }
                KeyCode::Char('q') | KeyCode::Char('Q') => {
                    let count = state.count;
                    self.mode = Mode::Normal;
                    self.status_msg = Some(format!("Replaced {count} occurrence(s)"));
                }
                _ => {}
            },
        }
    }

    /// Find the next match at or after `from`; ask about it, or in no-ask
    /// mode keep replacing until the matches run out.
    fn replace_advance(&mut self, mut from: usize) {
        loop {
            let Mode::Replace(state) = &mut self.mode else {
                return;
            };
            let find = state.find.clone();
            let whole = state.whole_word();
            let no_ask = state.no_ask();
            match self.buf.find(&find, from.min(self.buf.len_chars()), whole) {
                Some(at) if no_ask => {
                    from = self.do_replace(at);
                }
                Some(at) => {
                    let Mode::Replace(state) = &mut self.mode else {
                        return;
                    };
                    state.phase = ReplacePhase::Confirm(at);
                    self.cursor = at;
                    self.goal_col = None;
                    self.ensure_visible();
                    return;
                }
                None => {
                    let count = match &self.mode {
                        Mode::Replace(state) => state.count,
                        _ => 0,
                    };
                    self.mode = Mode::Normal;
                    self.status_msg = Some(format!("Replaced {count} occurrence(s)"));
                    self.ensure_visible();
                    return;
                }
            }
        }
    }

    /// Replace the match at `at`; returns the position to continue from.
    fn do_replace(&mut self, at: usize) -> usize {
        let Mode::Replace(state) = &mut self.mode else {
            return at + 1;
        };
        let find_len = state.find.chars().count();
        let with = state.with.clone();
        state.count += 1;
        let after = at + with.chars().count();
        self.apply_edit(at, find_len, &with, EditKind::Other, after);
        after.max(at + 1)
    }

    /// Replace the match at `at` interactively and step to the next one.
    fn replace_at(&mut self, at: usize) {
        let from = self.do_replace(at);
        self.replace_advance(from);
    }

    // --- file ops -------------------------------------------------------------

    fn save(&mut self) {
        match self.buf.save() {
            Ok(()) => self.finish_save(),
            Err(error) => self.prompt_alternate_save(error),
        }
    }

    fn save_as(&mut self, path: &str) {
        match self.buf.save_as(PathBuf::from(path)) {
            Ok(()) => self.finish_save(),
            Err(error) => self.prompt_alternate_save(error),
        }
    }

    fn finish_save(&mut self) {
        let file_name = self.buf.file_name();
        let source = self.buf.path.clone();
        let mut warnings = Vec::new();
        if let Err(error) = write_backup_after_save(
            self.backup_root.as_deref(),
            source.as_deref(),
            self.backup_depth,
        ) {
            warnings.push(format!("rolling backup failed: {error}"));
        }
        if let Err(error) = self.recovery_journals[self.active].clear() {
            warnings.push(format!("recovery cleanup failed: {error}"));
        }
        // Save As may have changed the buffer path, so future dirty edits need
        // a journal keyed to the newly adopted destination.
        self.recovery_journals[self.active] = Journal::new(source.as_deref());
        self.save_session();
        self.status_msg = Some(if warnings.is_empty() {
            format!("Saved {file_name}")
        } else {
            format!("Saved {file_name}; {}", warnings.join("; "))
        });
    }

    fn prompt_alternate_save(&mut self, error: io::Error) {
        let message = format!("Save failed: {error}");
        self.status_msg = Some(message.clone());
        self.mode = Mode::Input {
            label: format!("{message}. Alternate save path"),
            value: String::new(),
            action: InputAction::SaveAs,
        };
    }

    // --- windows ---------------------------------------------------------------

    /// ^KQ/^KX: with two windows, close just the active one; with one, quit.
    fn close_or_quit(&mut self) {
        if self.panes.len() > 1 {
            self.panes[self.active].save_session();
            let pane = self.panes.remove(self.active);
            let mut journal = self.recovery_journals.remove(self.active);
            if !pane.buf.dirty {
                let _ = journal.clear();
            }
            self.active = 0;
            self.status_msg = Some(String::from("Window closed"));
        } else {
            if !self.buf.dirty {
                let _ = self.recovery_journals[self.active].clear();
            }
            self.quit = true;
        }
    }

    /// ^OK with one window: open `path` in a second window below and focus it.
    fn open_split(&mut self, path: &str) {
        if self.panes.len() >= 2 {
            return;
        }
        match Pane::open(Some(PathBuf::from(path))) {
            Ok(pane) => {
                let journal = Journal::new(pane.buf.path.as_deref());
                self.panes.push(pane);
                self.recovery_journals.push(journal);
                self.active = self.panes.len() - 1;
            }
            Err(e) => self.status_msg = Some(format!("Open failed: {e}")),
        }
    }

    /// ^KA (WordStar): copy the block marked in the *other* window to the
    /// cursor here. Each window keeps its own marked block — this is the
    /// bridge between them. The copy becomes this window's marked block,
    /// mirroring ^KC's behavior within one document.
    fn copy_from_other(&mut self) {
        if self.panes.len() < 2 {
            self.status_msg = Some(String::from("No second window (^OK opens one)"));
            return;
        }
        let other = 1 - self.active;
        let Some((b, e)) = self.panes[other].blocks.range() else {
            self.status_msg = Some(String::from("No block marked in the other window"));
            return;
        };
        let text: String = self.panes[other].buf.rope.slice(b..e).to_string();
        let len = e - b;
        let at = self.cursor;
        self.blocks.remember();
        self.apply_edit(at, 0, &text, EditKind::Other, at);
        self.blocks.begin = Some(at);
        self.blocks.end = Some(at + len);
        self.blocks.hidden = false;
        self.status_msg = Some(String::from("Block copied from other window"));
    }

    // --- project management ---------------------------------------------------

    /// Open a project from a .pstarproj manifest file (R1, task 1.2).
    /// Stores the loaded project in `self.project`, or shows an error if the
    /// load fails (file not found, TOML parse error). Keeps `self.project` as
    /// `None` on failure, so the editor stays usable (C3: never lose work).
    fn open_project(&mut self, path: &str) {
        use std::path::Path;

        let manifest_path = Path::new(path);

        // Load the project using Project::load from project.rs
        match Project::load(manifest_path) {
            Ok(proj) => {
                let name = proj.manifest.name.clone();
                let count = proj.manifest.docs.len();
                self.project = Some(proj);
                self.status_msg = Some(format!(
                    "Project \"{}\" opened ({} document{})",
                    name,
                    count,
                    if count == 1 { "" } else { "s" }
                ));
            }
            Err(e) => {
                // R1.8: backward compatibility — keep project as None on error
                self.project = None;
                self.status_msg = Some(format!("Failed to open project: {}", e));
            }
        }
    }

    /// Create a new project manifest at the given path (^PN).
    ///
    /// The user supplies a path ending in `.pstarproj`. The project name is
    /// derived from the file stem (e.g. `MyNovel.pstarproj` → name "MyNovel").
    /// The manifest is written atomically (R11.5) and immediately loaded so the
    /// binder and other project commands become available.
    fn new_project(&mut self, path: &str) {
        use crate::paths;
        use crate::project::{ProjectManifest, Separator};
        use std::path::Path;

        let manifest_path = Path::new(path);

        // Ensure the path has the .pstarproj extension.
        let has_ext = manifest_path
            .extension()
            .map(|e| e == "pstarproj")
            .unwrap_or(false);
        let manifest_path = if has_ext {
            manifest_path.to_path_buf()
        } else {
            manifest_path.with_extension("pstarproj")
        };

        // Don't overwrite an existing manifest — use ^PP to open it instead.
        if manifest_path.exists() {
            self.status_msg = Some(String::from(
                "File already exists (use ^PP to open an existing project)",
            ));
            return;
        }

        // Ensure the parent directory exists.
        if let Some(parent) = manifest_path.parent() {
            if !parent.exists() {
                if let Err(e) = std::fs::create_dir_all(parent) {
                    self.status_msg = Some(format!("Cannot create directory: {e}"));
                    return;
                }
            }
        }

        // Derive the project name from the file stem.
        let name = manifest_path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("Untitled")
            .to_string();

        // Build an empty manifest.
        let manifest = ProjectManifest {
            name: name.clone(),
            docs: Vec::new(),
            separator: Separator::default(),
        };

        // Serialize and write atomically.
        let data = match toml::to_string_pretty(&manifest) {
            Ok(s) => s,
            Err(e) => {
                self.status_msg = Some(format!("Failed to serialize manifest: {e}"));
                return;
            }
        };
        if let Err(e) = paths::write_atomic(&manifest_path, data.as_bytes()) {
            self.status_msg = Some(format!("Failed to write manifest: {e}"));
            return;
        }

        // Load the freshly-created project so it's immediately active.
        match Project::load(&manifest_path) {
            Ok(proj) => {
                self.project = Some(proj);
                self.status_msg = Some(format!(
                    "Project \"{name}\" created (use ^PA to add documents)"
                ));
            }
            Err(e) => {
                self.status_msg = Some(format!("Created manifest but failed to load: {e}"));
            }
        }
    }

    /// Move the selected document up in the binder (^PE, R1.4, task 1.4).
    /// Only works when in binder mode. Updates the manifest atomically.
    fn binder_move_up(&mut self) {
        // Check if we're in binder mode.
        let Mode::Binder { selected, .. } = &self.mode else {
            self.status_msg = Some(String::from("Not in binder mode"));
            return;
        };
        let selected_idx = *selected;

        // Can't move the first document up.
        if selected_idx == 0 {
            self.status_msg = Some(String::from("Already at top"));
            return;
        }

        // Perform the reorder on the project.
        if let Some(ref mut project) = self.project {
            let from = selected_idx;
            let to = selected_idx - 1;
            project.reorder_doc(from, to);

            // Save the manifest atomically (R1.4, R11.5).
            match project.save() {
                Ok(()) => {
                    self.status_msg = Some(String::from("Document moved up"));
                    // Refresh the binder to show the new order, with selection following the moved doc.
                    self.refresh_binder_with_selection(to);
                }
                Err(e) => {
                    // On save error, keep the old state in memory and show error.
                    // Reload the project to revert the in-memory change.
                    let manifest_path = project.manifest_path.clone();
                    match Project::load(&manifest_path) {
                        Ok(proj) => self.project = Some(proj),
                        Err(_) => self.project = None,
                    }
                    self.status_msg = Some(format!("Failed to save manifest: {e}"));
                }
            }
        } else {
            self.status_msg = Some(String::from("No project loaded"));
        }
    }

    /// Move the selected document down in the binder (^PX, R1.4, task 1.4).
    /// Only works when in binder mode. Updates the manifest atomically.
    fn binder_move_down(&mut self) {
        // Check if we're in binder mode.
        let Mode::Binder { selected, .. } = &self.mode else {
            self.status_msg = Some(String::from("Not in binder mode"));
            return;
        };
        let selected_idx = *selected;

        // Get the project and check if we can move down.
        let Some(ref mut project) = self.project else {
            self.status_msg = Some(String::from("No project loaded"));
            return;
        };

        let num_docs = project.manifest.docs.len();
        if selected_idx + 1 >= num_docs {
            self.status_msg = Some(String::from("Already at bottom"));
            return;
        }

        // Perform the reorder.
        let from = selected_idx;
        let to = selected_idx + 1;
        project.reorder_doc(from, to);

        // Save the manifest atomically (R1.4, R11.5).
        match project.save() {
            Ok(()) => {
                self.status_msg = Some(String::from("Document moved down"));
                // Refresh the binder to show the new order, with selection following the moved doc.
                self.refresh_binder_with_selection(to);
            }
            Err(e) => {
                // On save error, revert the in-memory change by reloading.
                let manifest_path = project.manifest_path.clone();
                match Project::load(&manifest_path) {
                    Ok(proj) => self.project = Some(proj),
                    Err(_) => self.project = None,
                }
                self.status_msg = Some(format!("Failed to save manifest: {e}"));
            }
        }
    }

    /// Refresh the binder panel with updated entries, maintaining a specific selection.
    fn refresh_binder_with_selection(&mut self, new_selected: usize) {
        if let Some(ref project) = self.project {
            let entries: Vec<BinderEntry> = project
                .manifest
                .docs
                .iter()
                .enumerate()
                .map(|(idx, doc)| BinderEntry {
                    idx,
                    title: doc.title.clone(),
                    word_count: project.doc_word_count(idx),
                    exists: project.doc_exists(idx),
                })
                .collect();
            let selected = new_selected.min(entries.len().saturating_sub(1));
            self.mode = Mode::Binder { entries, selected };
        }
    }

    /// Add a document to the project (^PA, R1.5, task 1.4).
    /// Prompts for a file path, generates a title, adds to the manifest, and saves atomically.
    fn project_add_doc(&mut self, path: &str) {
        use std::path::Path;

        let file_path = Path::new(path);

        // Check if the file exists (R1.5).
        if !file_path.exists() {
            self.status_msg = Some(format!("File not found: {path}"));
            return;
        }

        // Generate a title from the file stem or first heading.
        // For simplicity, use the file stem; a future enhancement could scan for headings.
        let title = file_path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("Untitled")
            .to_string();

        // Check if we need to refresh binder before mutating project.
        let in_binder = matches!(self.mode, Mode::Binder { .. });

        // Add to the project.
        if let Some(ref mut project) = self.project {
            project.add_doc(file_path.to_path_buf(), title.clone());

            // Save the manifest atomically (R1.4, R11.5).
            let save_result = project.save();
            let new_idx = project.manifest.docs.len() - 1;
            let manifest_path_on_error = project.manifest_path.clone();

            match save_result {
                Ok(()) => {
                    self.status_msg = Some(format!("Added: {title}"));
                }
                Err(e) => {
                    // On save error, revert the in-memory change by reloading.
                    match Project::load(&manifest_path_on_error) {
                        Ok(proj) => self.project = Some(proj),
                        Err(_) => self.project = None,
                    }
                    self.status_msg = Some(format!("Failed to save manifest: {e}"));
                    return;
                }
            }

            // If in binder mode, refresh to show the new document.
            if in_binder {
                self.refresh_binder_with_selection(new_idx);
            }
        } else {
            self.status_msg = Some(String::from("No project loaded"));
        }
    }

    /// Remove a document from the project (^PR, R1.5, task 1.4).
    /// When in binder mode, removes the selected document. The file on disk is NEVER deleted (R1.5).
    fn project_remove_doc(&mut self) {
        // Check if we're in binder mode.
        let Mode::Binder { selected, .. } = &self.mode else {
            self.status_msg = Some(String::from("Use this command in binder mode (^PB)"));
            return;
        };
        let selected_idx = *selected;

        // Remove from the project.
        if let Some(ref mut project) = self.project {
            if let Some(removed) = project.remove_doc(selected_idx) {
                // Save the manifest atomically (R1.4, R11.5).
                match project.save() {
                    Ok(()) => {
                        // R1.5: clear message that the file is kept on disk.
                        self.status_msg = Some(format!(
                            "\"{}\" removed from project (file kept on disk)",
                            removed.title
                        ));
                        // Refresh the binder, adjusting selection if needed.
                        let new_selected = if project.manifest.docs.is_empty() {
                            0
                        } else {
                            selected_idx.min(project.manifest.docs.len().saturating_sub(1))
                        };
                        self.refresh_binder_with_selection(new_selected);
                    }
                    Err(e) => {
                        // On save error, revert by reloading the project.
                        let manifest_path = project.manifest_path.clone();
                        match Project::load(&manifest_path) {
                            Ok(proj) => self.project = Some(proj),
                            Err(_) => self.project = None,
                        }
                        self.status_msg = Some(format!("Failed to save manifest: {e}"));
                    }
                }
            } else {
                self.status_msg = Some(String::from("Invalid document index"));
            }
        } else {
            self.status_msg = Some(String::from("No project loaded"));
        }
    }

    // --- project-wide search (R6) -------------------------------------------

    fn run_project_search(&mut self, query: &str, replace_with: Option<String>) {
        let Some(ref project) = self.project else {
            self.status_msg = Some(String::from("No project loaded"));
            return;
        };
        let docs: Vec<(usize, String, std::path::PathBuf)> = project
            .manifest
            .docs
            .iter()
            .enumerate()
            .map(|(i, d)| (i, d.title.clone(), d.path.clone()))
            .collect();

        let active_path = self.panes[self.active].buf.path.clone();
        let results = projsearch::search_project(
            &docs,
            query,
            false,
            active_path.as_deref(),
            Some(&self.panes[self.active].buf.rope),
        );

        if results.is_empty() {
            self.status_msg = Some(format!("No matches for \"{query}\" in project"));
            return;
        }
        let count = results.len();
        self.mode = Mode::ProjectSearch {
            query: query.to_string(),
            results,
            selected: 0,
            replace_with,
        };
        self.status_msg = Some(format!("{count} match(es) found"));
    }

    fn handle_project_search_key(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let (num_results, selected, replace_with) = {
            let Mode::ProjectSearch {
                results,
                selected,
                replace_with,
                ..
            } = &self.mode
            else {
                return;
            };
            (results.len(), *selected, replace_with.clone())
        };
        match key.code {
            KeyCode::Esc => self.mode = Mode::Normal,
            KeyCode::Up | KeyCode::Char('e') if ctrl || matches!(key.code, KeyCode::Up) => {
                if let Mode::ProjectSearch { selected, .. } = &mut self.mode {
                    *selected = selected.saturating_sub(1);
                }
            }
            KeyCode::Down | KeyCode::Char('x') if ctrl || matches!(key.code, KeyCode::Down) => {
                if let Mode::ProjectSearch { selected, .. } = &mut self.mode {
                    *selected = (*selected + 1).min(num_results.saturating_sub(1));
                }
            }
            KeyCode::Enter => {
                // Jump to the selected result (R6.2).
                self.project_search_jump(selected);
            }
            KeyCode::Char('r') if ctrl && replace_with.is_some() => {
                // Replace at current match and advance (R6.3).
                self.project_search_replace_at(selected);
            }
            KeyCode::Char('a') if ctrl && replace_with.is_some() => {
                // Replace all remaining (R6.3).
                self.project_search_replace_all();
            }
            _ => {}
        }
    }

    fn project_search_jump(&mut self, idx: usize) {
        let (path, char_pos) = {
            let Mode::ProjectSearch { results, .. } = &self.mode else {
                return;
            };
            let Some(m) = results.get(idx) else { return };
            (m.path.clone(), m.char_pos)
        };
        self.mode = Mode::Normal;

        // If the file is already in the active pane, just jump.
        if self.panes[self.active].buf.path.as_deref() == Some(path.as_path()) {
            self.long_jump(char_pos);
            return;
        }

        // Open the doc (R6.2).
        match Pane::open(Some(path)) {
            Ok(pane) => {
                let journal = Journal::new(pane.buf.path.as_deref());
                self.panes[self.active] = pane;
                self.recovery_journals[self.active] = journal;
                // Recompute stats for the new document.
                self.doc_stats =
                    crate::stats::DocStats::from_rope(&self.panes[self.active].buf.rope);
                self.long_jump(char_pos);
            }
            Err(e) => {
                self.status_msg = Some(format!("Failed to open: {e}"));
            }
        }
    }

    fn project_search_replace_at(&mut self, idx: usize) {
        let (path, char_pos, query_len, replacement) = {
            let Mode::ProjectSearch {
                results,
                query,
                replace_with,
                ..
            } = &self.mode
            else {
                return;
            };
            let Some(m) = results.get(idx) else { return };
            let Some(rep) = replace_with.as_ref() else {
                return;
            };
            (
                m.path.clone(),
                m.char_pos,
                query.chars().count(),
                rep.clone(),
            )
        };

        // Ensure the file is open in the active pane.
        if self.panes[self.active].buf.path.as_deref() != Some(path.as_path()) {
            match Pane::open(Some(path)) {
                Ok(pane) => {
                    let journal = Journal::new(pane.buf.path.as_deref());
                    self.panes[self.active] = pane;
                    self.recovery_journals[self.active] = journal;
                    self.doc_stats =
                        crate::stats::DocStats::from_rope(&self.panes[self.active].buf.rope);
                }
                Err(e) => {
                    self.status_msg = Some(format!("Failed to open for replace: {e}"));
                    return;
                }
            }
        }

        // Apply the replacement as an undoable edit (R6.4, R6.6).
        self.set_cursor(char_pos);
        self.apply_edit(
            char_pos,
            query_len,
            &replacement,
            EditKind::Other,
            char_pos + replacement.chars().count(),
        );
        self.save();

        // Advance to next result (remove current from the list).
        if let Mode::ProjectSearch {
            results, selected, ..
        } = &mut self.mode
        {
            results.remove(idx);
            if results.is_empty() {
                self.mode = Mode::Normal;
                self.status_msg = Some(String::from("All replacements done"));
            } else {
                *selected = idx.min(results.len().saturating_sub(1));
            }
        }
    }

    fn project_search_replace_all(&mut self) {
        // Replace from the end to preserve char positions within each file.
        let entries = {
            let Mode::ProjectSearch {
                results,
                query,
                replace_with,
                ..
            } = &self.mode
            else {
                return;
            };
            let Some(rep) = replace_with.as_ref() else {
                return;
            };
            // Group by path, process in reverse char-pos order so offsets stay valid.
            let mut entries: Vec<(std::path::PathBuf, usize, usize, String)> = results
                .iter()
                .map(|m| {
                    (
                        m.path.clone(),
                        m.char_pos,
                        query.chars().count(),
                        rep.clone(),
                    )
                })
                .collect();
            entries.sort_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)));
            entries
        };

        let mut count = 0usize;
        let mut last_path: Option<std::path::PathBuf> = None;

        for (path, char_pos, query_len, replacement) in &entries {
            // Open file if not already loaded.
            if self.panes[self.active].buf.path.as_deref() != Some(path.as_path()) {
                // Save previous file if it was modified.
                if self.panes[self.active].buf.dirty {
                    self.save();
                }
                match Pane::open(Some(path.clone())) {
                    Ok(pane) => {
                        let journal = Journal::new(pane.buf.path.as_deref());
                        self.panes[self.active] = pane;
                        self.recovery_journals[self.active] = journal;
                        self.doc_stats =
                            crate::stats::DocStats::from_rope(&self.panes[self.active].buf.rope);
                    }
                    Err(_) => continue,
                }
            }
            last_path = Some(path.clone());
            self.set_cursor(*char_pos);
            self.apply_edit(
                *char_pos,
                *query_len,
                replacement,
                EditKind::Other,
                char_pos + replacement.chars().count(),
            );
            count += 1;
        }

        // Save the last modified file.
        if self.panes[self.active].buf.dirty {
            self.save();
        }
        let _ = last_path; // suppress unused warning
        self.mode = Mode::Normal;
        self.status_msg = Some(format!("{count} replacement(s) made"));
    }
}

fn write_backup_after_save(
    root: Option<&Path>,
    source: Option<&Path>,
    depth: usize,
) -> io::Result<()> {
    if depth == 0 {
        return Ok(());
    }
    let root = root.ok_or_else(|| io::Error::other("metadata directory is unavailable"))?;
    let source = source.ok_or_else(|| io::Error::other("saved document has no path"))?;
    recovery::write_rolling_backup(root, source, depth).map(|_| ())
}

fn is_word(c: char) -> bool {
    c.is_alphanumeric() || c == '_' || c == '\''
}

fn is_prefix_key(key: &KeyEvent) -> bool {
    matches!(key.code, KeyCode::Char(c)
        if key.modifiers.contains(KeyModifiers::CONTROL)
            && matches!(c.to_ascii_lowercase(), 'k' | 'q' | 'o' | 'p'))
}

fn is_edit_cmd(cmd: Cmd) -> bool {
    matches!(
        cmd,
        Cmd::DeleteRight
            | Cmd::DeleteLeft
            | Cmd::DeleteWordRight
            | Cmd::DeleteLine
            | Cmd::DeleteToLineEnd
            | Cmd::InsertBlankLine
            | Cmd::TransposeWords
            | Cmd::TransposeChars
            | Cmd::BlockCopy
            | Cmd::BlockMove
            | Cmd::BlockDelete
            | Cmd::Put
            | Cmd::CopyFromOther
    )
}

fn prefix_caret(prefix: Prefix) -> &'static str {
    match prefix {
        Prefix::K => "^K",
        Prefix::Q => "^Q",
        Prefix::O => "^O",
        Prefix::P => "^P",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::project::{DocEntry, ProjectManifest};
    use ropey::Rope;

    fn scratch_dir(tag: &str) -> std::path::PathBuf {
        use std::sync::atomic::{AtomicU64, Ordering};
        static COUNTER: AtomicU64 = AtomicU64::new(0);
        let id = COUNTER.fetch_add(1, Ordering::Relaxed);
        std::env::temp_dir().join(format!("pstar-app-{tag}-{}-{id}", std::process::id()))
    }

    #[test]
    fn save_failure_preserves_every_copy_then_alternate_save_succeeds() {
        let dir = scratch_dir("save-failure");
        std::fs::create_dir_all(&dir).unwrap();
        let failed_path = dir.join("chapter.md");
        let alternate_path = dir.join("recovered.md");
        let disk_text = "previous good manuscript";
        std::fs::write(&failed_path, disk_text).unwrap();

        let mut app = App::new(Some(failed_path.clone())).unwrap();
        let end = app.buf.len_chars();
        app.buf.insert(end, " with unsaved changes");
        let expected_text = app.buf.rope.to_string();
        let recovery_root = dir.join("recovery");
        app.backup_depth = 2;
        app.backup_root = Some(recovery_root.clone());
        app.recovery_journals[0] = Journal::in_root(&recovery_root, Some(&failed_path), "unused");
        app.maybe_autosave();
        let recovery_path = app.recovery_journals[0].path().unwrap().to_path_buf();
        assert_eq!(
            std::fs::read_to_string(&recovery_path).unwrap(),
            expected_text
        );

        // A directory at the atomic helper's sibling temp path deterministically
        // simulates a write failure while a prior good manuscript exists.
        let mut temporary = failed_path.clone().into_os_string();
        temporary.push(".tmp~");
        std::fs::create_dir(PathBuf::from(temporary)).unwrap();

        // Exercise the actual command arm, not just Buffer::save directly.
        app.execute(Cmd::Save);

        assert_eq!(app.buf.rope.to_string(), expected_text);
        assert_eq!(app.buf.path.as_deref(), Some(failed_path.as_path()));
        assert!(app.buf.dirty);
        assert_eq!(std::fs::read_to_string(&failed_path).unwrap(), disk_text);
        assert_eq!(
            std::fs::read_to_string(failed_path.with_extension("md.bak")).unwrap(),
            disk_text
        );
        assert_eq!(
            std::fs::read_to_string(&recovery_path).unwrap(),
            expected_text
        );
        assert!(
            app.status_msg
                .as_deref()
                .unwrap()
                .starts_with("Save failed:")
        );
        match &app.mode {
            Mode::Input {
                label,
                action: InputAction::SaveAs,
                ..
            } => {
                assert!(label.contains("Save failed:"));
                assert!(label.contains("Alternate save path"));
            }
            _ => panic!("save failure did not open the alternate-path prompt"),
        }

        if let Mode::Input { value, .. } = &mut app.mode {
            *value = alternate_path.to_string_lossy().into_owned();
        }
        app.handle_input_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));

        assert!(matches!(app.mode, Mode::Normal));
        assert_eq!(app.buf.path.as_deref(), Some(alternate_path.as_path()));
        assert!(!app.buf.dirty);
        assert!(
            !recovery_path.exists(),
            "successful Save As left the old recovery journal"
        );
        assert_eq!(std::fs::read_to_string(&failed_path).unwrap(), disk_text);
        assert_eq!(
            std::fs::read_to_string(&alternate_path).unwrap(),
            expected_text
        );
        assert_eq!(
            app.status_msg.as_deref(),
            Some(format!("Saved {}", app.buf.file_name()).as_str())
        );
        let save_as_backups = recovery_root
            .join("backups")
            .join(crate::paths::path_key(&alternate_path));
        let backup = std::fs::read_dir(save_as_backups)
            .unwrap()
            .next()
            .unwrap()
            .unwrap()
            .path();
        assert_eq!(std::fs::read_to_string(backup).unwrap(), expected_text);

        // finish_save persists the pane session under the normal metadata root;
        // remove this test's path-keyed artifact as well as its manuscript.
        if let Some(sessions) = crate::paths::sessions() {
            let session =
                sessions.join(format!("{}.json", crate::paths::path_key(&alternate_path)));
            let _ = std::fs::remove_file(session);
        }
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn successful_save_paths_rotate_to_exact_backup_depth() {
        let dir = scratch_dir("rolling-save-seams");
        let source = dir.join("chapter.md");
        let recovery_root = dir.join("recovery");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(&source, "saved").unwrap();

        let mut app = App::new(Some(source.clone())).unwrap();
        app.backup_depth = 2;
        app.backup_root = Some(recovery_root.clone());

        app.recovery_journals[0] = Journal::in_root(&recovery_root, Some(&source), "unused");
        let first_end = app.buf.len_chars();
        app.buf.insert(first_end, " manually");
        app.save();

        app.recovery_journals[0] = Journal::in_root(&recovery_root, Some(&source), "unused");
        let second_end = app.buf.len_chars();
        app.buf.insert(second_end, " twice");
        app.save();

        app.recovery_journals[0] = Journal::in_root(&recovery_root, Some(&source), "unused");
        app.autosave = Duration::from_nanos(1);
        let autosave_end = app.buf.len_chars();
        app.buf.insert(autosave_end, " and automatically");
        app.maybe_autosave();

        let backup_dir = recovery_root
            .join("backups")
            .join(crate::paths::path_key(&source));
        let mut backups = std::fs::read_dir(backup_dir)
            .unwrap()
            .map(|entry| entry.unwrap().path())
            .collect::<Vec<_>>();
        backups.sort();
        assert_eq!(backups.len(), app.backup_depth);
        assert_eq!(
            std::fs::read_to_string(&backups[0]).unwrap(),
            "saved manually twice"
        );
        assert_eq!(
            std::fs::read_to_string(&backups[1]).unwrap(),
            "saved manually twice and automatically"
        );
        assert_eq!(
            std::fs::read_to_string(&source).unwrap(),
            "saved manually twice and automatically"
        );
        assert_eq!(app.status_msg.as_deref(), Some("Autosaved"));
        assert!(!app.buf.dirty);

        if let Some(sessions) = crate::paths::sessions() {
            let session = sessions.join(format!("{}.json", crate::paths::path_key(&source)));
            let _ = std::fs::remove_file(session);
        }
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn rolling_backup_failure_warns_without_turning_save_into_failure() {
        let dir = scratch_dir("rolling-warning");
        let source = dir.join("chapter.md");
        let blocked_root = dir.join("not-a-directory");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(&source, "old").unwrap();
        std::fs::write(&blocked_root, "blocks directory creation").unwrap();

        let mut app = App::new(Some(source.clone())).unwrap();
        app.backup_depth = 1;
        app.backup_root = Some(blocked_root);
        let old_len = app.buf.len_chars();
        app.buf.delete(0..old_len);
        app.buf.insert(0, "new saved text");
        app.save();

        assert!(!app.buf.dirty);
        assert_eq!(std::fs::read_to_string(&source).unwrap(), "new saved text");
        let message = app.status_msg.as_deref().unwrap();
        assert!(message.starts_with("Saved chapter.md;"));
        assert!(message.contains("rolling backup failed:"));

        if let Some(sessions) = crate::paths::sessions() {
            let session = sessions.join(format!("{}.json", crate::paths::path_key(&source)));
            let _ = std::fs::remove_file(session);
        }
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn idle_tick_journals_unnamed_buffer_when_autosave_is_disabled() {
        let dir = scratch_dir("recovery-unnamed");
        let mut app = App::new(None).unwrap();
        app.autosave = Duration::ZERO;
        app.recovery_journals[0] = Journal::in_root(&dir, None, "untitled-idle");
        app.buf.insert(0, "new unsaved manuscript");

        app.maybe_autosave();

        let journal_path = app.recovery_journals[0].path().unwrap();
        assert!(app.buf.dirty);
        assert_eq!(
            std::fs::read_to_string(journal_path).unwrap(),
            "new unsaved manuscript"
        );
        assert!(
            journal_path
                .file_name()
                .unwrap()
                .to_string_lossy()
                .starts_with("untitled-idle-")
        );

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

    #[test]
    fn clean_exit_clears_journal_but_dirty_abandon_retains_it() {
        let clean_dir = scratch_dir("recovery-clean-exit");
        let mut clean_app = App::new(None).unwrap();
        clean_app.autosave = Duration::ZERO;
        clean_app.recovery_journals[0] = Journal::in_root(&clean_dir, None, "untitled-clean");
        clean_app.buf.insert(0, "saved work");
        clean_app.maybe_autosave();
        let clean_path = clean_app.recovery_journals[0].path().unwrap().to_path_buf();
        clean_app.buf.dirty = false;

        clean_app.close_or_quit();

        assert!(clean_app.quit);
        assert!(!clean_path.exists());

        let dirty_dir = scratch_dir("recovery-dirty-exit");
        let mut dirty_app = App::new(None).unwrap();
        dirty_app.autosave = Duration::ZERO;
        dirty_app.recovery_journals[0] = Journal::in_root(&dirty_dir, None, "untitled-dirty");
        dirty_app.buf.insert(0, "abandoned but recoverable");
        dirty_app.maybe_autosave();
        let dirty_path = dirty_app.recovery_journals[0].path().unwrap().to_path_buf();

        // This is called only after the user confirms abandoning changes.
        dirty_app.close_or_quit();

        assert!(dirty_app.quit);
        assert!(dirty_path.exists());
        assert_eq!(
            std::fs::read_to_string(&dirty_path).unwrap(),
            "abandoned but recoverable"
        );

        let _ = std::fs::remove_dir_all(clean_dir);
        let _ = std::fs::remove_dir_all(dirty_dir);
    }

    #[test]
    fn startup_recovery_restores_as_one_undoable_dirty_edit() {
        let dir = scratch_dir("recovery-restore");
        let source = dir.join("chapter.md");
        let recovery_root = dir.join("recovery");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(&source, "saved manuscript").unwrap();
        std::thread::sleep(Duration::from_millis(20));

        let mut app = App::new(Some(source.clone())).unwrap();
        app.recovery_journals[0] = Journal::in_root(&recovery_root, Some(&source), "unused");
        app.recovery_journals[0]
            .write_if_changed(&Rope::from_str("recovered manuscript"), Instant::now())
            .unwrap();
        let recovery_path = app.recovery_journals[0].path().unwrap().to_path_buf();
        app.offer_recovery_for_active();

        assert!(matches!(app.mode, Mode::ConfirmRecover));
        assert!(
            !app.splash,
            "the splash must not consume the recovery answer"
        );
        app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE));
        assert!(matches!(app.mode, Mode::ConfirmRecover));
        app.handle_key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE));

        assert!(matches!(app.mode, Mode::Normal));
        assert_eq!(app.buf.rope.to_string(), "recovered manuscript");
        assert!(app.buf.dirty);
        assert_eq!(
            std::fs::read_to_string(&source).unwrap(),
            "saved manuscript"
        );
        assert!(
            recovery_path.exists(),
            "restore must retain the journal until save"
        );

        app.execute(Cmd::Undo);
        assert_eq!(app.buf.rope.to_string(), "saved manuscript");

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

    #[test]
    fn simulated_crash_restart_restores_then_save_clears_journal() {
        let dir = scratch_dir("recovery-restart");
        let source = dir.join("chapter.md");
        let recovery_root = dir.join("recovery");
        let disk_text = "saved manuscript";
        let recovered_text = "saved manuscript plus unsaved work";
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(&source, disk_text).unwrap();
        std::thread::sleep(Duration::from_millis(20));

        // First process: edit and reach the idle recovery tick, then disappear
        // without save/clean-exit cleanup.
        let mut crashed = App::new(Some(source.clone())).unwrap();
        crashed.autosave = Duration::ZERO;
        crashed.recovery_journals[0] = Journal::in_root(&recovery_root, Some(&source), "unused");
        let end = crashed.buf.len_chars();
        crashed.buf.insert(end, " plus unsaved work");
        crashed.maybe_autosave();
        let recovery_path = crashed.recovery_journals[0].path().unwrap().to_path_buf();
        assert_eq!(
            std::fs::read_to_string(&recovery_path).unwrap(),
            recovered_text
        );
        assert_eq!(std::fs::read_to_string(&source).unwrap(), disk_text);
        drop(crashed);

        // Second process: reopen from disk, discover the surviving journal,
        // accept it, and keep the on-disk manuscript unchanged until save.
        let mut restarted = App::new(Some(source.clone())).unwrap();
        restarted.backup_depth = 0;
        restarted.recovery_journals[0] = Journal::in_root(&recovery_root, Some(&source), "unused");
        restarted.offer_recovery_for_active();
        assert!(matches!(restarted.mode, Mode::ConfirmRecover));
        restarted.handle_key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE));

        assert_eq!(restarted.buf.rope.to_string(), recovered_text);
        assert!(restarted.buf.dirty);
        assert_eq!(std::fs::read_to_string(&source).unwrap(), disk_text);
        assert!(recovery_path.exists());

        restarted.save();

        assert!(!restarted.buf.dirty);
        assert_eq!(std::fs::read_to_string(&source).unwrap(), recovered_text);
        assert!(
            !recovery_path.exists(),
            "committing restored text must clear its crash journal"
        );

        if let Some(sessions) = crate::paths::sessions() {
            let session = sessions.join(format!("{}.json", crate::paths::path_key(&source)));
            let _ = std::fs::remove_file(session);
        }
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn declining_startup_recovery_keeps_disk_text_and_clears_record() {
        let dir = scratch_dir("recovery-decline");
        let source = dir.join("chapter.md");
        let recovery_root = dir.join("recovery");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(&source, "saved manuscript").unwrap();
        std::thread::sleep(Duration::from_millis(20));

        let mut app = App::new(Some(source.clone())).unwrap();
        app.recovery_journals[0] = Journal::in_root(&recovery_root, Some(&source), "unused");
        app.recovery_journals[0]
            .write_if_changed(&Rope::from_str("declined manuscript"), Instant::now())
            .unwrap();
        let recovery_path = app.recovery_journals[0].path().unwrap().to_path_buf();
        app.offer_recovery_for_active();
        app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));

        assert!(matches!(app.mode, Mode::Normal));
        assert_eq!(app.buf.rope.to_string(), "saved manuscript");
        assert!(!app.buf.dirty);
        assert!(!recovery_path.exists());
        assert_eq!(app.status_msg.as_deref(), Some("Recovery declined"));

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

    #[test]
    fn app_project_initializes_as_none() {
        // R1.8: backward compat — app starts with no project when opening
        // a bare file. Task 1.2.
        let app = App::new(None).expect("App creation should succeed");
        assert!(app.project.is_none(), "Project should be None at startup");
    }

    #[test]
    fn project_field_holds_loaded_project() {
        // Task 1.2: the project field exists and can store a Project.
        // We don't test the full load flow here (that's in project.rs tests),
        // just that the type can hold one.
        let mut app = App::new(None).expect("App creation should succeed");
        assert!(app.project.is_none());

        // Setting a project (would be done by open_project in practice).
        // Just verify the field can hold it.
        let _can_be_set: Option<Project> = app.project.take();
        app.project = None; // Put it back
        assert!(app.project.is_none());
    }

    /// Helper to create a test project with sample documents.
    fn setup_test_project() -> (std::path::PathBuf, Project) {
        use std::sync::atomic::{AtomicU64, Ordering};
        static COUNTER: AtomicU64 = AtomicU64::new(0);
        let id = COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir = std::env::temp_dir().join(format!("pstar-app-test-1.4-{}", id));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).expect(&format!("Failed to create test dir: {:?}", dir));

        // Create test files.
        let doc1 = dir.join("doc1.md");
        let doc2 = dir.join("doc2.md");
        let doc3 = dir.join("doc3.md");
        std::fs::write(&doc1, "First document content").expect("Failed to write doc1");
        std::fs::write(&doc2, "Second document content").expect("Failed to write doc2");
        std::fs::write(&doc3, "Third document content").expect("Failed to write doc3");

        // Create a project manifest.
        let manifest_path = dir.join("test.pstarproj");
        let project = Project {
            manifest_path: manifest_path.clone(),
            manifest: crate::project::ProjectManifest {
                name: "Test Project".to_string(),
                docs: vec![
                    crate::project::DocEntry {
                        path: doc1,
                        title: "Doc 1".to_string(),
                        include_in_compile: true,
                    },
                    crate::project::DocEntry {
                        path: doc2,
                        title: "Doc 2".to_string(),
                        include_in_compile: true,
                    },
                    crate::project::DocEntry {
                        path: doc3,
                        title: "Doc 3".to_string(),
                        include_in_compile: true,
                    },
                ],
                separator: crate::project::Separator::PageBreak,
            },
        };
        project.save().expect(&format!(
            "Failed to save project manifest to {:?}",
            manifest_path
        ));

        (dir, project)
    }

    #[test]
    fn binder_move_up_at_top_is_noop() {
        // Task 1.4: moving the first document up should be a no-op.
        let (_dir, project) = setup_test_project();
        let mut app = App::new(None).unwrap();
        app.project = Some(project);

        // Enter binder mode with first doc selected.
        app.mode = Mode::Binder {
            entries: vec![
                BinderEntry {
                    idx: 0,
                    title: "Doc 1".to_string(),
                    word_count: Some(3),
                    exists: true,
                },
                BinderEntry {
                    idx: 1,
                    title: "Doc 2".to_string(),
                    word_count: Some(3),
                    exists: true,
                },
            ],
            selected: 0,
        };

        // Try to move up from position 0.
        app.binder_move_up();

        // Should show "Already at top" message.
        assert!(app.status_msg.as_ref().unwrap().contains("top"));

        // Order should be unchanged.
        let project = app.project.as_ref().unwrap();
        assert_eq!(project.manifest.docs[0].title, "Doc 1");
        assert_eq!(project.manifest.docs[1].title, "Doc 2");
    }

    #[test]
    fn binder_move_down_at_bottom_is_noop() {
        // Task 1.4: moving the last document down should be a no-op.
        let (_dir, project) = setup_test_project();
        let mut app = App::new(None).unwrap();
        app.project = Some(project);

        // Enter binder mode with last doc selected.
        app.mode = Mode::Binder {
            entries: vec![
                BinderEntry {
                    idx: 0,
                    title: "Doc 1".to_string(),
                    word_count: Some(3),
                    exists: true,
                },
                BinderEntry {
                    idx: 1,
                    title: "Doc 2".to_string(),
                    word_count: Some(3),
                    exists: true,
                },
                BinderEntry {
                    idx: 2,
                    title: "Doc 3".to_string(),
                    word_count: Some(3),
                    exists: true,
                },
            ],
            selected: 2,
        };

        // Try to move down from last position.
        app.binder_move_down();

        // Should show "Already at bottom" message.
        assert!(app.status_msg.as_ref().unwrap().contains("bottom"));

        // Order should be unchanged.
        let project = app.project.as_ref().unwrap();
        assert_eq!(project.manifest.docs[2].title, "Doc 3");
    }

    #[test]
    fn binder_move_up_reorders_and_saves() {
        // Task 1.4: moving a document up should reorder and persist atomically (R1.4).
        let (_dir, project) = setup_test_project();
        let mut app = App::new(None).unwrap();
        app.project = Some(project);

        // Enter binder mode with second doc selected.
        app.mode = Mode::Binder {
            entries: vec![
                BinderEntry {
                    idx: 0,
                    title: "Doc 1".to_string(),
                    word_count: Some(3),
                    exists: true,
                },
                BinderEntry {
                    idx: 1,
                    title: "Doc 2".to_string(),
                    word_count: Some(3),
                    exists: true,
                },
                BinderEntry {
                    idx: 2,
                    title: "Doc 3".to_string(),
                    word_count: Some(3),
                    exists: true,
                },
            ],
            selected: 1,
        };

        // Move second doc up (should become first).
        app.binder_move_up();

        // Check the new order in memory.
        let project = app.project.as_ref().unwrap();
        assert_eq!(project.manifest.docs[0].title, "Doc 2");
        assert_eq!(project.manifest.docs[1].title, "Doc 1");
        assert_eq!(project.manifest.docs[2].title, "Doc 3");

        // Verify it was saved (reload and check).
        let manifest_path = project.manifest_path.clone();
        let reloaded = Project::load(&manifest_path).unwrap();
        assert_eq!(reloaded.manifest.docs[0].title, "Doc 2");
        assert_eq!(reloaded.manifest.docs[1].title, "Doc 1");
    }

    #[test]
    fn binder_move_down_reorders_and_saves() {
        // Task 1.4: moving a document down should reorder and persist atomically (R1.4).
        let (_dir, project) = setup_test_project();
        let mut app = App::new(None).unwrap();
        app.project = Some(project);

        // Enter binder mode with first doc selected.
        app.mode = Mode::Binder {
            entries: vec![
                BinderEntry {
                    idx: 0,
                    title: "Doc 1".to_string(),
                    word_count: Some(3),
                    exists: true,
                },
                BinderEntry {
                    idx: 1,
                    title: "Doc 2".to_string(),
                    word_count: Some(3),
                    exists: true,
                },
                BinderEntry {
                    idx: 2,
                    title: "Doc 3".to_string(),
                    word_count: Some(3),
                    exists: true,
                },
            ],
            selected: 0,
        };

        // Move first doc down (should become second).
        app.binder_move_down();

        // Check the new order in memory.
        let project = app.project.as_ref().unwrap();
        assert_eq!(project.manifest.docs[0].title, "Doc 2");
        assert_eq!(project.manifest.docs[1].title, "Doc 1");
        assert_eq!(project.manifest.docs[2].title, "Doc 3");

        // Verify it was saved.
        let manifest_path = project.manifest_path.clone();
        let reloaded = Project::load(&manifest_path).unwrap();
        assert_eq!(reloaded.manifest.docs[0].title, "Doc 2");
        assert_eq!(reloaded.manifest.docs[1].title, "Doc 1");
    }

    #[test]
    fn project_add_doc_adds_and_saves() {
        // Task 1.4: adding a document should append to manifest and save atomically (R1.5).
        let (dir, project) = setup_test_project();
        let mut app = App::new(None).unwrap();
        app.project = Some(project);

        // Create a new file to add.
        let new_doc = dir.join("doc4.md");
        std::fs::write(&new_doc, "New document").unwrap();

        // Add the document.
        app.project_add_doc(new_doc.to_str().unwrap());

        // Verify it was added.
        let project = app.project.as_ref().unwrap();
        assert_eq!(project.manifest.docs.len(), 4);
        assert_eq!(project.manifest.docs[3].title, "doc4");

        // Verify it was saved.
        let manifest_path = project.manifest_path.clone();
        let reloaded = Project::load(&manifest_path).unwrap();
        assert_eq!(reloaded.manifest.docs.len(), 4);
        assert_eq!(reloaded.manifest.docs[3].title, "doc4");
    }

    #[test]
    fn project_add_doc_missing_file_shows_error() {
        // Task 1.4: adding a missing file should show an error (R1.5).
        let (_dir, project) = setup_test_project();
        let mut app = App::new(None).unwrap();
        app.project = Some(project);

        // Try to add a non-existent file.
        app.project_add_doc("/nonexistent/file.md");

        // Should show "File not found" error.
        assert!(app.status_msg.as_ref().unwrap().contains("not found"));

        // Project should be unchanged.
        let project = app.project.as_ref().unwrap();
        assert_eq!(project.manifest.docs.len(), 3);
    }

    #[test]
    fn project_remove_doc_removes_and_saves() {
        // Task 1.4: removing a document should delete from manifest but keep file (R1.5).
        let (_dir, project) = setup_test_project();
        let mut app = App::new(None).unwrap();
        let doc2_path = project.manifest.docs[1].path.clone();
        app.project = Some(project);

        // Enter binder mode with second doc selected.
        app.mode = Mode::Binder {
            entries: vec![
                BinderEntry {
                    idx: 0,
                    title: "Doc 1".to_string(),
                    word_count: Some(3),
                    exists: true,
                },
                BinderEntry {
                    idx: 1,
                    title: "Doc 2".to_string(),
                    word_count: Some(3),
                    exists: true,
                },
                BinderEntry {
                    idx: 2,
                    title: "Doc 3".to_string(),
                    word_count: Some(3),
                    exists: true,
                },
            ],
            selected: 1,
        };

        // Remove the selected document.
        app.project_remove_doc();

        // Verify it was removed from the manifest.
        let project = app.project.as_ref().unwrap();
        assert_eq!(project.manifest.docs.len(), 2);
        assert_eq!(project.manifest.docs[0].title, "Doc 1");
        assert_eq!(project.manifest.docs[1].title, "Doc 3");

        // R1.5: verify the file still exists on disk.
        assert!(doc2_path.exists(), "File should not be deleted from disk");

        // Verify the change was saved.
        let manifest_path = project.manifest_path.clone();
        let reloaded = Project::load(&manifest_path).unwrap();
        assert_eq!(reloaded.manifest.docs.len(), 2);
    }

    #[test]
    fn project_remove_doc_shows_clear_message() {
        // Task 1.4: removing should show clear message that file is kept (R1.5).
        let (_dir, project) = setup_test_project();
        let mut app = App::new(None).unwrap();
        app.project = Some(project);

        // Enter binder mode with first doc selected.
        app.mode = Mode::Binder {
            entries: vec![BinderEntry {
                idx: 0,
                title: "Doc 1".to_string(),
                word_count: Some(3),
                exists: true,
            }],
            selected: 0,
        };

        // Remove the document.
        app.project_remove_doc();

        // Verify the status message mentions "file kept on disk".
        let msg = app.status_msg.as_ref().unwrap();
        assert!(
            msg.contains("kept on disk"),
            "Message should clarify file is kept: {}",
            msg
        );
    }

    #[test]
    fn project_remove_last_doc_adjusts_selection() {
        // Task 1.4: removing the last document should adjust selection to avoid out-of-bounds.
        let (_dir, project) = setup_test_project();
        let mut app = App::new(None).unwrap();
        app.project = Some(project);

        // Enter binder mode with last doc selected.
        app.mode = Mode::Binder {
            entries: vec![
                BinderEntry {
                    idx: 0,
                    title: "Doc 1".to_string(),
                    word_count: Some(3),
                    exists: true,
                },
                BinderEntry {
                    idx: 1,
                    title: "Doc 2".to_string(),
                    word_count: Some(3),
                    exists: true,
                },
                BinderEntry {
                    idx: 2,
                    title: "Doc 3".to_string(),
                    word_count: Some(3),
                    exists: true,
                },
            ],
            selected: 2,
        };

        // Remove the last document.
        app.project_remove_doc();

        // Verify selection was adjusted.
        if let Mode::Binder { selected, entries } = &app.mode {
            assert_eq!(
                *selected, 1,
                "Selection should be adjusted to last valid index"
            );
            assert_eq!(entries.len(), 2);
        } else {
            panic!("Should still be in binder mode");
        }
    }

    #[test]
    fn missing_file_resilience_in_binder() {
        // Task 1.5: missing files should be flagged in binder but not prevent opening the project (R1.7).
        let dir = std::env::temp_dir().join("pstar-missing-test");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        // Create a project with three docs, but only two files exist.
        let doc1 = dir.join("exists1.md");
        let doc2 = dir.join("missing.md"); // This file will NOT be created
        let doc3 = dir.join("exists2.md");

        std::fs::write(&doc1, "File 1 content").unwrap();
        // doc2 intentionally not created
        std::fs::write(&doc3, "File 3 content").unwrap();

        let manifest_path = dir.join("test.pstarproj");
        let project = Project {
            manifest_path: manifest_path.clone(),
            manifest: ProjectManifest {
                name: "Test Project".to_string(),
                docs: vec![
                    DocEntry {
                        path: doc1.clone(),
                        title: "Existing Doc 1".to_string(),
                        include_in_compile: true,
                    },
                    DocEntry {
                        path: doc2.clone(),
                        title: "Missing Doc".to_string(),
                        include_in_compile: true,
                    },
                    DocEntry {
                        path: doc3.clone(),
                        title: "Existing Doc 3".to_string(),
                        include_in_compile: true,
                    },
                ],
                separator: crate::project::Separator::PageBreak,
            },
        };
        project.save().unwrap();

        // Load the project - should succeed despite missing file (R1.7).
        let loaded_project = Project::load(&manifest_path).unwrap();
        assert_eq!(loaded_project.manifest.docs.len(), 3);

        // Verify doc_exists correctly identifies missing file.
        assert!(loaded_project.doc_exists(0), "Doc 1 should exist");
        assert!(!loaded_project.doc_exists(1), "Doc 2 should be missing");
        assert!(loaded_project.doc_exists(2), "Doc 3 should exist");

        // Verify word count returns None for missing file.
        assert!(
            loaded_project.doc_word_count(0).is_some(),
            "Word count should work for existing files"
        );
        assert!(
            loaded_project.doc_word_count(1).is_none(),
            "Word count should return None for missing file"
        );
        assert!(
            loaded_project.doc_word_count(2).is_some(),
            "Word count should work for existing files"
        );

        // Create an App with this project and open the binder.
        let mut app = App::new(None).unwrap();
        app.project = Some(loaded_project);

        // Trigger binder toggle to build entries.
        app.execute(Cmd::BinderToggle);

        // Verify binder entries reflect the existence status.
        if let Mode::Binder { entries, .. } = &app.mode {
            assert_eq!(entries.len(), 3);
            assert!(entries[0].exists, "Entry 0 should exist");
            assert!(!entries[1].exists, "Entry 1 should be marked as missing");
            assert!(entries[2].exists, "Entry 2 should exist");

            assert!(entries[0].word_count.is_some());
            assert!(entries[1].word_count.is_none());
            assert!(entries[2].word_count.is_some());
        } else {
            panic!("Should be in binder mode");
        }

        // Simulate trying to open the missing file from the binder.
        app.mode = Mode::Binder {
            entries: vec![
                BinderEntry {
                    idx: 0,
                    title: "Existing Doc 1".to_string(),
                    word_count: Some(3),
                    exists: true,
                },
                BinderEntry {
                    idx: 1,
                    title: "Missing Doc".to_string(),
                    word_count: None,
                    exists: false,
                },
                BinderEntry {
                    idx: 2,
                    title: "Existing Doc 3".to_string(),
                    word_count: Some(3),
                    exists: true,
                },
            ],
            selected: 1, // Select the missing file
        };

        // Try to open it by simulating Enter key.
        use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
        app.handle_binder_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));

        // Should show error message and stay in binder mode.
        assert!(
            app.status_msg.as_ref().unwrap().contains("missing"),
            "Should show missing file error"
        );
        assert!(
            matches!(app.mode, Mode::Binder { .. }),
            "Should stay in binder mode"
        );

        // Verify we can open existing files.
        app.mode = Mode::Binder {
            entries: vec![
                BinderEntry {
                    idx: 0,
                    title: "Existing Doc 1".to_string(),
                    word_count: Some(3),
                    exists: true,
                },
                BinderEntry {
                    idx: 1,
                    title: "Missing Doc".to_string(),
                    word_count: None,
                    exists: false,
                },
                BinderEntry {
                    idx: 2,
                    title: "Existing Doc 3".to_string(),
                    word_count: Some(3),
                    exists: true,
                },
            ],
            selected: 0, // Select existing file
        };

        app.handle_binder_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));

        // Should successfully open and exit binder mode.
        assert!(
            matches!(app.mode, Mode::Normal),
            "Should exit binder after opening existing file"
        );
        assert!(
            app.status_msg.as_ref().unwrap().contains("Opened"),
            "Should show success message"
        );

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