hjkl 0.33.2

Vim-modal terminal editor: standalone TUI built on the hjkl engine.
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
use super::*;

// ── :write / :write! disk-state guard tests ─────────────────────────────

#[test]
fn colon_write_blocked_by_disk_state_guard_without_bang() {
    let path = std::env::temp_dir().join("hjkl_write_no_bang_guard.txt");
    std::fs::write(&path, "original\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();
    // Mark disk changed without reloading buffer, then dirty the buffer.
    app.active_mut().disk_state = DiskState::ChangedOnDisk;
    app.active_mut().dirty = true;
    seed_buffer(&mut app, "edited\n");
    // :write without bang must refuse.
    app.dispatch_ex("write");
    let msg = app.bus.last_body_or_empty().to_string();
    assert!(
        msg.contains("E13"),
        "expected E13 guard message, got: {msg}"
    );
    // File on disk must be unchanged.
    let on_disk = std::fs::read_to_string(&path).unwrap();
    assert_eq!(
        on_disk, "original\n",
        "disk must be unchanged after blocked :w"
    );
    let _ = std::fs::remove_file(&path);
}

#[test]
fn colon_write_bang_overrides_disk_state_guard() {
    let path = std::env::temp_dir().join("hjkl_write_bang_guard.txt");
    std::fs::write(&path, "original\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();
    app.active_mut().disk_state = DiskState::ChangedOnDisk;
    app.active_mut().dirty = true;
    seed_buffer(&mut app, "edited\n");
    // :write! must force-save.
    app.dispatch_ex("write!");
    let msg = app.bus.last_body_or_empty().to_string();
    assert!(!msg.contains("E13"), ":w! must not produce E13, got: {msg}");
    // disk_state must be reset to Synced.
    assert_eq!(
        app.active().disk_state,
        DiskState::Synced,
        "disk_state must be Synced after :w!"
    );
    // File on disk must contain the new content.
    let on_disk = std::fs::read_to_string(&path).unwrap();
    assert!(
        on_disk.contains("edited"),
        "disk must have new content after :w!"
    );
    let _ = std::fs::remove_file(&path);
}

// ── :e tests ────────────────────────────────────────────────────────────

#[test]
fn edit_percent_reloads_current_file() {
    let path = std::env::temp_dir().join("hjkl_edit_percent_reload.txt");
    std::fs::write(&path, "first\nsecond\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();
    std::fs::write(&path, "alpha\nbeta\ngamma\n").unwrap();
    app.dispatch_ex("e %");
    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert_eq!(lines, vec!["alpha", "beta", "gamma"]);
    let _ = std::fs::remove_file(&path);
}

#[test]
fn edit_no_arg_reloads_current_file() {
    let path = std::env::temp_dir().join("hjkl_edit_noarg_reload.txt");
    std::fs::write(&path, "v1\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();
    std::fs::write(&path, "v2\n").unwrap();
    app.dispatch_ex("e");
    assert_eq!(
        app.active_editor()
            .buffer()
            .rope()
            .lines()
            .map(|s| {
                let s = s.to_string();
                s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
            })
            .collect::<Vec<_>>(),
        vec!["v2".to_string()]
    );
    let _ = std::fs::remove_file(&path);
}

#[test]
fn edit_blocks_dirty_buffer_without_force() {
    let path = std::env::temp_dir().join("hjkl_edit_dirty_block.txt");
    std::fs::write(&path, "orig\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();
    app.active_mut().dirty = true;
    app.dispatch_ex("e %");
    let msg = app.bus.last_body_or_empty().to_string();
    assert!(msg.contains("E37"), "expected E37, got: {msg}");
    let _ = std::fs::remove_file(&path);
}

#[test]
fn edit_force_reloads_dirty_buffer() {
    let path = std::env::temp_dir().join("hjkl_edit_force.txt");
    std::fs::write(&path, "disk\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();
    app.active_mut().dirty = true;
    app.dispatch_ex("e!");
    assert_eq!(
        app.active_editor()
            .buffer()
            .rope()
            .lines()
            .map(|s| {
                let s = s.to_string();
                s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
            })
            .collect::<Vec<_>>(),
        vec!["disk".to_string()]
    );
    assert!(!app.active().dirty);
    let _ = std::fs::remove_file(&path);
}

#[test]
fn undo_to_saved_state_clears_dirty() {
    let path = std::env::temp_dir().join("hjkl_undo_clears_dirty.txt");
    std::fs::write(&path, "alpha\nbravo\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();
    assert!(!app.active().dirty);
    hjkl_vim_tui::handle_key(app.active_editor_mut(), key(KeyCode::Char('i')));
    hjkl_vim_tui::handle_key(app.active_editor_mut(), key(KeyCode::Char('X')));
    if app.active_editor_mut().take_dirty() {
        app.active_mut().refresh_dirty_against_saved();
    }
    assert!(app.active().dirty, "edit should mark dirty");
    hjkl_vim_tui::handle_key(app.active_editor_mut(), key(KeyCode::Esc));
    hjkl_vim_tui::handle_key(app.active_editor_mut(), key(KeyCode::Char('u')));
    if app.active_editor_mut().take_dirty() {
        app.active_mut().refresh_dirty_against_saved();
    }
    assert!(
        !app.active().dirty,
        "undo to saved state should clear dirty"
    );
    let _ = std::fs::remove_file(&path);
}

// ── Phase C: multi-buffer tests ─────────────────────────────────────────
#[test]
fn edit_new_path_appends_slot_and_switches() {
    let path_a = std::env::temp_dir().join("hjkl_phc_a.txt");
    let path_b = std::env::temp_dir().join("hjkl_phc_b.txt");
    std::fs::write(&path_a, "alpha\n").unwrap();
    std::fs::write(&path_b, "beta\n").unwrap();
    let mut app = App::new(Some(path_a.clone()), false, None, None).unwrap();
    assert_eq!(app.slots.len(), 1);
    app.dispatch_ex(&format!("e {}", path_b.display()));
    assert_eq!(app.slots.len(), 2);
    assert_eq!(app.active_index(), 1);
    assert_eq!(
        app.active_editor()
            .buffer()
            .rope()
            .lines()
            .map(|s| {
                let s = s.to_string();
                s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
            })
            .collect::<Vec<_>>(),
        vec!["beta".to_string()]
    );
    let _ = std::fs::remove_file(&path_a);
    let _ = std::fs::remove_file(&path_b);
}

#[test]
fn edit_existing_path_switches_to_open_slot() {
    let path_a = std::env::temp_dir().join("hjkl_phc_switch_a.txt");
    let path_b = std::env::temp_dir().join("hjkl_phc_switch_b.txt");
    std::fs::write(&path_a, "alpha\n").unwrap();
    std::fs::write(&path_b, "beta\n").unwrap();
    let mut app = App::new(Some(path_a.clone()), false, None, None).unwrap();
    app.dispatch_ex(&format!("e {}", path_b.display()));
    assert_eq!(app.active_index(), 1);
    // Re-open path_a → switch back, no third slot.
    app.dispatch_ex(&format!("e {}", path_a.display()));
    assert_eq!(app.slots.len(), 2);
    assert_eq!(app.active_index(), 0);
    let _ = std::fs::remove_file(&path_a);
    let _ = std::fs::remove_file(&path_b);
}

#[test]
fn edit_other_open_path_does_not_block_on_dirty() {
    let path_a = std::env::temp_dir().join("hjkl_phc_dirty_a.txt");
    let path_b = std::env::temp_dir().join("hjkl_phc_dirty_b.txt");
    std::fs::write(&path_a, "a\n").unwrap();
    std::fs::write(&path_b, "b\n").unwrap();
    let mut app = App::new(Some(path_a.clone()), false, None, None).unwrap();
    app.active_mut().dirty = true;
    // Switching to a *different* file must not be gated on the
    // current slot's dirty flag — the slot isn't being destroyed.
    app.dispatch_ex(&format!("e {}", path_b.display()));
    assert_eq!(app.active_index(), 1);
    assert!(app.slots[0].dirty, "slot 0 should remain dirty");
    let _ = std::fs::remove_file(&path_a);
    let _ = std::fs::remove_file(&path_b);
}

#[test]
fn bnext_bprev_cycle_active() {
    let path_a = std::env::temp_dir().join("hjkl_phc_cycle_a.txt");
    let path_b = std::env::temp_dir().join("hjkl_phc_cycle_b.txt");
    let path_c = std::env::temp_dir().join("hjkl_phc_cycle_c.txt");
    for p in [&path_a, &path_b, &path_c] {
        std::fs::write(p, "x\n").unwrap();
    }
    let mut app = App::new(Some(path_a.clone()), false, None, None).unwrap();
    app.dispatch_ex(&format!("e {}", path_b.display()));
    app.dispatch_ex(&format!("e {}", path_c.display()));
    assert_eq!(app.active_index(), 2);
    app.dispatch_ex("bn");
    assert_eq!(app.active_index(), 0, "wrap forward to 0");
    app.dispatch_ex("bn");
    assert_eq!(app.active_index(), 1);
    app.dispatch_ex("bp");
    assert_eq!(app.active_index(), 0);
    app.dispatch_ex("bp");
    assert_eq!(app.active_index(), 2, "wrap backward to last");
    for p in [&path_a, &path_b, &path_c] {
        let _ = std::fs::remove_file(p);
    }
}

#[test]
fn bnext_no_op_with_single_slot() {
    let mut app = App::new(None, false, None, None).unwrap();
    app.dispatch_ex("bn");
    assert_eq!(app.active_index(), 0);
    assert_eq!(app.slots.len(), 1);
}

#[test]
fn bdelete_blocks_dirty_without_force() {
    let path_a = std::env::temp_dir().join("hjkl_phc_bd_a.txt");
    let path_b = std::env::temp_dir().join("hjkl_phc_bd_b.txt");
    std::fs::write(&path_a, "a\n").unwrap();
    std::fs::write(&path_b, "b\n").unwrap();
    let mut app = App::new(Some(path_a.clone()), false, None, None).unwrap();
    app.dispatch_ex(&format!("e {}", path_b.display()));
    app.active_mut().dirty = true;
    app.dispatch_ex("bd");
    let msg = app.bus.last_body_or_empty().to_string();
    assert!(msg.contains("E89"), "expected E89, got: {msg}");
    assert_eq!(app.slots.len(), 2);
    let _ = std::fs::remove_file(&path_a);
    let _ = std::fs::remove_file(&path_b);
}

#[test]
fn bdelete_force_removes_dirty_slot() {
    let path_a = std::env::temp_dir().join("hjkl_phc_bdforce_a.txt");
    let path_b = std::env::temp_dir().join("hjkl_phc_bdforce_b.txt");
    std::fs::write(&path_a, "a\n").unwrap();
    std::fs::write(&path_b, "b\n").unwrap();
    let mut app = App::new(Some(path_a.clone()), false, None, None).unwrap();
    app.dispatch_ex(&format!("e {}", path_b.display()));
    app.active_mut().dirty = true;
    app.dispatch_ex("bd!");
    assert_eq!(app.slots.len(), 1);
    assert_eq!(app.active_index(), 0);
    assert_eq!(
        app.active_editor()
            .buffer()
            .rope()
            .lines()
            .map(|s| {
                let s = s.to_string();
                s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
            })
            .collect::<Vec<_>>(),
        vec!["a".to_string()]
    );
    let _ = std::fs::remove_file(&path_a);
    let _ = std::fs::remove_file(&path_b);
}

/// Regression: closing a buffer in a multi-buffer session must delete that
/// buffer's swap file. The owning process stays alive (so the orphan scan never
/// reaps it) and the slot is gone (so cleanup_swaps_on_exit can't either) —
/// leaving it behind makes the next open of that file surface a spurious
/// recovery prompt.
#[test]
fn bdelete_removes_closed_buffers_swap() {
    let path_a = std::env::temp_dir().join("hjkl_bd_swap_a.txt");
    let path_b = std::env::temp_dir().join("hjkl_bd_swap_b.txt");
    std::fs::write(&path_a, "a\n").unwrap();
    std::fs::write(&path_b, "b\n").unwrap();
    let mut app = App::new(Some(path_a.clone()), false, None, None).unwrap();
    app.dispatch_ex(&format!("e {}", path_b.display()));

    // Inject a real swap file for the active (b) slot.
    let swap_b = std::env::temp_dir().join("hjkl_bd_swap_b.swp");
    std::fs::write(&swap_b, b"x").unwrap();
    app.active_mut().swap_path = Some(swap_b.clone());
    assert!(swap_b.exists(), "swap must exist before bdelete");

    app.dispatch_ex("bd");

    assert_eq!(app.slots.len(), 1, "one slot should remain after bdelete");
    assert!(
        !swap_b.exists(),
        "closed buffer's swap must be removed by bdelete"
    );
    let _ = std::fs::remove_file(&path_a);
    let _ = std::fs::remove_file(&path_b);
    let _ = std::fs::remove_file(&swap_b);
}

#[test]
fn bdelete_on_last_slot_resets_to_no_name() {
    let path = std::env::temp_dir().join("hjkl_phc_bd_last.txt");
    std::fs::write(&path, "content\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();
    app.dispatch_ex("bd");
    assert_eq!(app.slots.len(), 1);
    assert!(app.active().filename.is_none());
    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert!(
        lines.is_empty() || (lines.len() == 1 && lines[0].is_empty()),
        "expected empty scratch buffer, got: {lines:?}"
    );
    let _ = std::fs::remove_file(&path);
}

// ── :bwipeout tests (#101) ──────────────────────────────────────────────

#[test]
fn bwipeout_clears_marks_on_last_slot() {
    let path = std::env::temp_dir().join("hjkl_bwipeout_marks_last.txt");
    std::fs::write(&path, "hello\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();
    // Set a mark on the buffer.
    app.active_editor_mut().set_mark('a', (0, 0));
    assert!(
        app.active_editor().mark('a').is_some(),
        "mark should be set before wipe"
    );
    app.dispatch_ex("bw");
    // After wipe the fresh scratch buffer must have no marks.
    assert!(
        app.active_editor().mark('a').is_none(),
        ":bwipeout on last slot must not carry marks into scratch buffer"
    );
    assert_eq!(app.slots.len(), 1);
    assert!(app.active().filename.is_none());
    let _ = std::fs::remove_file(&path);
}

#[test]
fn bwipeout_clears_jumplist_on_last_slot() {
    let path = std::env::temp_dir().join("hjkl_bwipeout_jumps_last.txt");
    std::fs::write(&path, "line1\nline2\nline3\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();
    // Push an entry into the jumplist.
    app.active_editor_mut().record_jump((2, 0));
    let (back, _) = app.active_editor().jump_list();
    assert!(
        !back.is_empty(),
        "jumplist should have an entry before wipe"
    );
    app.dispatch_ex("bw");
    // After wipe the fresh scratch buffer must have an empty jumplist.
    let (back, fwd) = app.active_editor().jump_list();
    assert!(
        back.is_empty() && fwd.is_empty(),
        ":bwipeout on last slot must not carry jumps into scratch buffer"
    );
    let _ = std::fs::remove_file(&path);
}

#[test]
fn bdelete_does_not_explicitly_wipe_marks_path() {
    // Verify :bdelete and :bwipeout both reach distinct code paths.
    // With two slots, :bdelete removes the active slot (different slot survives).
    let path_a = std::env::temp_dir().join("hjkl_bdelete_path_a.txt");
    let path_b = std::env::temp_dir().join("hjkl_bdelete_path_b.txt");
    std::fs::write(&path_a, "a\n").unwrap();
    std::fs::write(&path_b, "b\n").unwrap();
    let mut app = App::new(Some(path_a.clone()), false, None, None).unwrap();
    app.dispatch_ex(&format!("e {}", path_b.display()));
    assert_eq!(app.slots.len(), 2);
    // Set a mark on slot 1 (path_b).
    app.active_editor_mut().set_mark('z', (0, 0));
    // :bd removes slot 1; slot 0 (path_a) survives with its own editor.
    app.dispatch_ex("bd");
    assert_eq!(app.slots.len(), 1);
    // The surviving slot (path_a) never had mark 'z'.
    assert!(
        app.active_editor().mark('z').is_none(),
        "mark from removed slot must not survive after :bd"
    );
    let _ = std::fs::remove_file(&path_a);
    let _ = std::fs::remove_file(&path_b);
}

/// Regression: `:bwipe` in a multi-buffer session must also delete the closed
/// buffer's swap (same rationale as `bdelete_removes_closed_buffers_swap` — the
/// other slot-removal site in `buffer_ops.rs`).
#[test]
fn bwipe_removes_closed_buffers_swap() {
    let path_a = std::env::temp_dir().join("hjkl_bw_swap_a.txt");
    let path_b = std::env::temp_dir().join("hjkl_bw_swap_b.txt");
    std::fs::write(&path_a, "a\n").unwrap();
    std::fs::write(&path_b, "b\n").unwrap();
    let mut app = App::new(Some(path_a.clone()), false, None, None).unwrap();
    app.dispatch_ex(&format!("e {}", path_b.display()));

    // Inject a real swap file for the active (b) slot.
    let swap_b = std::env::temp_dir().join("hjkl_bw_swap_b.swp");
    std::fs::write(&swap_b, b"x").unwrap();
    app.active_mut().swap_path = Some(swap_b.clone());
    assert!(swap_b.exists(), "swap must exist before bwipe");

    app.dispatch_ex("bw");

    assert_eq!(app.slots.len(), 1, "one slot should remain after bwipe");
    assert!(
        !swap_b.exists(),
        "closed buffer's swap must be removed by bwipe"
    );
    let _ = std::fs::remove_file(&path_a);
    let _ = std::fs::remove_file(&path_b);
    let _ = std::fs::remove_file(&swap_b);
}

#[test]
fn bwipeout_multi_slot_removes_slot() {
    let path_a = std::env::temp_dir().join("hjkl_bwipeout_multi_a.txt");
    let path_b = std::env::temp_dir().join("hjkl_bwipeout_multi_b.txt");
    std::fs::write(&path_a, "a\n").unwrap();
    std::fs::write(&path_b, "b\n").unwrap();
    let mut app = App::new(Some(path_a.clone()), false, None, None).unwrap();
    app.dispatch_ex(&format!("e {}", path_b.display()));
    assert_eq!(app.slots.len(), 2);
    app.dispatch_ex("bw");
    assert_eq!(app.slots.len(), 1);
    let msg = app.bus.last_body_or_empty().to_string();
    assert!(
        msg.contains("wiped"),
        "expected wipe status message, got: {msg}"
    );
    let _ = std::fs::remove_file(&path_a);
    let _ = std::fs::remove_file(&path_b);
}

#[test]
fn bwipeout_blocks_dirty_without_force() {
    let path_a = std::env::temp_dir().join("hjkl_bwipeout_dirty_a.txt");
    let path_b = std::env::temp_dir().join("hjkl_bwipeout_dirty_b.txt");
    std::fs::write(&path_a, "a\n").unwrap();
    std::fs::write(&path_b, "b\n").unwrap();
    let mut app = App::new(Some(path_a.clone()), false, None, None).unwrap();
    app.dispatch_ex(&format!("e {}", path_b.display()));
    app.active_mut().dirty = true;
    app.dispatch_ex("bw");
    let msg = app.bus.last_body_or_empty().to_string();
    assert!(msg.contains("E89"), "expected E89, got: {msg}");
    assert_eq!(
        app.slots.len(),
        2,
        "slot must not be removed when dirty without force"
    );
    let _ = std::fs::remove_file(&path_a);
    let _ = std::fs::remove_file(&path_b);
}

// ── Alt-buffer (D2) tests ───────────────────────────────────────────────

#[test]
fn buffer_alt_swaps_with_prev_active() {
    let path_a = std::env::temp_dir().join("hjkl_d2_alt_a.txt");
    let path_b = std::env::temp_dir().join("hjkl_d2_alt_b.txt");
    let path_c = std::env::temp_dir().join("hjkl_d2_alt_c.txt");
    for p in [&path_a, &path_b, &path_c] {
        std::fs::write(p, "x\n").unwrap();
    }
    let mut app = App::new(Some(path_a.clone()), false, None, None).unwrap();
    app.dispatch_ex(&format!("e {}", path_b.display())); // active=1, prev=0
    app.dispatch_ex(&format!("e {}", path_c.display())); // active=2, prev=1
    assert_eq!(app.active_index(), 2);
    assert_eq!(app.prev_active, Some(1));

    // First alt: go back to 1, prev becomes 2.
    app.buffer_alt();
    assert_eq!(app.active_index(), 1);
    assert_eq!(app.prev_active, Some(2));

    // Second alt: go back to 2.
    app.buffer_alt();
    assert_eq!(app.active_index(), 2);

    for p in [&path_a, &path_b, &path_c] {
        let _ = std::fs::remove_file(p);
    }
}

#[test]
fn buffer_alt_with_single_slot_no_op_with_message() {
    let mut app = App::new(None, false, None, None).unwrap();
    assert_eq!(app.slots.len(), 1);
    app.buffer_alt();
    assert_eq!(app.active_index(), 0);
    let msg = app.bus.last_body_or_empty().to_string();
    assert!(
        msg.contains("only one buffer"),
        "expected 'only one buffer' message, got: {msg}"
    );
}

#[test]
fn bd_clears_prev_active() {
    let path_a = std::env::temp_dir().join("hjkl_d2_bd_a.txt");
    let path_b = std::env::temp_dir().join("hjkl_d2_bd_b.txt");
    std::fs::write(&path_a, "a\n").unwrap();
    std::fs::write(&path_b, "b\n").unwrap();
    let mut app = App::new(Some(path_a.clone()), false, None, None).unwrap();
    app.dispatch_ex(&format!("e {}", path_b.display())); // active=1, prev=0
    assert_eq!(app.prev_active, Some(0));
    // Force-close the active slot (b.txt).
    app.dispatch_ex("bd!");
    // prev_active must be reset so the stale index is gone.
    assert!(
        app.prev_active.is_none(),
        "prev_active should be None after bd!"
    );
    let _ = std::fs::remove_file(&path_a);
    let _ = std::fs::remove_file(&path_b);
}

// ── Phase E: multi-buffer ex-command parity tests ──────────────────────

#[test]
fn b_num_switches_by_index() {
    let path_a = std::env::temp_dir().join("hjkl_phe_bnum_a.txt");
    let path_b = std::env::temp_dir().join("hjkl_phe_bnum_b.txt");
    let path_c = std::env::temp_dir().join("hjkl_phe_bnum_c.txt");
    for p in [&path_a, &path_b, &path_c] {
        std::fs::write(p, "x\n").unwrap();
    }
    let mut app = App::new(Some(path_a.clone()), false, None, None).unwrap();
    app.dispatch_ex(&format!("e {}", path_b.display()));
    app.dispatch_ex(&format!("e {}", path_c.display()));
    assert_eq!(app.slots.len(), 3);
    app.dispatch_ex("b 2");
    assert_eq!(app.active_index(), 1, "`:b 2` should switch to index 1");
    for p in [&path_a, &path_b, &path_c] {
        let _ = std::fs::remove_file(p);
    }
}

#[test]
fn b_num_out_of_range_errors() {
    let mut app = App::new(None, false, None, None).unwrap();
    assert_eq!(app.slots.len(), 1);
    app.dispatch_ex("b 5");
    let msg = app.bus.last_body_or_empty().to_string();
    assert!(msg.contains("E86"), "expected E86, got: {msg}");
}

#[test]
fn b_name_substring_switches() {
    let path_foo = std::env::temp_dir().join("hjkl_phe_bname_foo.txt");
    let path_bar = std::env::temp_dir().join("hjkl_phe_bname_bar.txt");
    std::fs::write(&path_foo, "foo\n").unwrap();
    std::fs::write(&path_bar, "bar\n").unwrap();
    let mut app = App::new(Some(path_foo.clone()), false, None, None).unwrap();
    app.dispatch_ex(&format!("e {}", path_bar.display()));
    assert_eq!(app.active_index(), 1);
    // Switch to the foo slot by substring
    app.dispatch_ex("b foo");
    assert_eq!(
        app.active_index(),
        0,
        "`:b foo` should switch to foo's slot"
    );
    let _ = std::fs::remove_file(&path_foo);
    let _ = std::fs::remove_file(&path_bar);
}

#[test]
fn b_name_ambiguous_errors() {
    let path_a = std::env::temp_dir().join("hjkl_phe_bamb_foo_a.txt");
    let path_b = std::env::temp_dir().join("hjkl_phe_bamb_foo_b.txt");
    std::fs::write(&path_a, "a\n").unwrap();
    std::fs::write(&path_b, "b\n").unwrap();
    let mut app = App::new(Some(path_a.clone()), false, None, None).unwrap();
    app.dispatch_ex(&format!("e {}", path_b.display()));
    // Both filenames contain "foo" — ambiguous
    app.dispatch_ex("b foo");
    let msg = app.bus.last_body_or_empty().to_string();
    assert!(
        msg.contains("E93"),
        "expected E93 ambiguous error, got: {msg}"
    );
    let _ = std::fs::remove_file(&path_a);
    let _ = std::fs::remove_file(&path_b);
}

#[test]
fn bfirst_blast_jump_to_ends() {
    let path_a = std::env::temp_dir().join("hjkl_phe_bfl_a.txt");
    let path_b = std::env::temp_dir().join("hjkl_phe_bfl_b.txt");
    let path_c = std::env::temp_dir().join("hjkl_phe_bfl_c.txt");
    for p in [&path_a, &path_b, &path_c] {
        std::fs::write(p, "x\n").unwrap();
    }
    let mut app = App::new(Some(path_a.clone()), false, None, None).unwrap();
    app.dispatch_ex(&format!("e {}", path_b.display()));
    app.dispatch_ex(&format!("e {}", path_c.display()));
    assert_eq!(app.slots.len(), 3);
    // Start in middle
    app.dispatch_ex("b 2");
    assert_eq!(app.active_index(), 1);
    app.dispatch_ex("bfirst");
    assert_eq!(app.active_index(), 0, "`:bfirst` should go to slot 0");
    app.dispatch_ex("blast");
    assert_eq!(app.active_index(), 2, "`:blast` should go to last slot");
    for p in [&path_a, &path_b, &path_c] {
        let _ = std::fs::remove_file(p);
    }
}

#[test]
fn wa_writes_dirty_named_slots() {
    let path_a = std::env::temp_dir().join("hjkl_phe_wa_a.txt");
    let path_b = std::env::temp_dir().join("hjkl_phe_wa_b.txt");
    std::fs::write(&path_a, "original a\n").unwrap();
    std::fs::write(&path_b, "original b\n").unwrap();
    let mut app = App::new(Some(path_a.clone()), false, None, None).unwrap();
    app.dispatch_ex(&format!("e {}", path_b.display()));
    // Mark both slots dirty with new content
    app.slots[0].dirty = true;
    BufferEdit::replace_all(app.slots[0].editor.buffer_mut(), "edited a");
    app.slots[1].dirty = true;
    BufferEdit::replace_all(app.slots[1].editor.buffer_mut(), "edited b");
    app.dispatch_ex("wa");
    assert!(!app.slots[0].dirty, "slot 0 should be clean after :wa");
    assert!(!app.slots[1].dirty, "slot 1 should be clean after :wa");
    let contents_a = std::fs::read_to_string(&path_a).unwrap_or_default();
    let contents_b = std::fs::read_to_string(&path_b).unwrap_or_default();
    assert!(
        contents_a.contains("edited a"),
        "file a should contain edited content, got: {contents_a}"
    );
    assert!(
        contents_b.contains("edited b"),
        "file b should contain edited content, got: {contents_b}"
    );
    let _ = std::fs::remove_file(&path_a);
    let _ = std::fs::remove_file(&path_b);
}

#[test]
fn qa_blocks_when_any_slot_dirty() {
    let path_a = std::env::temp_dir().join("hjkl_phe_qa_dirty_a.txt");
    let path_b = std::env::temp_dir().join("hjkl_phe_qa_dirty_b.txt");
    std::fs::write(&path_a, "a\n").unwrap();
    std::fs::write(&path_b, "b\n").unwrap();
    let mut app = App::new(Some(path_a.clone()), false, None, None).unwrap();
    app.dispatch_ex(&format!("e {}", path_b.display()));
    app.slots[0].dirty = true;
    app.dispatch_ex("qa");
    assert!(
        !app.exit_requested,
        ":qa should not exit when dirty slot exists"
    );
    let msg = app.bus.last_body_or_empty().to_string();
    assert!(msg.contains("E37"), "expected E37, got: {msg}");
    let _ = std::fs::remove_file(&path_a);
    let _ = std::fs::remove_file(&path_b);
}

#[test]
fn qa_force_exits_with_dirty() {
    let path_a = std::env::temp_dir().join("hjkl_phe_qa_force_a.txt");
    std::fs::write(&path_a, "a\n").unwrap();
    let mut app = App::new(Some(path_a.clone()), false, None, None).unwrap();
    app.slots[0].dirty = true;
    app.dispatch_ex("qa!");
    assert!(app.exit_requested, ":qa! should exit even when dirty");
    let _ = std::fs::remove_file(&path_a);
}

#[test]
fn q_on_multi_slot_closes_slot_not_app() {
    let path_a = std::env::temp_dir().join("hjkl_phe_q_multi_a.txt");
    let path_b = std::env::temp_dir().join("hjkl_phe_q_multi_b.txt");
    std::fs::write(&path_a, "a\n").unwrap();
    std::fs::write(&path_b, "b\n").unwrap();
    let mut app = App::new(Some(path_a.clone()), false, None, None).unwrap();
    app.dispatch_ex(&format!("e {}", path_b.display()));
    assert_eq!(app.slots.len(), 2);
    app.dispatch_ex("q!");
    assert_eq!(
        app.slots.len(),
        1,
        "`:q!` with 2 slots should close active slot"
    );
    assert!(
        !app.exit_requested,
        "app should remain open after closing one slot"
    );
    let _ = std::fs::remove_file(&path_a);
    let _ = std::fs::remove_file(&path_b);
}

#[test]
fn q_on_last_slot_quits_app() {
    let mut app = App::new(None, false, None, None).unwrap();
    assert_eq!(app.slots.len(), 1);
    assert!(!app.active().dirty);
    app.dispatch_ex("q");
    assert!(app.exit_requested, "`:q` on clean last slot should exit");
}

/// Phase 1 of the hjkl-ex extraction (kryptic-sh/hjkl#73): `:q!` on a dirty
/// buffer must force-quit even though the buffer is unsaved. This exercises
/// the new `hjkl_ex::try_dispatch` → `bridge_ex_effect` path; if either side
/// regresses (registry stops resolving `q!` or the bridge drops `force=true`)
/// the dirty buffer would block the exit and the assertion fails.
#[test]
fn q_bang_force_quits_dirty_buffer_via_hjkl_ex() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "unsaved work");
    // Mark the buffer dirty so a plain `:q` would refuse with E37.
    app.active_mut().dirty = true;
    app.dispatch_ex("q!");
    assert!(
        app.exit_requested,
        "`:q!` must force-quit a dirty buffer (hjkl-ex Phase 1 routing)"
    );
}

// ── checktime / disk-change detection tests ────────────────────────────

/// Helper: bump mtime by writing a file then sleeping briefly so the
/// filesystem timestamp advances past the stored baseline.
#[test]
fn checktime_reloads_clean_buffer_when_disk_changed() {
    let path = std::env::temp_dir().join("hjkl_ct_reload.txt");
    std::fs::write(&path, "line1\nline2\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();
    assert_eq!(
        app.active_editor()
            .buffer()
            .rope()
            .lines()
            .map(|s| {
                let s = s.to_string();
                s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
            })
            .collect::<Vec<_>>(),
        vec!["line1", "line2"]
    );

    write_and_wait(&path, "new content\n");
    app.checktime_all();

    assert_eq!(
        app.active_editor()
            .buffer()
            .rope()
            .lines()
            .map(|s| {
                let s = s.to_string();
                s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
            })
            .collect::<Vec<_>>(),
        vec!["new content"],
        "buffer should be reloaded from disk"
    );
    assert!(!app.active().dirty, "reloaded buffer must not be dirty");
    assert_eq!(app.active().disk_state, DiskState::Synced);
    let _ = std::fs::remove_file(&path);
}

#[test]
fn checktime_marks_dirty_buffer_as_changed_on_disk_no_reload() {
    let path = std::env::temp_dir().join("hjkl_ct_dirty.txt");
    std::fs::write(&path, "original\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();

    // Dirty the buffer without touching disk.
    app.active_mut().dirty = true;

    write_and_wait(&path, "changed on disk\n");
    app.checktime_all();

    // Content must NOT have changed.
    assert_eq!(
        app.active_editor()
            .buffer()
            .rope()
            .lines()
            .map(|s| {
                let s = s.to_string();
                s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
            })
            .collect::<Vec<_>>(),
        vec!["original"],
        "dirty buffer must not be reloaded"
    );
    assert_eq!(
        app.active().disk_state,
        DiskState::ChangedOnDisk,
        "disk_state must be ChangedOnDisk"
    );
    let _ = std::fs::remove_file(&path);
}

#[test]
fn checktime_with_autoreload_off_does_not_reload_clean_buffer() {
    let path = std::env::temp_dir().join("hjkl_ct_noar.txt");
    std::fs::write(&path, "original\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();

    // Disable autoreload (default is on).
    app.dispatch_ex("set noautoreload");
    assert!(!app.active_editor().settings().autoreload);

    write_and_wait(&path, "changed on disk\n");
    app.checktime_all();

    // Clean buffer but autoreload off → must NOT reload; flagged ChangedOnDisk.
    assert_eq!(
        app.active_editor()
            .buffer()
            .rope()
            .lines()
            .map(|s| s.to_string().trim_end_matches('\n').to_string())
            .collect::<Vec<_>>(),
        vec!["original"],
        "autoreload off must leave the clean buffer untouched"
    );
    assert_eq!(app.active().disk_state, DiskState::ChangedOnDisk);
    let _ = std::fs::remove_file(&path);
}

#[test]
fn checktime_reload_preserves_cursor_column() {
    let path = std::env::temp_dir().join("hjkl_ct_curcol.txt");
    std::fs::write(&path, "abcdefgh\nsecond\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();
    // Park the cursor mid-line (row 0, col 4).
    app.active_editor_mut().jump_cursor(0, 4);

    // External change keeps row 0 long enough that col 4 is still valid.
    write_and_wait(&path, "abXXdefgh longer\nsecond\n");
    app.checktime_all();

    let (row, col) = app.active_editor().cursor();
    assert_eq!(
        (row, col),
        (0, 4),
        "reload must preserve cursor row + column"
    );
    let _ = std::fs::remove_file(&path);
}

#[test]
fn checktime_marks_deleted_when_file_removed() {
    let path = std::env::temp_dir().join("hjkl_ct_deleted.txt");
    std::fs::write(&path, "content\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();

    std::fs::remove_file(&path).unwrap();
    app.checktime_all();

    assert_eq!(app.active().disk_state, DiskState::DeletedOnDisk);
    // Buffer content preserved.
    assert_eq!(
        app.active_editor()
            .buffer()
            .rope()
            .lines()
            .map(|s| {
                let s = s.to_string();
                s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
            })
            .collect::<Vec<_>>(),
        vec!["content"]
    );
}

#[test]
fn checktime_recovers_after_file_recreated() {
    let path = std::env::temp_dir().join("hjkl_ct_recover.txt");
    std::fs::write(&path, "v1\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();

    // Delete → marks DeletedOnDisk.
    std::fs::remove_file(&path).unwrap();
    app.checktime_all();
    assert_eq!(app.active().disk_state, DiskState::DeletedOnDisk);

    // Recreate with new content — next checktime should reload (not dirty).
    write_and_wait(&path, "v2\n");
    app.checktime_all();

    assert_eq!(
        app.active_editor()
            .buffer()
            .rope()
            .lines()
            .map(|s| {
                let s = s.to_string();
                s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
            })
            .collect::<Vec<_>>(),
        vec!["v2"],
        "recreated file should be reloaded"
    );
    assert_eq!(app.active().disk_state, DiskState::Synced);
    let _ = std::fs::remove_file(&path);
}

// ── Event-driven autoreload (fs-watch, #242) ───────────────────────────────
//
// These drive `apply_fs_events` directly (the reconcile half of the watcher),
// so they need no live notify thread and stay hermetic. The watcher wiring
// (filter set, drain) is exercised end-to-end by the PTY test in
// tests/pty_harness/autoreload.rs.

/// Read a slot's lines with trailing newlines stripped.
fn fsw_lines(app: &App, idx: usize) -> Vec<String> {
    app.slots[idx]
        .editor
        .buffer()
        .rope()
        .lines()
        .map(|s| s.to_string().trim_end_matches('\n').to_string())
        .collect()
}

/// A `Modified` event on a clean+autoreload buffer reloads it in place and
/// reports the reload via the return value.
#[test]
fn fs_event_modified_reloads_clean_buffer() {
    let path = std::env::temp_dir().join("hjkl_fsw_modify.txt");
    std::fs::write(&path, "old\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();

    write_and_wait(&path, "fresh\n");
    let reloaded = app.apply_fs_events(vec![hjkl_fs_watch::FsEvent::Modified(path.clone())]);

    assert!(reloaded, "a clean buffer must report a reload");
    assert_eq!(fsw_lines(&app, app.focused_slot_idx()), vec!["fresh"]);
    assert!(!app.active().dirty);
    assert_eq!(app.active().disk_state, DiskState::Synced);
    let _ = std::fs::remove_file(&path);
}

/// A dirty, focused buffer is never clobbered by a watch event — content
/// preserved, flagged ChangedOnDisk, and the interactive keep/reload/diff
/// prompt (#241) is raised (repaint requested).
#[test]
fn fs_event_dirty_buffer_raises_prompt_no_reload() {
    let path = std::env::temp_dir().join("hjkl_fsw_dirty.txt");
    std::fs::write(&path, "original\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();
    app.active_mut().dirty = true;

    write_and_wait(&path, "external\n");
    let needs_repaint = app.apply_fs_events(vec![hjkl_fs_watch::FsEvent::Modified(path.clone())]);

    assert!(needs_repaint, "raising the prompt must request a repaint");
    assert!(
        app.pending_disk_change.is_some(),
        "focused dirty buffer must raise the keep/reload/diff prompt"
    );
    assert_eq!(fsw_lines(&app, app.focused_slot_idx()), vec!["original"]);
    assert_eq!(app.active().disk_state, DiskState::ChangedOnDisk);
    let _ = std::fs::remove_file(&path);
}

/// `:set noautoreload` makes a watch event flag the change without reloading.
#[test]
fn fs_event_autoreload_off_no_reload() {
    let path = std::env::temp_dir().join("hjkl_fsw_noar.txt");
    std::fs::write(&path, "original\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();
    app.dispatch_ex("set noautoreload");

    write_and_wait(&path, "external\n");
    let reloaded = app.apply_fs_events(vec![hjkl_fs_watch::FsEvent::Modified(path.clone())]);

    assert!(!reloaded);
    assert_eq!(fsw_lines(&app, app.focused_slot_idx()), vec!["original"]);
    assert_eq!(app.active().disk_state, DiskState::ChangedOnDisk);
    let _ = std::fs::remove_file(&path);
}

/// A `Removed` event flags the buffer DeletedOnDisk without dropping content.
#[test]
fn fs_event_removed_flags_deleted() {
    let path = std::env::temp_dir().join("hjkl_fsw_removed.txt");
    std::fs::write(&path, "content\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();

    std::fs::remove_file(&path).unwrap();
    let reloaded = app.apply_fs_events(vec![hjkl_fs_watch::FsEvent::Removed(path.clone())]);

    assert!(!reloaded);
    assert_eq!(app.active().disk_state, DiskState::DeletedOnDisk);
    assert_eq!(fsw_lines(&app, app.focused_slot_idx()), vec!["content"]);
}

/// An event for a path no buffer has open is a no-op.
#[test]
fn fs_event_unrelated_path_is_noop() {
    let path = std::env::temp_dir().join("hjkl_fsw_open.txt");
    std::fs::write(&path, "open\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();

    let other = std::env::temp_dir().join("hjkl_fsw_unrelated.txt");
    std::fs::write(&other, "noise\n").unwrap();
    let reloaded = app.apply_fs_events(vec![hjkl_fs_watch::FsEvent::Modified(other.clone())]);

    assert!(!reloaded, "event for an unopened path must do nothing");
    assert_eq!(fsw_lines(&app, app.focused_slot_idx()), vec!["open"]);
    assert_eq!(app.active().disk_state, DiskState::Synced);
    let _ = std::fs::remove_file(&path);
    let _ = std::fs::remove_file(&other);
}

/// A `Renamed { to }` whose destination is an open buffer reloads that buffer
/// (the `to` end is matched, not just `from`).
#[test]
fn fs_event_rename_to_open_path_reloads() {
    let path = std::env::temp_dir().join("hjkl_fsw_rename_to.txt");
    std::fs::write(&path, "old\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();

    write_and_wait(&path, "renamed-in\n");
    let from = std::env::temp_dir().join("hjkl_fsw_rename_from.txt");
    let reloaded = app.apply_fs_events(vec![hjkl_fs_watch::FsEvent::Renamed {
        from,
        to: path.clone(),
    }]);

    assert!(reloaded);
    assert_eq!(fsw_lines(&app, app.focused_slot_idx()), vec!["renamed-in"]);
    let _ = std::fs::remove_file(&path);
}

/// Two `Modified` events for the same file in one batch reload exactly once
/// (canonicalized + deduped), emitting a single reload notice.
#[test]
fn fs_event_duplicate_events_reload_once() {
    let path = std::env::temp_dir().join("hjkl_fsw_dedup.txt");
    std::fs::write(&path, "old\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();

    write_and_wait(&path, "deduped\n");
    let reloaded = app.apply_fs_events(vec![
        hjkl_fs_watch::FsEvent::Modified(path.clone()),
        hjkl_fs_watch::FsEvent::Modified(path.clone()),
    ]);

    assert!(reloaded);
    assert_eq!(fsw_lines(&app, app.focused_slot_idx()), vec!["deduped"]);
    let reload_notices = app
        .bus
        .history()
        .filter(|h| h.display_body().contains("reloaded from disk"))
        .count();
    assert_eq!(reload_notices, 1, "duplicate events must reload only once");
    let _ = std::fs::remove_file(&path);
}

/// Reloading from a watch event preserves the cursor row + column.
#[test]
fn fs_event_reload_preserves_cursor_column() {
    let path = std::env::temp_dir().join("hjkl_fsw_cursor.txt");
    std::fs::write(&path, "abcdefgh\nsecond\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();
    app.active_editor_mut().jump_cursor(0, 4);

    write_and_wait(&path, "abXXdefgh longer\nsecond\n");
    app.apply_fs_events(vec![hjkl_fs_watch::FsEvent::Modified(path.clone())]);

    assert_eq!(app.active_editor().cursor(), (0, 4));
    let _ = std::fs::remove_file(&path);
}

/// With two files open, an event for one reloads only that slot.
#[test]
fn fs_event_only_matching_slot_reloads() {
    let a = std::env::temp_dir().join("hjkl_fsw_multi_a.txt");
    let b = std::env::temp_dir().join("hjkl_fsw_multi_b.txt");
    std::fs::write(&a, "a-old\n").unwrap();
    std::fs::write(&b, "b-old\n").unwrap();
    let mut app = App::new(Some(a.clone()), false, None, None).unwrap();
    let b_idx = app.open_new_slot(b.clone()).unwrap();
    let a_idx = app.focused_slot_idx();

    write_and_wait(&a, "a-new\n");
    write_and_wait(&b, "b-new\n");
    // Only `a` changed as far as the watcher reports.
    let reloaded = app.apply_fs_events(vec![hjkl_fs_watch::FsEvent::Modified(a.clone())]);

    assert!(reloaded);
    assert_eq!(fsw_lines(&app, a_idx), vec!["a-new"], "a reloads");
    assert_eq!(
        fsw_lines(&app, b_idx),
        vec!["b-old"],
        "b must be untouched (no event for it)"
    );
    let _ = std::fs::remove_file(&a);
    let _ = std::fs::remove_file(&b);
}

/// An empty event batch is a no-op.
#[test]
fn fs_event_empty_batch_is_noop() {
    let mut app = App::new(None, false, None, None).unwrap();
    assert!(!app.apply_fs_events(Vec::new()));
}

/// The watched-set sync helper is a safe no-op when fs-watch isn't enabled
/// (the default in tests / `App::new`).
#[test]
fn fs_watch_helpers_noop_without_watcher() {
    let mut app = App::new(None, false, None, None).unwrap();
    // Must not panic; fs_watch is None.
    app.fs_watch_sync();
}

/// A `Removed` event flags DeletedOnDisk; a later `Created` event for a
/// recreated file reloads the new content (the delete→reappear branch reached
/// over the event channel, not just via `:checktime`).
#[test]
fn fs_event_recreate_after_delete_reloads() {
    let path = std::env::temp_dir().join("hjkl_fsw_recreate.txt");
    std::fs::write(&path, "v1\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();

    std::fs::remove_file(&path).unwrap();
    let r1 = app.apply_fs_events(vec![hjkl_fs_watch::FsEvent::Removed(path.clone())]);
    assert!(!r1);
    assert_eq!(app.active().disk_state, DiskState::DeletedOnDisk);

    write_and_wait(&path, "v2-recreated\n");
    let r2 = app.apply_fs_events(vec![hjkl_fs_watch::FsEvent::Created(path.clone())]);

    assert!(r2, "recreated file must reload");
    assert_eq!(
        fsw_lines(&app, app.focused_slot_idx()),
        vec!["v2-recreated"]
    );
    assert_eq!(app.active().disk_state, DiskState::Synced);
    let _ = std::fs::remove_file(&path);
}

/// A `Renamed` whose neither end is an open buffer is a no-op.
#[test]
fn fs_event_rename_unrelated_is_noop() {
    let path = std::env::temp_dir().join("hjkl_fsw_rename_noop_open.txt");
    std::fs::write(&path, "open\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();

    let from = std::env::temp_dir().join("hjkl_fsw_rn_from.txt");
    let to = std::env::temp_dir().join("hjkl_fsw_rn_to.txt");
    let reloaded = app.apply_fs_events(vec![hjkl_fs_watch::FsEvent::Renamed { from, to }]);

    assert!(!reloaded);
    assert_eq!(fsw_lines(&app, app.focused_slot_idx()), vec!["open"]);
    assert_eq!(app.active().disk_state, DiskState::Synced);
    let _ = std::fs::remove_file(&path);
}

/// A mixed batch (events for an open file + unrelated files) reloads only the
/// open file and ignores the rest.
#[test]
fn fs_event_mixed_batch_reloads_only_open() {
    let open = std::env::temp_dir().join("hjkl_fsw_mixed_open.txt");
    std::fs::write(&open, "old\n").unwrap();
    let mut app = App::new(Some(open.clone()), false, None, None).unwrap();

    write_and_wait(&open, "mixed-new\n");
    let noise_a = std::env::temp_dir().join("hjkl_fsw_mixed_noise_a.txt");
    let noise_b = std::env::temp_dir().join("hjkl_fsw_mixed_noise_b.txt");
    let reloaded = app.apply_fs_events(vec![
        hjkl_fs_watch::FsEvent::Created(noise_a.clone()),
        hjkl_fs_watch::FsEvent::Modified(open.clone()),
        hjkl_fs_watch::FsEvent::Removed(noise_b.clone()),
    ]);

    assert!(reloaded);
    assert_eq!(fsw_lines(&app, app.focused_slot_idx()), vec!["mixed-new"]);
    let _ = std::fs::remove_file(&open);
}

// ── Substitute ex-command tests ──────────────────────────────────────────────

/// `:%s/foo/bar/g` over a multi-line buffer replaces all occurrences.
#[test]
fn substitute_percent_global_multi_line() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "foo foo\nfoo");
    app.dispatch_ex("%s/foo/bar/g");
    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert_eq!(
        lines,
        vec!["bar bar", "bar"],
        "buffer should be fully substituted"
    );
    let msg = app.bus.last_body_or_empty().to_string();
    assert_eq!(msg, "3 substitutions on 2 lines", "status: {msg}");
}

/// `:s/foo/bar/` on the current line replaces only the first occurrence.
#[test]
fn substitute_current_line_first_only() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "foo foo\nfoo");
    app.dispatch_ex("s/foo/bar/");
    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert_eq!(lines[0], "bar foo", "only first occurrence on current line");
    assert_eq!(lines[1], "foo", "second line unchanged");
    let msg = app.bus.last_body_or_empty().to_string();
    assert_eq!(msg, "1 substitutions on 1 lines", "status: {msg}");
}

/// `:s//xxx/` after a `/foo` search reuses the last pattern.
#[test]
fn substitute_empty_pattern_reuses_last_search() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "hello world");
    // Simulate a prior search by setting last_search directly.
    app.active_editor_mut()
        .set_last_search(Some("world".to_string()), true);
    app.dispatch_ex("s//planet/");
    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert_eq!(
        lines[0], "hello planet",
        "should replace using last search pattern"
    );
    let msg = app.bus.last_body_or_empty().to_string();
    assert_eq!(msg, "1 substitutions on 1 lines", "status: {msg}");
}

/// `:s/foo/bar/` with no match leaves the buffer unchanged and shows "Pattern not found".
#[test]
fn substitute_no_match_shows_pattern_not_found() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "hello world");
    app.dispatch_ex("s/xyz/bar/");
    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert_eq!(lines[0], "hello world", "buffer should be unchanged");
    let msg = app.bus.last_body_or_empty().to_string();
    assert_eq!(msg, "Pattern not found", "status: {msg}");
}

// ── :Anvil ex command tests ───────────────────────────────────────────────────
#[test]
fn anvil_install_unknown_tool_sets_error_message() {
    let mut app = App::new(None, false, None, None).unwrap();
    app.dispatch_ex("Anvil install definitely-not-a-real-tool-xyz");
    let msg = app.bus.last_body_or_empty().to_string();
    assert!(
        msg.contains("unknown tool"),
        "expected 'unknown tool' in status message, got: {msg:?}"
    );
}

#[test]
fn anvil_uninstall_not_installed_graceful() {
    // Uninstalling a tool that has no package dir must not panic.
    // It should set a success or no-op status message.
    let mut app = App::new(None, false, None, None).unwrap();
    // rust-analyzer is in the registry but not installed in CI.
    app.dispatch_ex("Anvil uninstall rust-analyzer");
    // Either "removed" or "failed to resolve" — should not panic.
    let msg = app.bus.last_body_or_empty().to_string();
    assert!(
        !msg.is_empty(),
        "expected some status message after anvil uninstall"
    );
}

#[test]
fn anvil_update_all_with_zero_installed_tools() {
    // :Anvil update with no installed tools should reach the sweep-started toast.
    // In CI the XDG store is empty so read_rev returns None for all tools,
    // which means anvil_update_all skips all names and sets the sweep message.
    let mut app = App::new(None, false, None, None).unwrap();
    app.dispatch_ex("Anvil update");
    let msg = app.bus.last_body_or_empty().to_string();
    assert!(
        msg.contains("update sweep started"),
        "expected 'update sweep started', got: {msg:?}"
    );
}

#[test]
fn anvil_picker_source_builds_from_registry() {
    use crate::picker_sources::{AnvilPickerSource, AnvilState};

    let registry = hjkl_anvil::Registry::embedded().expect("embedded registry must load");
    let source = AnvilPickerSource::from_registry(&registry);

    // The embedded catalog has at least one tool (rust-analyzer).
    assert!(!source.items.is_empty(), "picker source must have items");

    // In CI nothing is installed, so every item should be Available.
    for item in &source.items {
        // State should be Available (no .rev files in CI).
        // We can't assert Available specifically in all environments, but
        // we can assert the item fields are consistent.
        let label = item.label();
        assert!(
            label.contains(&item.name),
            "label must contain tool name; got: {label:?}"
        );
        assert!(
            matches!(
                item.state,
                AnvilState::Available | AnvilState::Installed { .. } | AnvilState::Outdated { .. }
            ),
            "state must be one of the three variants"
        );
    }
}

#[test]
fn anvil_bad_subcommand_shows_usage() {
    let mut app = App::new(None, false, None, None).unwrap();
    app.dispatch_ex("Anvil badsubcommand something else");
    let msg = app.bus.last_body_or_empty().to_string();
    assert!(
        msg.contains("usage"),
        "expected usage hint in status message, got: {msg:?}"
    );
}

#[test]
fn unbound_chord_tail_trie_returns_multi_key_replay() {
    // <leader>x: leader is bound (as a prefix), but <leader>x is not.
    // The trie returns Unbound([<leader>, x]) with replay.len() > 1.
    // The event_loop now always forwards multi-key Unbound replays to the
    // engine (so gg/gj/etc work). This test verifies the trie shape only.
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "abcdef");

    let leader = app.config.editor.leader;
    let mut replay: Vec<hjkl_keymap::KeyEvent> = Vec::new();

    // First key: leader. Should be Pending → consumed = true.
    let consumed1 = app.dispatch_keymap(
        hjkl_keymap::KeyEvent::new(
            hjkl_keymap::KeyCode::Char(leader),
            hjkl_keymap::KeyModifiers::NONE,
        ),
        1,
        &mut replay,
    );
    assert!(consumed1, "leader should be consumed as Pending prefix");

    // Second key: 'x' — unmapped. The dispatch returns consumed=false
    // and replay=[leader, x] (both keys buffered by the trie).
    replay.clear();
    let consumed2 = app.dispatch_keymap(
        hjkl_keymap::KeyEvent::new(
            hjkl_keymap::KeyCode::Char('x'),
            hjkl_keymap::KeyModifiers::NONE,
        ),
        1,
        &mut replay,
    );
    assert!(!consumed2, "<leader>x is unbound → consumed=false");
    assert!(
        replay.len() > 1,
        "replay should contain both keys, got {} keys",
        replay.len()
    );
    // Note: event_loop now forwards multi-key replays to the engine.
    // <leader>x with leader=space → space (move-right) + x (delete-char).
    // This is vim-compatible; users can `:nmap <leader> <Nop>` to stop.
}

// ── Phase 2b hjkl-ex integration: :e <path> ────────────────────────────────

/// `:e <path>` dispatched via hjkl_ex::try_dispatch must open the file and
/// make its content visible in the active buffer.  This exercises the
/// EditFile early-intercept in dispatch_ex introduced in Phase 2b.
#[test]
fn colon_e_path_opens_file_via_hjkl_ex() {
    // Write a temp file with known content.
    let path = tmp_path("hjkl_ex_2b_edit_test.txt");
    std::fs::write(&path, "hello from hjkl-ex\n").unwrap();

    let mut app = App::new(None, false, None, None).unwrap();
    // dispatch_ex expects a command string without the leading `:`.
    app.dispatch_ex(&format!("e {}", path.display()));

    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert_eq!(
        lines,
        vec!["hello from hjkl-ex"],
        "`:e <path>` must load the file content into the active buffer; got {lines:?}"
    );
    let active_path = app
        .active()
        .filename
        .as_deref()
        .unwrap_or(std::path::Path::new(""));
    assert_eq!(
        active_path,
        path.as_path(),
        "`:e <path>` must set the active slot filename to the opened path"
    );

    let _ = std::fs::remove_file(&path);
}

/// `:bd` dispatched via hjkl_ex::try_dispatch on the only slot must reset
/// the buffer to an empty unnamed scratch (vim parity).
#[test]
fn colon_bd_via_hjkl_ex_clears_sole_buffer() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "some content");
    // Mark clean so buffer_delete doesn't refuse.
    app.active_mut().dirty = false;
    app.dispatch_ex("bd");
    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    // After :bd on the last slot the buffer is reset to empty unnamed scratch.
    assert_eq!(
        lines,
        vec![""],
        "`:bd` on sole buffer must leave an empty scratch; got {lines:?}"
    );
    assert!(
        app.active().filename.is_none(),
        "`:bd` on sole buffer must clear the filename"
    );
}

// ── Phase 7: filename expansion (`%`, `#`) integration tests ────────────────

/// `dispatch_ex("e %")` with a current filename set must re-open the same
/// file (no error) — the `%` expands to the current buffer path at dispatch
/// time.
#[test]
fn colon_e_percent_expands_to_current_file() {
    let path = tmp_path("hjkl_phase7_percent_test.txt");
    std::fs::write(&path, "phase7 percent\n").unwrap();

    let mut app = App::new(None, false, None, None).unwrap();
    // Open the file by path first so active().filename is set.
    app.dispatch_ex(&format!("e {}", path.display()));
    let active_after_first_open = app
        .active()
        .filename
        .as_deref()
        .unwrap_or(std::path::Path::new(""))
        .to_path_buf();

    // Now dispatch `e %` — should expand to the same path and re-open.
    app.dispatch_ex("e %");

    let active_after_percent = app
        .active()
        .filename
        .as_deref()
        .unwrap_or(std::path::Path::new(""))
        .to_path_buf();

    assert_eq!(
        active_after_percent, active_after_first_open,
        "`:e %%` must expand to the current file path; got {active_after_percent:?}"
    );
    // No error message — expansion and re-open succeeded.
    assert!(
        app.bus.last_body_or_empty().is_empty() || !app.bus.last_body_or_empty().starts_with('E'),
        "`:e %%` must not produce an error; got: {:?}",
        app.bus.last_body_or_empty()
    );

    let _ = std::fs::remove_file(&path);
}

/// `dispatch_ex("e #")` after opening two files must switch back to the
/// first file (alternate buffer expansion).
#[test]
fn colon_e_hash_expands_to_alt() {
    let path_a = tmp_path("hjkl_phase7_hash_a.txt");
    let path_b = tmp_path("hjkl_phase7_hash_b.txt");
    std::fs::write(&path_a, "file a\n").unwrap();
    std::fs::write(&path_b, "file b\n").unwrap();

    let mut app = App::new(None, false, None, None).unwrap();
    // Open file A.
    app.dispatch_ex(&format!("e {}", path_a.display()));
    // Open file B — now A becomes the alternate buffer (prev_active).
    app.dispatch_ex(&format!("e {}", path_b.display()));

    let active_before = app
        .active()
        .filename
        .as_deref()
        .map(|p| p.to_path_buf())
        .unwrap();
    assert!(
        active_before.ends_with("hjkl_phase7_hash_b.txt"),
        "sanity: active must be B; got {active_before:?}"
    );

    // `e #` must expand to file A and open it.
    app.dispatch_ex("e #");

    let active_after = app
        .active()
        .filename
        .as_deref()
        .map(|p| p.to_path_buf())
        .unwrap();
    assert!(
        active_after.ends_with("hjkl_phase7_hash_a.txt"),
        "`:e #` must expand to alt (file A); got {active_after:?}"
    );

    let _ = std::fs::remove_file(&path_a);
    let _ = std::fs::remove_file(&path_b);
}

// ── Phase 4b: host-registry window/tab command tests ────────────────────────

#[test]
fn colon_split_via_host_registry() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "hello");
    let before = app.layout().leaves().len();
    app.dispatch_ex("split");
    assert_eq!(
        app.layout().leaves().len(),
        before + 1,
        ":split must add one leaf"
    );
}

#[test]
fn colon_sp_alias_via_host_registry() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "hello");
    let before = app.layout().leaves().len();
    app.dispatch_ex("sp");
    assert_eq!(
        app.layout().leaves().len(),
        before + 1,
        ":sp alias must add one leaf"
    );
}

#[test]
fn colon_vsplit_via_host_registry() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "hello");
    let before = app.layout().leaves().len();
    app.dispatch_ex("vsplit");
    assert_eq!(
        app.layout().leaves().len(),
        before + 1,
        ":vsplit must add one leaf"
    );
}

#[test]
fn colon_close_via_host_registry() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "hello");
    app.dispatch_ex("split");
    assert_eq!(app.layout().leaves().len(), 2, "setup: need 2 leaves");
    app.dispatch_ex("close");
    assert_eq!(
        app.layout().leaves().len(),
        1,
        ":close must collapse back to 1 leaf"
    );
}

#[test]
fn colon_tabnew_via_host_registry() {
    let mut app = App::new(None, false, None, None).unwrap();
    let before = app.tabs.len();
    app.dispatch_ex("tabnew");
    assert_eq!(app.tabs.len(), before + 1, ":tabnew must add a tab");
}

#[test]
fn colon_tabprev_via_host_registry() {
    let mut app = App::new(None, false, None, None).unwrap();
    app.dispatch_ex("tabnew");
    app.dispatch_ex("tabnew");
    // active_tab = 2; go back one.
    let before = app.active_tab;
    app.dispatch_ex("tabprev");
    assert_eq!(
        app.active_tab,
        before - 1,
        ":tabprev must decrement active_tab"
    );
}

#[test]
fn colon_tabclose_via_host_registry() {
    let mut app = App::new(None, false, None, None).unwrap();
    app.dispatch_ex("tabnew");
    assert_eq!(app.tabs.len(), 2, "setup: need 2 tabs");
    app.dispatch_ex("tabclose");
    assert_eq!(app.tabs.len(), 1, ":tabclose must remove a tab");
}

#[test]
fn colon_only_via_host_registry() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "data");
    app.dispatch_ex("split");
    app.dispatch_ex("split");
    assert!(
        app.layout().leaves().len() >= 2,
        "setup: need at least 2 leaves"
    );
    app.dispatch_ex("only");
    assert_eq!(
        app.layout().leaves().len(),
        1,
        ":only must leave exactly 1 leaf"
    );
}

// ── Phase 4c: buffer-nav host-registry tests ─────────────────────────────────

#[test]
fn colon_bnext_via_host_registry() {
    let mut app = setup_three_slot_app();
    assert_eq!(app.active_index(), 2);
    app.dispatch_ex("bnext");
    assert_eq!(app.active_index(), 0, ":bnext must wrap to first slot");
}

#[test]
fn colon_bn_alias_via_host_registry() {
    let mut app = setup_three_slot_app();
    assert_eq!(app.active_index(), 2);
    app.dispatch_ex("bn");
    assert_eq!(app.active_index(), 0, ":bn alias must wrap to first slot");
}

#[test]
fn colon_bprevious_via_host_registry() {
    let mut app = setup_three_slot_app();
    // Start at slot 2, go back to slot 1.
    app.dispatch_ex("bprevious");
    assert_eq!(app.active_index(), 1, ":bprevious must retreat one slot");
}

#[test]
fn colon_bp_alias_via_host_registry() {
    let mut app = setup_three_slot_app();
    app.dispatch_ex("bp");
    assert_eq!(app.active_index(), 1, ":bp alias must retreat one slot");
}

#[test]
fn colon_bfirst_via_host_registry() {
    let mut app = setup_three_slot_app();
    assert_eq!(app.active_index(), 2);
    app.dispatch_ex("bfirst");
    assert_eq!(app.active_index(), 0, ":bfirst must jump to slot 0");
}

#[test]
fn colon_blast_via_host_registry() {
    let mut app = setup_three_slot_app();
    // Switch to first so blast has work to do.
    app.dispatch_ex("bfirst");
    assert_eq!(app.active_index(), 0);
    app.dispatch_ex("blast");
    assert_eq!(
        app.active_index(),
        app.slots.len() - 1,
        ":blast must jump to the last slot"
    );
}

#[test]
fn colon_ls_via_host_registry() {
    let mut app = setup_three_slot_app();
    app.dispatch_ex("ls");
    let msg = app.bus.last_body_or_empty().to_string();
    assert!(!msg.is_empty(), ":ls must produce a status message");
}

#[test]
fn colon_buffers_via_host_registry() {
    let mut app = setup_three_slot_app();
    app.dispatch_ex("buffers");
    let msg = app
        .info_popup
        .as_ref()
        .map(|p| p.content.clone())
        .unwrap_or_else(|| app.bus.last_body_or_empty().to_string());
    assert!(!msg.is_empty(), ":buffers must produce output");
}

#[test]
fn colon_clipboard_via_host_registry() {
    let mut app = App::new(None, false, None, None).unwrap();
    app.dispatch_ex("clipboard");
    let msg = app
        .info_popup
        .as_ref()
        .map(|p| p.content.clone())
        .unwrap_or_else(|| app.bus.last_body_or_empty().to_string());
    assert!(!msg.is_empty(), ":clipboard must produce output");
}

// ── Phase 4d2: misc host-registry tests ──────────────────────────────────────

#[test]
fn colon_picker_via_host_registry() {
    let mut app = App::new(None, false, None, None).unwrap();
    assert!(app.picker.is_none(), "picker must start None");
    app.dispatch_ex("picker");
    assert!(app.picker.is_some(), ":picker must open the picker");
}

#[test]
fn colon_rg_via_host_registry() {
    let mut app = App::new(None, false, None, None).unwrap();
    app.dispatch_ex("rg");
    assert!(app.picker.is_some(), ":rg must open the grep picker");
}

#[test]
fn colon_rg_with_pattern_via_host_registry() {
    let mut app = App::new(None, false, None, None).unwrap();
    app.dispatch_ex("rg fn main");
    assert!(
        app.picker.is_some(),
        ":rg <pattern> must open the grep picker"
    );
}

#[test]
fn leader_slash_opens_grep_picker() {
    let mut app = App::new(None, false, None, None).unwrap();
    assert!(app.picker.is_none(), "picker must start None");
    app.route_chord_key(key(KeyCode::Char(' ')));
    app.route_chord_key(key(KeyCode::Char('/')));
    assert!(
        app.picker.is_some(),
        "<leader>/ must open the grep picker; status={:?}",
        app.bus.last_body_or_empty()
    );
}

/// End-to-end leader-slash → type a query → confirm the rg-backed picker
/// enumerates items. Skips when rg / grep / findstr are all absent.
#[test]
fn leader_slash_grep_picker_populates_items() {
    if std::process::Command::new("rg")
        .arg("--version")
        .output()
        .is_err()
        && std::process::Command::new("grep")
            .arg("--version")
            .output()
            .is_err()
    {
        eprintln!("skipping: no rg or grep on PATH");
        return;
    }

    // Seed a tmp dir with a known match.
    let dir = std::env::temp_dir().join(format!(
        "hjkl_grep_picker_{}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("findme.txt");
    std::fs::write(&file, "alpha\nUNIQUE_NEEDLE_42\nomega\n").unwrap();

    // App's cwd drives the grep root.
    let orig_cwd = std::env::current_dir().unwrap();
    std::env::set_current_dir(&dir).unwrap();

    let mut app = App::new(None, false, None, None).unwrap();
    app.route_chord_key(key(KeyCode::Char(' ')));
    app.route_chord_key(key(KeyCode::Char('/')));
    assert!(app.picker.is_some(), "<leader>/ must open the picker");

    // Type query, then poll until rg returns the seeded match.
    for c in "UNIQUE_NEEDLE_42".chars() {
        app.handle_picker_key(key(KeyCode::Char(c)));
    }
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
    let mut got_match = false;
    while std::time::Instant::now() < deadline {
        // Drive both refresh (schedules requery) and tick (fires the
        // debounced rg spawn). In production, render.rs does this every frame.
        if let Some(p) = app.picker.as_mut() {
            let _ = p.refresh();
            p.tick(std::time::Instant::now());
            let _ = p.refresh();
        }
        let count = app.picker.as_ref().map(|p| p.matched()).unwrap_or(0);
        if count > 0 {
            got_match = true;
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(50));
    }

    std::env::set_current_dir(&orig_cwd).unwrap();
    let _ = std::fs::remove_dir_all(&dir);

    assert!(
        got_match,
        "rg-backed grep picker must return at least one match for the seeded UNIQUE_NEEDLE_42; \
         status={:?}",
        app.bus.last_body_or_empty()
    );
}

#[test]
fn colon_b_numeric_via_host_registry() {
    let mut app = setup_three_slot_app();
    // slots are 0-indexed internally; :b 2 means slot index 1
    app.dispatch_ex("b 2");
    assert_eq!(app.active_index(), 1, ":b 2 must switch to slot index 1");
}

#[test]
fn colon_b_nonexistent_via_host_registry() {
    let mut app = setup_three_slot_app();
    app.dispatch_ex("b nonexistent_buffer_xyz");
    let msg = app.bus.last_body_or_empty().to_string();
    assert!(
        msg.contains("E94") || msg.contains("No matching"),
        ":b nonexistent must set error status"
    );
}

#[test]
fn colon_bpicker_via_host_registry() {
    let mut app = setup_three_slot_app();
    assert!(app.picker.is_none());
    app.dispatch_ex("bpicker");
    assert!(app.picker.is_some(), ":bpicker must open the buffer picker");
}

#[test]
fn colon_checktime_via_host_registry() {
    // checktime_all should not panic on a fresh app
    let mut app = App::new(None, false, None, None).unwrap();
    app.dispatch_ex("checktime");
    // no assertion beyond no-panic; bus may or may not have entries
}

#[test]
fn colon_vnew_via_host_registry() {
    let mut app = App::new(None, false, None, None).unwrap();
    let before = app.slots.len();
    app.dispatch_ex("vnew");
    assert!(app.slots.len() > before, ":vnew must add a new buffer slot");
}

#[test]
fn colon_new_via_host_registry() {
    let mut app = App::new(None, false, None, None).unwrap();
    let before = app.slots.len();
    app.dispatch_ex("new");
    assert!(app.slots.len() > before, ":new must add a new buffer slot");
}

#[test]
fn colon_tabfirst_via_host_registry() {
    let mut app = App::new(None, false, None, None).unwrap();
    // add a second tab so tabfirst has work to do
    app.dispatch_ex("tabnew");
    assert!(app.active_tab > 0 || app.tabs.len() > 1);
    app.dispatch_ex("tabfirst");
    assert_eq!(app.active_tab, 0, ":tabfirst must jump to tab 0");
}

#[test]
fn colon_tablast_via_host_registry() {
    let mut app = App::new(None, false, None, None).unwrap();
    app.dispatch_ex("tabnew");
    app.dispatch_ex("tabfirst");
    assert_eq!(app.active_tab, 0);
    app.dispatch_ex("tablast");
    let last = app.tabs.len() - 1;
    assert_eq!(app.active_tab, last, ":tablast must jump to the last tab");
}

// ── Phase 4f: host-registry tests ────────────────────────────────────────────

#[test]
fn colon_tabonly_via_host_registry() {
    // Two-tab setup: tabonly must close all but the current tab.
    let mut app = App::new(None, false, None, None).unwrap();
    app.dispatch_ex("tabnew");
    app.dispatch_ex("tabnew");
    assert_eq!(app.tabs.len(), 3);
    // Navigate to middle tab so we aren't on the last one.
    app.dispatch_ex("tabfirst");
    app.dispatch_ex("tabnext");
    assert_eq!(app.active_tab, 1);
    app.dispatch_ex("tabonly");
    assert_eq!(app.tabs.len(), 1, ":tabonly must leave exactly one tab");
    assert_eq!(app.active_tab, 0, ":tabonly must reset active_tab to 0");
}

#[test]
fn colon_tabs_via_host_registry() {
    // Multi-tab setup: :tabs must populate info_popup.
    let mut app = App::new(None, false, None, None).unwrap();
    app.dispatch_ex("tabnew");
    assert_eq!(app.tabs.len(), 2);
    app.info_popup = None;
    app.dispatch_ex("tabs");
    assert!(
        app.info_popup.is_some(),
        ":tabs must set info_popup with tab listing"
    );
    let popup = app.info_popup.as_ref().unwrap();
    assert!(
        popup.content.contains("Tab page 1"),
        "popup must list Tab page 1"
    );
    assert!(
        popup.content.contains("Tab page 2"),
        "popup must list Tab page 2"
    );
}

#[test]
fn colon_lnext_via_host_registry() {
    // No live LSP server — lnext_severity(None) must not panic on empty diag list.
    let mut app = App::new(None, false, None, None).unwrap();
    app.dispatch_ex("lnext");
    // no assertion beyond no-panic
}

#[test]
fn colon_lopen_via_host_registry() {
    // open_diag_picker with no diagnostics: routes through host registry and
    // pushes "no diagnostics" toast (empty-state path, no server needed).
    let mut app = App::new(None, false, None, None).unwrap();
    app.dispatch_ex("lopen");
    let msg = app.bus.last_body_or_empty().to_string();
    assert!(
        msg.contains("no diagnostics"),
        ":lopen with empty diag list must set status 'no diagnostics', got: {msg}"
    );
}

#[test]
fn colon_resize_via_host_registry() {
    // Horizontal split: dispatch `resize +5` must grow the focused window.
    let mut app = App::new(None, false, None, None).unwrap();
    app.dispatch_ex("sp");
    let rect = ratatui::layout::Rect {
        x: 0,
        y: 0,
        width: 80,
        height: 40,
    };
    let fw = app.focused_window();
    inject_split_rect(app.layout_mut(), fw, rect);

    let ratio_before = if let window::LayoutTree::Split { ratio, .. } = app.layout() {
        *ratio
    } else {
        panic!("expected Split");
    };

    app.dispatch_ex("resize +5");

    let ratio_after = if let window::LayoutTree::Split { ratio, .. } = app.layout() {
        *ratio
    } else {
        panic!("expected Split");
    };

    assert!(
        ratio_after > ratio_before,
        ":resize +5 must grow focused window ratio: before={ratio_before} after={ratio_after}"
    );
}

#[test]
fn colon_vertical_resize_via_host_registry() {
    // Vertical split: dispatch `vertical resize +5` must grow focused window width.
    let mut app = App::new(None, false, None, None).unwrap();
    app.dispatch_ex("vsp");
    let rect = ratatui::layout::Rect {
        x: 0,
        y: 0,
        width: 80,
        height: 24,
    };
    let fw = app.focused_window();
    inject_split_rect(app.layout_mut(), fw, rect);

    let ratio_before = if let window::LayoutTree::Split { ratio, .. } = app.layout() {
        *ratio
    } else {
        panic!("expected Split");
    };

    app.dispatch_ex("vertical resize +5");

    let ratio_after = if let window::LayoutTree::Split { ratio, .. } = app.layout() {
        *ratio
    } else {
        panic!("expected Split");
    };

    assert!(
        ratio_after > ratio_before,
        ":vertical resize +5 must grow focused window width ratio: before={ratio_before} after={ratio_after}"
    );
}

// ── Swap file / crash-recovery tests (issue #185) ─────────────────────────

/// `:w` must delete the swap file after a successful save.
/// Uses an injected swap_path to avoid mutating XDG env vars in parallel tests.
#[test]
fn colon_write_removes_swap_file() {
    let td = tempfile::tempdir().unwrap();
    let file_path = td.path().join("test_write_swap.txt");
    std::fs::write(&file_path, "hello\n").unwrap();

    let mut app = App::new(Some(file_path.clone()), false, None, None).unwrap();
    app.pending_recovery = None;

    // Inject a swap path directly into the slot.
    let swap_path = td.path().join("test_write_swap.swp");
    app.active_mut().swap_path = Some(swap_path.clone());

    // Seed some dirty content so dirty_gen advances.
    seed_buffer(&mut app, "changed content");
    app.active_mut().dirty = true;

    // Force-write swap.
    let idx = app.focused_slot_idx();
    app.write_swap_for_slot(idx);
    assert!(
        swap_path.exists(),
        "swap file must exist after write_swap_for_slot"
    );

    // Now save the file — should delete the swap.
    app.dispatch_ex("write");
    assert!(!swap_path.exists(), "swap file must be deleted after :w");
}

/// `:preserve` must write the swap immediately.
#[test]
fn colon_preserve_writes_swap() {
    let td = tempfile::tempdir().unwrap();
    let file_path = td.path().join("test_preserve_swap.txt");
    std::fs::write(&file_path, "initial\n").unwrap();

    let mut app = App::new(Some(file_path.clone()), false, None, None).unwrap();
    app.pending_recovery = None;

    // Inject a swap path directly into the slot.
    let swap_path = td.path().join("test_preserve_swap.swp");
    app.active_mut().swap_path = Some(swap_path.clone());

    seed_buffer(&mut app, "modified content");
    app.active_mut().dirty = true;

    // `:preserve` should write the swap.
    app.dispatch_ex("preserve");

    // Verify that the swap file was actually written.
    assert!(swap_path.exists(), "swap file must exist after :preserve");
}

/// Opening a file whose swap is newer than the on-disk version enters
/// recovery state (`pending_recovery.is_some()`).
///
/// This test writes the swap directly to a temp directory and injects the
/// swap_path onto the slot to avoid racing with other tests that mutate
/// XDG_CACHE_HOME.
#[test]
fn open_file_with_newer_swap_enters_recovery_state() {
    let td = tempfile::tempdir().unwrap();
    let file_path = td.path().join("test_recovery.txt");
    std::fs::write(&file_path, "on disk content\n").unwrap();

    let canonical = std::fs::canonicalize(&file_path).unwrap();

    let file_mtime_ms = std::fs::metadata(&file_path)
        .unwrap()
        .modified()
        .unwrap()
        .duration_since(std::time::SystemTime::UNIX_EPOCH)
        .unwrap()
        .as_millis() as u64;

    // Write the swap file directly into the temp dir (bypasses XDG).
    let swap_path = td.path().join("test_recovery.swp");
    let header = hjkl_app::swap::SwapHeader {
        magic: hjkl_app::swap::SwapHeader::MAGIC,
        version: hjkl_app::swap::SwapHeader::VERSION,
        canonical_path: canonical.to_string_lossy().into_owned(),
        file_mtime_unix_ms: file_mtime_ms,
        // Write time 10s after mtime → swap is "newer".
        write_time_unix_ms: file_mtime_ms + 10_000,
        cursor: (0, 0),
        writer_pid: std::process::id(),
    };
    let rope = ropey::Rope::from_str("swap body content");
    hjkl_app::swap::write_swap(&swap_path, &header, &rope).unwrap();

    // Create app without a pre-existing swap so App::new doesn't interfere.
    let mut app = App::new(Some(file_path.clone()), false, None, None).unwrap();
    // Clear any pending_recovery from App::new, then inject our swap path
    // directly and re-check.
    app.pending_recovery = None;
    app.active_mut().swap_path = Some(swap_path.clone());
    let idx = app.focused_slot_idx();
    let recovery_needed = app.check_recovery_on_open(idx);
    assert!(
        recovery_needed,
        "check_recovery_on_open must return true when swap is newer"
    );
    assert!(
        app.pending_recovery.is_some(),
        "pending_recovery must be set when swap is newer than disk"
    );
}

/// Choosing 'y' in the recovery prompt loads the swap body.
#[test]
fn recovery_y_loads_swap_body() {
    let td = tempfile::tempdir().unwrap();
    let file_path = td.path().join("test_recovery_y.txt");
    std::fs::write(&file_path, "on disk\n").unwrap();

    let canonical = std::fs::canonicalize(&file_path).unwrap();

    let file_mtime_ms = std::fs::metadata(&file_path)
        .unwrap()
        .modified()
        .unwrap()
        .duration_since(std::time::SystemTime::UNIX_EPOCH)
        .unwrap()
        .as_millis() as u64;

    let swap_path = td.path().join("test_recovery_y.swp");
    let header = hjkl_app::swap::SwapHeader {
        magic: hjkl_app::swap::SwapHeader::MAGIC,
        version: hjkl_app::swap::SwapHeader::VERSION,
        canonical_path: canonical.to_string_lossy().into_owned(),
        file_mtime_unix_ms: file_mtime_ms,
        write_time_unix_ms: file_mtime_ms + 10_000,
        cursor: (0, 0),
        writer_pid: std::process::id(),
    };
    let rope = ropey::Rope::from_str("recovered content");
    hjkl_app::swap::write_swap(&swap_path, &header, &rope).unwrap();

    let mut app = App::new(Some(file_path.clone()), false, None, None).unwrap();
    app.pending_recovery = None;
    app.active_mut().swap_path = Some(swap_path.clone());
    let idx = app.focused_slot_idx();
    app.check_recovery_on_open(idx);
    assert!(app.pending_recovery.is_some(), "must be in recovery state");

    // Simulate pressing 'y'.
    app.handle_recovery_key(key(crossterm::event::KeyCode::Char('y')));
    assert!(
        app.pending_recovery.is_none(),
        "pending_recovery must be cleared after 'y'"
    );
    let content = app.active_editor().buffer().content_joined();
    assert!(
        content.contains("recovered content"),
        "buffer must contain swap body after 'y', got: {content:?}"
    );
}

// ── #185 recovery must reset syntax (content_reset) ──────────────────────────

#[test]
fn recovery_y_resets_syntax_spans() {
    // Repro for the syntax-highlight-breaks-after-recovery bug: the recovery
    // accept path must signal a content reset (like a normal file open) so the
    // syntax layer drops its stale tree + spans. We assert this via the proxy
    // that `handle_active_content_reset` clears `styled_spans` to empty — which
    // only happens when the content-install flags `pending_content_reset`.
    let td = tempfile::tempdir().unwrap();
    let file_path = td.path().join("recover_syntax.txt");
    std::fs::write(&file_path, "on disk\n").unwrap();
    let canonical = std::fs::canonicalize(&file_path).unwrap();
    let file_mtime_ms = std::fs::metadata(&file_path)
        .unwrap()
        .modified()
        .unwrap()
        .duration_since(std::time::SystemTime::UNIX_EPOCH)
        .unwrap()
        .as_millis() as u64;

    let swap_path = td.path().join("recover_syntax.swp");
    let header = hjkl_app::swap::SwapHeader {
        magic: hjkl_app::swap::SwapHeader::MAGIC,
        version: hjkl_app::swap::SwapHeader::VERSION,
        canonical_path: canonical.to_string_lossy().into_owned(),
        file_mtime_unix_ms: file_mtime_ms,
        write_time_unix_ms: file_mtime_ms + 10_000,
        cursor: (0, 0),
        writer_pid: std::process::id(),
    };
    let rope = ropey::Rope::from_str("recovered body line one\nline two\n");
    hjkl_app::swap::write_swap(&swap_path, &header, &rope).unwrap();

    let mut app = App::new(Some(file_path.clone()), false, None, None).unwrap();
    app.pending_recovery = None;
    app.active_mut().swap_path = Some(swap_path.clone());

    let idx = app.focused_slot_idx();

    // The slot's syntax tree was parsed against the on-disk bytes in
    // build_slot. Recovering must force a fresh parse_initial — i.e. signal a
    // FULL content reset (pending_content_reset), not an incremental ContentEdit
    // — or the retained tree drifts against the swapped-in bytes and
    // highlighting breaks (#185). Drain build_slot's own reset first, then
    // install the recovered body and assert the reset fired.
    let _ = app.active_editor_mut().take_content_reset();
    app.recover_install_content(idx, "recovered body line one\nline two\n", 0, 0);
    assert!(
        app.active_editor_mut().take_content_reset(),
        "recovery content install must signal a full content reset (set_content), \
         not an incremental edit (replace_all) — else the syntax tree drifts"
    );
    let content = app.active_editor().buffer().content_joined();
    assert!(
        content.contains("recovered body line one"),
        "buffer must hold the recovered body, got: {content:?}"
    );
}

// ── PID-lock multi-instance tests (issue #185) ────────────────────────────────

/// Opening a file whose swap was written by a LIVE process (pid 1 = init/launchd,
/// always alive on unix, always != our pid) must be refused with E325.
///
/// Gated `#[cfg(unix)]` because the liveness check uses kill(2) which is
/// unix-only; on non-unix pid_is_alive always returns false (no enforcement).
#[test]
#[cfg(unix)]
fn open_locked_file_refused_when_pid_alive() {
    let td = tempfile::tempdir().unwrap();
    let file_path = td.path().join("locked_file.txt");
    std::fs::write(&file_path, "on disk\n").unwrap();

    let canonical = std::fs::canonicalize(&file_path).unwrap();
    let file_mtime_ms = std::fs::metadata(&file_path)
        .unwrap()
        .modified()
        .unwrap()
        .duration_since(std::time::SystemTime::UNIX_EPOCH)
        .unwrap()
        .as_millis() as u64;

    let swap_path = td.path().join("locked_file.swp");
    // Use pid=1 (init/launchd) — always alive and always != our pid.
    let header = hjkl_app::swap::SwapHeader {
        magic: hjkl_app::swap::SwapHeader::MAGIC,
        version: hjkl_app::swap::SwapHeader::VERSION,
        canonical_path: canonical.to_string_lossy().into_owned(),
        file_mtime_unix_ms: file_mtime_ms,
        write_time_unix_ms: file_mtime_ms + 10_000,
        cursor: (0, 0),
        writer_pid: 1, // pid 1 = init/launchd, always alive, never our pid
    };
    let rope = ropey::Rope::from_str("locked content");
    hjkl_app::swap::write_swap(&swap_path, &header, &rope).unwrap();

    let mut app = App::new(Some(file_path.clone()), false, None, None).unwrap();
    app.pending_recovery = None;
    let slot_count_before = app.slots.len();
    app.active_mut().swap_path = Some(swap_path.clone());
    let idx = app.focused_slot_idx();
    let recovery = app.check_recovery_on_open(idx);

    // Must be refused: check_recovery_on_open returns false AND removes the slot.
    assert!(!recovery, "locked file must not enter recovery state");
    assert!(
        app.pending_recovery.is_none(),
        "pending_recovery must remain None for a locked file"
    );
    // The error message must contain E325.
    let msgs: Vec<&str> = app.bus.history().map(|h| h.body.as_str()).collect();
    assert!(
        msgs.iter().any(|m| m.contains("E325")),
        "E325 error must be reported; got: {msgs:?}"
    );
    // The slot count must have decreased (slot removed on refusal) or stayed
    // the same if there was only one slot (we never drop the last slot).
    if slot_count_before > 1 {
        assert!(
            app.slots.len() < slot_count_before,
            "refused slot must be removed"
        );
    }
}

/// Opening a file whose swap was written by a DEAD process must proceed to
/// the normal recovery prompt (not refused).
///
/// Gated `#[cfg(unix)]` because on non-unix pid_is_alive always returns false,
/// which means liveness is never enforced — but that means the dead-pid path
/// should also work correctly there (no lock; proceed to recovery).
#[test]
#[cfg(unix)]
fn open_with_dead_pid_enters_recovery() {
    let td = tempfile::tempdir().unwrap();
    let file_path = td.path().join("dead_pid_file.txt");
    std::fs::write(&file_path, "on disk\n").unwrap();

    let canonical = std::fs::canonicalize(&file_path).unwrap();
    let file_mtime_ms = std::fs::metadata(&file_path)
        .unwrap()
        .modified()
        .unwrap()
        .duration_since(std::time::SystemTime::UNIX_EPOCH)
        .unwrap()
        .as_millis() as u64;

    let swap_path = td.path().join("dead_pid_file.swp");
    // Use a very high pid that is almost certainly not a live process.
    let header = hjkl_app::swap::SwapHeader {
        magic: hjkl_app::swap::SwapHeader::MAGIC,
        version: hjkl_app::swap::SwapHeader::VERSION,
        canonical_path: canonical.to_string_lossy().into_owned(),
        file_mtime_unix_ms: file_mtime_ms,
        write_time_unix_ms: file_mtime_ms + 10_000,
        cursor: (0, 0),
        writer_pid: 999_999_999, // almost certainly dead
    };
    let rope = ropey::Rope::from_str("recovered from dead pid");
    hjkl_app::swap::write_swap(&swap_path, &header, &rope).unwrap();

    let mut app = App::new(Some(file_path.clone()), false, None, None).unwrap();
    app.pending_recovery = None;
    app.active_mut().swap_path = Some(swap_path.clone());
    let idx = app.focused_slot_idx();
    let recovery = app.check_recovery_on_open(idx);

    assert!(
        recovery,
        "stale (dead-pid) swap must enter recovery state, not be refused"
    );
    assert!(
        app.pending_recovery.is_some(),
        "pending_recovery must be set for a dead-pid swap"
    );
    // Must NOT have an E325 error.
    let msgs: Vec<&str> = app.bus.history().map(|h| h.body.as_str()).collect();
    assert!(
        !msgs.iter().any(|m| m.contains("E325")),
        "E325 must NOT fire for a dead-pid swap; got: {msgs:?}"
    );
}

/// `:recover` with no arg forces the recovery prompt even when the swap's
/// write_time is OLDER than the file on disk (which would normally cause the
/// swap to be deleted as stale).
#[test]
fn colon_recover_forces_prompt_even_when_file_newer() {
    let td = tempfile::tempdir().unwrap();
    let file_path = td.path().join("force_recover.txt");
    std::fs::write(&file_path, "on disk content\n").unwrap();

    let canonical = std::fs::canonicalize(&file_path).unwrap();
    let file_mtime_ms = std::fs::metadata(&file_path)
        .unwrap()
        .modified()
        .unwrap()
        .duration_since(std::time::SystemTime::UNIX_EPOCH)
        .unwrap()
        .as_millis() as u64;

    let swap_path = td.path().join("force_recover.swp");
    // write_time OLDER than file mtime → normally stale-deleted; :recover must override.
    let header = hjkl_app::swap::SwapHeader {
        magic: hjkl_app::swap::SwapHeader::MAGIC,
        version: hjkl_app::swap::SwapHeader::VERSION,
        canonical_path: canonical.to_string_lossy().into_owned(),
        file_mtime_unix_ms: file_mtime_ms,
        write_time_unix_ms: file_mtime_ms.saturating_sub(5_000), // 5s BEFORE file mtime
        cursor: (0, 0),
        writer_pid: std::process::id(), // our own pid → not a lock
    };
    let rope = ropey::Rope::from_str("stale swap body");
    hjkl_app::swap::write_swap(&swap_path, &header, &rope).unwrap();

    let mut app = App::new(Some(file_path.clone()), false, None, None).unwrap();
    app.pending_recovery = None;
    app.active_mut().swap_path = Some(swap_path.clone());

    // :recover (no arg) → must force recovery even though swap is "stale".
    app.dispatch_ex("recover");

    assert!(
        app.pending_recovery.is_some(),
        ":recover must enter recovery state even when swap is older than file"
    );
}

/// `:recover` with no arg when no swap file exists reports a "not found" info
/// message and does NOT enter recovery state.
#[test]
fn colon_recover_no_swap_reports_not_found() {
    let td = tempfile::tempdir().unwrap();
    let file_path = td.path().join("no_swap.txt");
    std::fs::write(&file_path, "some content\n").unwrap();

    let mut app = App::new(Some(file_path.clone()), false, None, None).unwrap();
    app.pending_recovery = None;

    // Point swap_path at a non-existent file.
    let nonexistent_swap = td.path().join("no_swap.swp");
    app.active_mut().swap_path = Some(nonexistent_swap);

    app.dispatch_ex("recover");

    assert!(
        app.pending_recovery.is_none(),
        ":recover with no swap must not enter recovery state"
    );
    let msgs: Vec<&str> = app.bus.history().map(|h| h.body.as_str()).collect();
    assert!(
        msgs.iter().any(|m| m.contains("No swap file found")),
        "must report 'No swap file found'; got: {msgs:?}"
    );
}

// ── Write-on-open / graceful-exit swap tests (#185 multi-instance) ─────────────

/// Opening a named file must write the swap immediately (arm the PID lock) so
/// that a concurrent second instance opening the same unmodified file finds a
/// swap and is refused.
///
/// Verifies via `arm_swap_on_open` called directly against an injected
/// swap_path in a tempdir (avoids XDG env mutation, which is unsafe in the
/// multi-threaded test harness).
#[test]
fn open_writes_swap_immediately() {
    let td = tempfile::tempdir().unwrap();
    let file_path = td.path().join("arm_on_open.txt");
    std::fs::write(&file_path, "initial content\n").unwrap();

    let mut app = App::new(Some(file_path.clone()), false, None, None).unwrap();
    app.pending_recovery = None;

    // Inject a swap path in the tempdir (controlled location).
    let swap_path = td.path().join("arm_on_open.swp");
    app.active_mut().swap_path = Some(swap_path.clone());
    // Reset last_swap_dirty_gen so arm_swap_on_open actually writes.
    app.active_mut().last_swap_dirty_gen = None;

    // The swap must NOT exist yet (we just set the path, haven't written it).
    assert!(
        !swap_path.exists(),
        "swap must not exist before arm_swap_on_open"
    );

    // Arm: simulates what App::new now does after a clean open.
    let idx = app.focused_slot_idx();
    app.arm_swap_on_open(idx);

    assert!(
        swap_path.exists(),
        "swap file must exist on disk immediately after arm_swap_on_open (PID lock)"
    );
}

/// `cleanup_swaps_on_exit` must delete swap files and clear swap_path on every
/// slot. This simulates the graceful-exit path so clean sessions leave no swap.
#[test]
fn graceful_exit_removes_swap() {
    let td = tempfile::tempdir().unwrap();
    let file_path = td.path().join("cleanup_exit.txt");
    std::fs::write(&file_path, "content\n").unwrap();

    let mut app = App::new(Some(file_path.clone()), false, None, None).unwrap();
    app.pending_recovery = None;

    // Inject a swap path in the tempdir and write a real swap file.
    let swap_path = td.path().join("cleanup_exit.swp");
    app.active_mut().swap_path = Some(swap_path.clone());
    let idx = app.focused_slot_idx();
    // seed a dirty gen so write_swap_for_slot writes.
    seed_buffer(&mut app, "dirty content");
    app.write_swap_for_slot(idx);
    assert!(swap_path.exists(), "swap must exist before cleanup");

    // Simulate graceful exit.
    app.cleanup_swaps_on_exit();

    assert!(
        !swap_path.exists(),
        "swap file must be removed after cleanup_swaps_on_exit"
    );
    assert!(
        app.active().swap_path.is_none(),
        "swap_path must be None after cleanup_swaps_on_exit"
    );
}

/// The second-instance lock works end-to-end when the first instance arms the
/// swap at open. Mirrors `open_locked_file_refused_when_pid_alive` but asserts
/// the comment that write-on-open is what makes this scenario real: the swap
/// with writer_pid == our-own-pid simulates a live first instance that just
/// opened (not edited) the file.
///
/// Gated `#[cfg(unix)]` because `pid_is_alive` uses kill(2).
#[test]
#[cfg(unix)]
fn second_instance_refused_after_first_opens_unmodified() {
    let td = tempfile::tempdir().unwrap();
    let file_path = td.path().join("multi_instance.txt");
    std::fs::write(&file_path, "shared content\n").unwrap();

    let canonical = std::fs::canonicalize(&file_path).unwrap();
    let file_mtime_ms = std::fs::metadata(&file_path)
        .unwrap()
        .modified()
        .unwrap()
        .duration_since(std::time::SystemTime::UNIX_EPOCH)
        .unwrap()
        .as_millis() as u64;

    // Write a swap stamped with pid=1 (init/launchd — always alive, never our
    // pid) to simulate the first instance having armed the lock at open.
    let swap_path = td.path().join("multi_instance.swp");
    let header = hjkl_app::swap::SwapHeader {
        magic: hjkl_app::swap::SwapHeader::MAGIC,
        version: hjkl_app::swap::SwapHeader::VERSION,
        canonical_path: canonical.to_string_lossy().into_owned(),
        file_mtime_unix_ms: file_mtime_ms,
        write_time_unix_ms: file_mtime_ms + 1, // just after open, no edits
        cursor: (0, 0),
        writer_pid: 1, // pid 1 = init/launchd, always alive, never our pid
    };
    let rope = ropey::Rope::from_str("shared content");
    hjkl_app::swap::write_swap(&swap_path, &header, &rope).unwrap();

    // Second instance opens the file and injects the pre-existing swap.
    let mut app = App::new(Some(file_path.clone()), false, None, None).unwrap();
    app.pending_recovery = None;
    app.active_mut().swap_path = Some(swap_path.clone());
    let idx = app.focused_slot_idx();
    let recovery = app.check_recovery_on_open(idx);

    // Must be refused with E325.
    assert!(
        !recovery,
        "second instance must be refused when first holds PID lock"
    );
    assert!(
        app.pending_recovery.is_none(),
        "pending_recovery must remain None on refusal"
    );
    let msgs: Vec<&str> = app.bus.history().map(|h| h.body.as_str()).collect();
    assert!(
        msgs.iter().any(|m| m.contains("E325")),
        "E325 must be reported; got: {msgs:?}"
    );
}

#[cfg(unix)]
#[test]
fn open_locked_sole_buffer_is_readonly() {
    // When the locked file is the ONLY buffer (e.g. `hjkl <file>` startup),
    // we can't drop the sole slot — so it opens READ-ONLY with its swap_path
    // cleared, so this process never clobbers the owner's swap or file.
    let td = tempfile::tempdir().unwrap();
    let file_path = td.path().join("locked_sole.txt");
    std::fs::write(&file_path, "owned by another\n").unwrap();
    let canonical = std::fs::canonicalize(&file_path).unwrap();
    let file_mtime_ms = std::fs::metadata(&file_path)
        .unwrap()
        .modified()
        .unwrap()
        .duration_since(std::time::SystemTime::UNIX_EPOCH)
        .unwrap()
        .as_millis() as u64;

    let swap_path = td.path().join("locked_sole.swp");
    let header = hjkl_app::swap::SwapHeader {
        magic: hjkl_app::swap::SwapHeader::MAGIC,
        version: hjkl_app::swap::SwapHeader::VERSION,
        canonical_path: canonical.to_string_lossy().into_owned(),
        file_mtime_unix_ms: file_mtime_ms,
        write_time_unix_ms: file_mtime_ms + 10_000,
        cursor: (0, 0),
        // pid 1 (init/launchd): always alive, never our pid → live lock.
        writer_pid: 1,
    };
    hjkl_app::swap::write_swap(&swap_path, &header, &ropey::Rope::from_str("x")).unwrap();

    let mut app = App::new(Some(file_path.clone()), false, None, None).unwrap();
    app.pending_recovery = None;
    let idx = app.focused_slot_idx();
    assert_eq!(app.slots.len(), 1, "precondition: sole buffer");
    app.active_mut().swap_path = Some(swap_path.clone());

    let recovery = app.check_recovery_on_open(idx);
    assert!(!recovery, "locked sole buffer must not enter recovery");
    assert!(
        app.active_editor().is_readonly(),
        "locked sole buffer must open read-only"
    );
    assert!(
        app.active().swap_path.is_none(),
        "read-only viewer must not own a swap path"
    );

    // The danger the read-only fallback guards against: `:w` from the locked
    // viewer must NOT overwrite the file the owning instance holds. Dirty the
    // buffer and attempt a write — it must be refused (E45 readonly) and the
    // on-disk content must be unchanged.
    seed_buffer(&mut app, "clobbered by viewer\n");
    app.dispatch_ex("write");
    let on_disk = std::fs::read_to_string(&file_path).unwrap();
    assert_eq!(
        on_disk, "owned by another\n",
        "locked read-only viewer must not be able to :w over the owner's file"
    );
    let msgs: Vec<String> = app.bus.history().map(|h| h.body.clone()).collect();
    assert!(
        msgs.iter()
            .any(|m| m.contains("E45") || m.contains("readonly")),
        "write must be refused with a readonly error; got: {msgs:?}"
    );
}

#[cfg(unix)]
#[test]
fn locked_secondary_slot_is_readonly_not_removed() {
    // `hjkl file1 file2` where file2 is locked by another live instance:
    // file2's slot must open READ-ONLY and stay present — not be removed
    // (silently dropping a file the user explicitly asked for) nor left
    // editable. Repro for the multi-file open lock-handling bug.
    let td = tempfile::tempdir().unwrap();
    let file1 = td.path().join("ms_file1.txt");
    let file2 = td.path().join("ms_file2.txt");
    std::fs::write(&file1, "first\n").unwrap();
    std::fs::write(&file2, "second owned\n").unwrap();

    let canon2 = std::fs::canonicalize(&file2).unwrap();
    let mtime2 = std::fs::metadata(&file2)
        .unwrap()
        .modified()
        .unwrap()
        .duration_since(std::time::SystemTime::UNIX_EPOCH)
        .unwrap()
        .as_millis() as u64;
    let swap2 = td.path().join("ms_file2.swp");
    let header = hjkl_app::swap::SwapHeader {
        magic: hjkl_app::swap::SwapHeader::MAGIC,
        version: hjkl_app::swap::SwapHeader::VERSION,
        canonical_path: canon2.to_string_lossy().into_owned(),
        file_mtime_unix_ms: mtime2,
        write_time_unix_ms: mtime2 + 10_000,
        cursor: (0, 0),
        writer_pid: 1, // alive, not us → live lock
    };
    hjkl_app::swap::write_swap(&swap2, &header, &ropey::Rope::from_str("x")).unwrap();

    let mut app = App::new(Some(file1.clone()), false, None, None).unwrap();
    app.pending_recovery = None;
    // Open file2 as a second slot (mirrors CLI `hjkl file1 file2`).
    let idx2 = app.open_new_slot(file2.clone()).unwrap();
    assert_eq!(app.slots.len(), 2, "precondition: two slots");
    app.slots[idx2].swap_path = Some(swap2.clone());

    let recovery = app.check_recovery_on_open(idx2);
    assert!(!recovery, "locked secondary slot must not enter recovery");
    assert_eq!(
        app.slots.len(),
        2,
        "locked secondary slot must NOT be removed — the file was requested"
    );
    assert!(
        app.slots[idx2].editor.is_readonly(),
        "locked secondary slot must open read-only"
    );
    assert!(
        app.slots[idx2].swap_path.is_none(),
        "locked read-only slot must not own a swap path"
    );
}

// ── Scratch-buffer swap tests (issue #185) ────────────────────────────────────

/// A scratch buffer with content gets a swap file written lazily.
///
/// No `XDG_CACHE_HOME` env mutation — that's a process-global var and other
/// parallel tests inherit it, racing on the swap dir. Instead we let the
/// writer pick the real swap_dir path (unique per pid+buffer_id) and clean up.
#[test]
fn scratch_buffer_writes_swap_when_dirty() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "unsaved work");

    app.write_swap_for_slot(0);

    let swap_path = app.slots[0]
        .swap_path
        .clone()
        .expect("swap_path must be Some after write for non-empty scratch");
    assert!(swap_path.exists(), "swap file must exist at {swap_path:?}");

    let (header, body) = hjkl_app::swap::read_swap(&swap_path).unwrap();
    assert!(
        header.canonical_path.is_empty(),
        "scratch swap must have empty canonical_path, got {:?}",
        header.canonical_path
    );
    assert_eq!(body, "unsaved work", "swap body must match buffer content");

    // Clean up the swap we wrote into the real swap dir.
    let _ = hjkl_app::swap::remove_swap(&swap_path);
}

/// An empty scratch buffer produces no swap file. `swap_path` staying `None`
/// is the proof — `write_swap_for_slot` returns before choosing a path when
/// the buffer is empty, so nothing is written (no env / filesystem scan
/// needed, hence no cross-test races).
#[test]
fn empty_scratch_buffer_writes_no_swap() {
    let mut app = App::new(None, false, None, None).unwrap();
    // Buffer is empty by default — do not seed any content.

    app.write_swap_for_slot(0);

    assert!(
        app.slots[0].swap_path.is_none(),
        "empty scratch buffer must not get a swap_path (so nothing was written)"
    );
}

/// A dead-pid orphan scratch swap is loaded into a recovered unnamed buffer.
#[test]
fn recover_orphan_scratch_loads_buffer() {
    let td = tempfile::tempdir().unwrap();

    // Write a scratch swap with a dead pid into the tempdir.
    let orphan_path = td.path().join("scratch_999999999_42.swp");
    let header = hjkl_app::swap::SwapHeader {
        magic: hjkl_app::swap::SwapHeader::MAGIC,
        version: hjkl_app::swap::SwapHeader::VERSION,
        canonical_path: String::new(),
        file_mtime_unix_ms: 0,
        write_time_unix_ms: 1_700_000_000_000,
        cursor: (0, 0),
        writer_pid: 999_999_999,
    };
    let rope = ropey::Rope::from_str("unsaved work\n");
    hjkl_app::swap::write_swap(&orphan_path, &header, &rope).unwrap();

    let mut app = App::new(None, false, None, None).unwrap();
    let initial_slot_count = app.slots.len();

    // Use dir-injected variant — no XDG mutation needed.
    let recovered = app.recover_orphan_scratch_buffers_from(td.path());

    assert_eq!(recovered, 1, "must recover exactly 1 buffer");
    assert_eq!(
        app.slots.len(),
        initial_slot_count + 1,
        "a new slot must have been added"
    );

    let new_slot = &app.slots[app.slots.len() - 1];
    assert!(
        new_slot.filename.is_none(),
        "recovered slot must be unnamed"
    );
    assert!(new_slot.dirty, "recovered slot must be dirty");

    // Check content contains the recovered text.
    let content = new_slot.editor.buffer().rope().to_string();
    assert!(
        content.contains("unsaved work"),
        "recovered buffer content must contain 'unsaved work', got {content:?}"
    );

    // Orphan swap must be deleted.
    assert!(
        !orphan_path.exists(),
        "orphan swap must be deleted after recovery"
    );
}

#[test]
fn active_swap_pending_true_for_dirty_scratch_buffer() {
    // Regression: scratch slots start with swap_path = None, so the idle
    // writer's active_swap_pending() gate must still fire for a non-empty
    // unnamed buffer — otherwise the scratch swap is never written at runtime.
    let mut app = App::new(None, false, None, None).unwrap();
    assert!(
        app.active().filename.is_none(),
        "precondition: scratch buffer"
    );
    assert!(
        !app.active_swap_pending(),
        "empty scratch buffer has nothing to protect yet"
    );
    seed_buffer(&mut app, "unsaved scratch work\n");
    assert!(
        app.active_swap_pending(),
        "dirty non-empty scratch buffer must arm the idle swap writer"
    );
}

// ── :colorscheme (#35) ───────────────────────────────────────────────────────

#[test]
fn colorscheme_switches_and_reports() {
    let mut app = App::new(None, false, None, None).unwrap();
    assert_eq!(app.colorscheme, "dark", "default colorscheme is dark");

    app.dispatch_ex("colorscheme light");
    assert_eq!(app.colorscheme, "light");
    assert!(
        app.bus.last_body_or_empty().contains("colorscheme light"),
        "switch must report the new scheme"
    );

    // Bare query reports current.
    app.dispatch_ex("colorscheme");
    assert!(app.bus.last_body_or_empty().contains("colorscheme light"));

    // `:colo` abbreviation switches back.
    app.dispatch_ex("colo dark");
    assert_eq!(app.colorscheme, "dark");
}

#[test]
fn colorscheme_unknown_errors_and_keeps_current() {
    let mut app = App::new(None, false, None, None).unwrap();
    app.dispatch_ex("colorscheme solarized");
    assert_eq!(
        app.colorscheme, "dark",
        "unknown scheme must not change current"
    );
    assert!(
        app.bus.last_body_or_empty().contains("E185"),
        "unknown colorscheme must report E185"
    );
}

#[test]
fn set_background_tracks_colorscheme() {
    let mut app = App::new(None, false, None, None).unwrap();
    app.dispatch_ex("set background=light");
    assert_eq!(
        app.colorscheme, "light",
        ":set background= must track colorscheme"
    );
}

/// App-level indentation surface coverage, driven through the real keypress
/// path (`macro_key_seq`). Expected outputs match `nvim --headless` with
/// `expandtab` / `shiftwidth=4`. Covers operator+motion, text objects, dot
/// repeat, visual-mode counts (the regression this suite was added for), and
/// insert-mode `Ctrl-T` / `Ctrl-D`.
fn indent_app(seed: &str, keys: &[KeyEvent]) -> String {
    let mut app = App::new(None, false, None, None).unwrap();
    app.active_editor_mut().settings_mut().expandtab = true;
    app.active_editor_mut().settings_mut().shiftwidth = 4;
    seed_buffer(&mut app, seed);
    app.active_editor_mut().jump_cursor(0, 0);
    macro_key_seq(&mut app, keys);
    (*app.active_editor().buffer().content_joined()).clone()
}

#[test]
fn indent_operator_motion_forms() {
    assert_eq!(
        indent_app("a\nb\nc\n", &[ck('>'), ck('j')]),
        "    a\n    b\nc\n"
    );
    assert_eq!(
        indent_app("a\nb\nc\n", &[ck('>'), ck('G')]),
        "    a\n    b\n    c\n"
    );
    // count between op and motion, and before op — both indent 3 lines.
    assert_eq!(
        indent_app("a\nb\nc\nd\n", &[ck('>'), ck('2'), ck('j')]),
        "    a\n    b\n    c\nd\n"
    );
    assert_eq!(
        indent_app("a\nb\nc\nd\n", &[ck('2'), ck('>'), ck('j')]),
        "    a\n    b\n    c\nd\n"
    );
}

#[test]
fn indent_text_objects() {
    // `>ip` indents the paragraph (up to the blank line).
    assert_eq!(
        indent_app("a\nb\n\nc\n", &[ck('>'), ck('i'), ck('p')]),
        "    a\n    b\n\nc\n"
    );
    // `>iB` indents inside the surrounding `{ }` block.
    assert_eq!(
        indent_app("{\nx\ny\n}\n", &[ck('j'), ck('>'), ck('i'), ck('B')]),
        "{\n    x\n    y\n}\n"
    );
}

#[test]
fn indent_dot_repeat() {
    // `>>` then `j.` repeats the indent on the next line.
    assert_eq!(
        indent_app("a\nb\nc\n", &[ck('>'), ck('>'), ck('j'), ck('.')]),
        "    a\n    b\nc\n"
    );
}

#[test]
fn visual_indent_count_applies_levels() {
    // `Vj2>` indents the two selected lines by TWO shiftwidths (8 spaces).
    assert_eq!(
        indent_app("a\nb\nc\n", &[ck('V'), ck('j'), ck('2'), ck('>')]),
        "        a\n        b\nc\n"
    );
    // `Vj2<` outdents the two selected lines by TWO shiftwidths (8 → 0).
    assert_eq!(
        indent_app(
            "        a\n        b\n        c\n",
            &[ck('V'), ck('j'), ck('2'), ck('<')]
        ),
        "a\nb\n        c\n"
    );
    // `V3>` indents the single selected line by THREE shiftwidths (12 spaces).
    assert_eq!(
        indent_app("a\nb\nc\n", &[ck('V'), ck('3'), ck('>')]),
        "            a\nb\nc\n"
    );
}

#[test]
fn visual_motion_count_extends_selection() {
    // `V2j>` — the count on the motion extends the selection 2 lines down, so
    // three lines are indented once.
    assert_eq!(
        indent_app("a\nb\nc\nd\ne\n", &[ck('V'), ck('2'), ck('j'), ck('>')]),
        "    a\n    b\n    c\nd\ne\n"
    );
}

#[test]
fn insert_ctrl_t_and_ctrl_d() {
    // `i` then Ctrl-T indents the current line by one shiftwidth.
    assert_eq!(indent_app("abc\n", &[ck('i'), ctrl_key('t')]), "    abc\n");
    // Ctrl-D outdents it back.
    assert_eq!(
        indent_app("abc\n", &[ck('i'), ctrl_key('t'), ctrl_key('d')]),
        "abc\n"
    );
}

/// Reproduce `==` through the REAL keypress path (handle_keypress →
/// route_chord_key → chord_routing → submit_external_format), not a direct
/// call. Skipped where taplo isn't on PATH.
#[test]
fn double_equals_keypress_formats_toml() {
    if !hjkl_mangler::is_tool_installed("taplo") {
        return;
    }
    let td = tempfile::tempdir().unwrap();
    let path = td.path().join("k.toml");
    std::fs::write(&path, "[a]\nx=1\n").unwrap();
    let mut app = App::new(Some(path), false, None, None).unwrap();
    seed_buffer(&mut app, "[a]\nx=1\n");
    app.active_editor_mut().jump_cursor(0, 0);

    // Press `==` exactly as the live loop would.
    macro_key_seq(&mut app, &[ck('='), ck('=')]);

    let mut installed = false;
    for _ in 0..200 {
        if app.poll_format_results() {
            installed = true;
            break;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    assert!(
        installed,
        "`==` keypress must submit a format job whose result installs"
    );
    let out = app.active_editor().buffer().content_joined();
    assert!(
        out.contains("x = 1"),
        "`==` must reformat `x=1` → `x = 1`, got: {out:?}"
    );
}

/// End-to-end `==`/`=` external-format path: `submit_external_format` (what the
/// `=` operator calls) must dispatch the async worker, and `poll_format_results`
/// must install taplo's reformatted output into the buffer. Skipped where taplo
/// isn't on PATH (CI) so it never flakes there.
#[test]
fn external_format_toml_installs_worker_result() {
    if !hjkl_mangler::is_tool_installed("taplo") {
        return; // taplo not available — nothing to exercise
    }
    let td = tempfile::tempdir().unwrap();
    let path = td.path().join("messy.toml");
    std::fs::write(&path, "[a]\nx=1\n").unwrap();
    let mut app = App::new(Some(path), false, None, None).unwrap();
    seed_buffer(&mut app, "[a]\nx=1\n");

    let submitted = app.submit_external_format(Some(hjkl_mangler::RangeSpec {
        start_row: 0,
        end_row: 1,
    }));
    assert!(
        submitted,
        "taplo is installed → submit_external_format must dispatch a job"
    );

    let mut installed = false;
    for _ in 0..200 {
        if app.poll_format_results() {
            installed = true;
            break;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    assert!(installed, "the async format result must install within ~4s");

    let out = app.active_editor().buffer().content_joined();
    assert!(
        out.contains("x = 1"),
        "taplo must reformat `x=1` → `x = 1`, got: {out:?}"
    );
}

// ── trailing-newline (EOL) model: vim-consistent ─────────────────────────────
//
// vim's line model excludes the file-final newline: a file `a\nb\nc\n` is 3
// lines, not 4. hjkl strips one trailing `\n` on load and re-adds it on save
// (matching vim's `fixendofline`), so the buffer never shows a phantom empty
// last line. Formatter output (prettier appends `\n`) is normalised the same
// way at the install site.

#[test]
fn trailing_newline_file_loads_without_phantom_line() {
    use hjkl_engine::Query;
    let td = tempfile::tempdir().unwrap();
    let path = td.path().join("eol.txt");
    std::fs::write(&path, "a\nb\nc\n").unwrap();
    let app = App::new(Some(path), false, None, None).unwrap();
    assert_eq!(
        app.active_editor().buffer().line_count(),
        3,
        "a file ending in `\\n` must load as 3 lines, not 4 (no phantom empty line)"
    );
}

#[test]
fn save_round_trips_trailing_newline_exactly_once() {
    let td = tempfile::tempdir().unwrap();
    let path = td.path().join("eol_rt.txt");
    std::fs::write(&path, "a\nb\nc\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();
    app.active_mut().dirty = true; // force the write
    app.dispatch_ex("w");
    let on_disk = std::fs::read_to_string(&path).unwrap();
    assert_eq!(
        on_disk, "a\nb\nc\n",
        "save must preserve exactly one trailing newline, not drop or double it"
    );
}

#[test]
fn save_adds_trailing_newline_when_missing() {
    use hjkl_engine::Query;
    let td = tempfile::tempdir().unwrap();
    let path = td.path().join("noeol.txt");
    std::fs::write(&path, "a\nb\nc").unwrap(); // no trailing newline
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();
    // Still 3 lines (load strips nothing here — there's no trailing newline).
    assert_eq!(app.active_editor().buffer().line_count(), 3);
    app.active_mut().dirty = true;
    app.dispatch_ex("w");
    let on_disk = std::fs::read_to_string(&path).unwrap();
    assert_eq!(
        on_disk, "a\nb\nc\n",
        "save must add a trailing newline when missing (vim `fixendofline`)"
    );
}

// ── sed-style ex commands: vim-compat (range + %/# literal-in-body) ───────────
//
// These run through the full `dispatch_ex` path WITH A CURRENT FILE so the
// command-line `%`/`#` filename expansion is live. The bug class: the leading
// range `%` (`:%s/…`) and any `%`/`#` inside a substitute/global body were
// being rewritten to the current filename, breaking the command. Vim expands
// `%`/`#` only in file-argument/shell commands — never the range, never the
// substitute/global body.

/// Open an app on a temp file seeded with `content`; returns (app, tempdir).
/// The tempdir must outlive the app (kept by the caller).
fn app_with_file(content: &str) -> (App, tempfile::TempDir) {
    let td = tempfile::tempdir().unwrap();
    let path = td.path().join("sed_compat.txt");
    std::fs::write(&path, content).unwrap();
    let mut app = App::new(Some(path), false, None, None).unwrap();
    seed_buffer(&mut app, content);
    (app, td)
}

#[test]
fn percent_substitute_replaces_all_lines() {
    // The reported bug: `:%s/foo/bar/g` did nothing because the leading `%`
    // range was expanded to the current filename before dispatch.
    let (mut app, _td) = app_with_file("foo foo\nbar\nfoo\n");
    app.dispatch_ex("%s/foo/bar/g");
    let content = app.active_editor().buffer().content_joined();
    assert_eq!(
        &**content, "bar bar\nbar\nbar\n",
        "`:%s/foo/bar/g` must replace every match on every line, got: {content:?}"
    );
}

#[test]
fn substitute_literal_percent_in_pattern() {
    // `%` inside the substitute pattern is a literal char, NOT the current-file
    // token — vim never expands `%`/`#` in a substitute body.
    let (mut app, _td) = app_with_file("50% done\n");
    // Cursor is on line 0; no range → current line.
    app.dispatch_ex("s/50%/half/");
    let content = app.active_editor().buffer().content_joined();
    assert_eq!(
        &**content, "half done\n",
        "`%` in the substitute pattern must stay literal, got: {content:?}"
    );
}

#[test]
fn substitute_literal_hash_in_replacement() {
    // `#` (alternate-file token) must also stay literal in a substitute body.
    let (mut app, _td) = app_with_file("count: N\n");
    app.dispatch_ex(r"s/N/#42/");
    let content = app.active_editor().buffer().content_joined();
    assert_eq!(
        &**content, "count: #42\n",
        "`#` in the replacement must stay literal, got: {content:?}"
    );
}

#[test]
fn percent_global_delete_matching_lines() {
    // `:%g/pat/d` — range `%` + global; the leading `%` must not expand.
    let (mut app, _td) = app_with_file("keep\ndrop me\nkeep2\ndrop again\n");
    app.dispatch_ex("%g/drop/d");
    let content = app.active_editor().buffer().content_joined();
    assert_eq!(
        &**content, "keep\nkeep2\n",
        "`:%g/drop/d` must delete every matching line, got: {content:?}"
    );
}

#[test]
fn numeric_range_substitute_still_works() {
    // Control: a numeric range (no `%`) was never affected; guard it stays so.
    let (mut app, _td) = app_with_file("a\nx\nx\nx\nb\n");
    app.dispatch_ex("2,3s/x/y/");
    let content = app.active_editor().buffer().content_joined();
    assert_eq!(
        &**content, "a\ny\ny\nx\nb\n",
        "`:2,3s/x/y/` must touch only lines 2-3, got: {content:?}"
    );
}

#[test]
fn edit_percent_still_expands_to_filename() {
    // Guard the OTHER side: `%` as a FILE ARGUMENT (`:e %`) must still expand —
    // the fix must not over-suppress expansion for file commands.
    let (mut app, _td) = app_with_file("hello\n");
    // `:e %` reloads the current file; it must not error with an unexpanded
    // `%` path. Dirty the buffer first so the reload is observable, then
    // force-edit to discard.
    seed_buffer(&mut app, "changed\n");
    app.active_mut().dirty = true;
    app.dispatch_ex("e! %");
    let content = app.active_editor().buffer().content_joined();
    assert_eq!(
        content.trim_end(),
        "hello",
        "`:e! %` must expand `%` to the current file and reload it, got: {content:?}"
    );
    assert!(
        !content.contains("changed"),
        "reload must replace the dirty buffer, got: {content:?}"
    );
}

// ── :DiffOrig (#208) ──────────────────────────────────────────────────────

#[test]
fn diff_orig_opens_readonly_diff_split_with_hunks() {
    let path = std::env::temp_dir().join("hjkl_diff_orig_hunks.txt");
    std::fs::write(&path, "alpha\nbeta\ngamma\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();
    let original_win = app.focused_window();

    // Edit the buffer in memory only (do not save).
    seed_buffer(&mut app, "alpha\nBETA\ngamma\n");
    app.active_mut().dirty = true;

    app.dispatch_ex("DiffOrig");

    // A new split opened and is focused.
    assert_eq!(
        app.windows.iter().filter(|w| w.is_some()).count(),
        2,
        "expected 2 open windows after :DiffOrig"
    );
    let new_win = app.focused_window();
    assert_ne!(new_win, original_win, ":DiffOrig must focus the new split");

    let new_slot = app.windows[new_win].as_ref().unwrap().slot;
    let slot = &app.slots[new_slot];
    assert!(
        slot.filename.is_none(),
        "diff buffer must be an unnamed scratch slot"
    );
    assert_eq!(
        slot.editor.settings().filetype,
        "diff",
        "diff buffer filetype must be `diff`"
    );
    assert!(
        !slot.editor.is_modifiable(),
        "diff buffer must be read-only"
    );

    let content = slot.editor.buffer().rope().to_string();
    assert!(
        content.contains("@@"),
        "diff must contain a hunk header: {content}"
    );
    assert!(
        content.contains("-beta"),
        "diff must show removed line: {content}"
    );
    assert!(
        content.contains("+BETA"),
        "diff must show added line: {content}"
    );

    let _ = std::fs::remove_file(&path);
}

#[test]
fn diff_orig_no_changes_shows_no_difference_message() {
    let path = std::env::temp_dir().join("hjkl_diff_orig_clean.txt");
    std::fs::write(&path, "same\ncontent\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();

    // Buffer matches disk exactly.
    app.dispatch_ex("DiffOrig");

    let new_win = app.focused_window();
    let new_slot = app.windows[new_win].as_ref().unwrap().slot;
    let content = app.slots[new_slot].editor.buffer().rope().to_string();
    assert!(
        content.contains("no differences"),
        "clean buffer must report no differences: {content}"
    );
    assert!(
        !content.contains("@@"),
        "clean buffer must not produce a hunk: {content}"
    );

    let _ = std::fs::remove_file(&path);
}

#[test]
fn diff_orig_without_filename_errors_and_opens_no_split() {
    let mut app = App::new(None, false, None, None).unwrap();
    let before = app.windows.iter().filter(|w| w.is_some()).count();

    app.dispatch_ex("DiffOrig");

    let msg = app.bus.last_body_or_empty().to_string();
    assert!(msg.contains("E32"), "expected E32 no-file-name, got: {msg}");
    assert_eq!(
        app.windows.iter().filter(|w| w.is_some()).count(),
        before,
        ":DiffOrig on an unnamed buffer must not open a split"
    );
}

#[test]
fn diff_orig_file_deleted_on_disk_shows_all_additions() {
    let path = std::env::temp_dir().join("hjkl_diff_orig_deleted.txt");
    std::fs::write(&path, "placeholder\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();

    // Buffer has content, but the file vanishes from disk (old side empty).
    seed_buffer(&mut app, "line one\nline two\n");
    app.active_mut().dirty = true;
    std::fs::remove_file(&path).unwrap();

    app.dispatch_ex("DiffOrig");

    let new_win = app.focused_window();
    let new_slot = app.windows[new_win].as_ref().unwrap().slot;
    let content = app.slots[new_slot].editor.buffer().rope().to_string();
    assert!(
        content.contains("+line one"),
        "expected added line: {content}"
    );
    assert!(
        content.contains("+line two"),
        "expected added line: {content}"
    );
    assert!(
        !content.contains("no differences"),
        "deleted-on-disk buffer must produce a real diff: {content}"
    );
}

#[test]
fn diff_orig_leaves_original_buffer_untouched() {
    let path = std::env::temp_dir().join("hjkl_diff_orig_untouched.txt");
    std::fs::write(&path, "disk\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();
    let original_win = app.focused_window();
    let original_slot = app.windows[original_win].as_ref().unwrap().slot;

    seed_buffer(&mut app, "edited\n");
    app.active_mut().dirty = true;

    app.dispatch_ex("DiffOrig");

    // The source buffer keeps its (still-unsaved) content and stays modifiable.
    let src = &app.slots[original_slot];
    assert_eq!(
        src.editor.buffer().rope().to_string(),
        "edited\n",
        "source buffer content must be unchanged by :DiffOrig"
    );
    assert!(
        src.editor.is_modifiable(),
        "source buffer must remain modifiable"
    );
    assert_eq!(
        src.filename.as_deref(),
        Some(path.as_path()),
        "source buffer must keep its filename"
    );

    let _ = std::fs::remove_file(&path);
}

// ── Dirty-buffer disk-change prompt (#241) ────────────────────────────────

/// Set up a focused, dirty buffer whose file then changes on disk, and drive
/// the fs-watch path so the keep/reload/diff prompt is raised. Returns the app
/// and the file path (caller removes it).
fn raise_disk_change_prompt(tag: &str) -> (App, std::path::PathBuf) {
    let path = std::env::temp_dir().join(format!("hjkl_dc_{tag}.txt"));
    std::fs::write(&path, "disk one\n").unwrap();
    let mut app = App::new(Some(path.clone()), false, None, None).unwrap();
    seed_buffer(&mut app, "buffer edit\n");
    app.active_mut().dirty = true;

    write_and_wait(&path, "disk changed\n");
    let repaint = app.apply_fs_events(vec![hjkl_fs_watch::FsEvent::Modified(path.clone())]);
    assert!(repaint, "raising the prompt must request a repaint");
    assert!(
        app.pending_disk_change.is_some(),
        "dirty focused buffer must raise the disk-change prompt"
    );
    (app, path)
}

#[test]
fn disk_change_prompt_raised_and_buffer_intact() {
    let (app, path) = raise_disk_change_prompt("raise");
    // Buffer content untouched while the prompt is up.
    assert_eq!(
        app.active_editor().buffer().rope().to_string(),
        "buffer edit\n"
    );
    let _ = std::fs::remove_file(&path);
}

#[test]
fn disk_change_prompt_keep_preserves_buffer() {
    let (mut app, path) = raise_disk_change_prompt("keep");
    app.handle_disk_change_key(key(KeyCode::Char('k')));

    assert!(
        app.pending_disk_change.is_none(),
        "keep dismisses the prompt"
    );
    let content = app.active_editor().buffer().rope().to_string();
    assert!(
        content.contains("buffer edit"),
        "keep must preserve buffer: {content}"
    );
    // Still flagged changed so the :w guard stays armed.
    assert_eq!(app.active().disk_state, DiskState::ChangedOnDisk);
    let _ = std::fs::remove_file(&path);
}

#[test]
fn disk_change_prompt_reload_discards_changes() {
    let (mut app, path) = raise_disk_change_prompt("reload");
    app.handle_disk_change_key(key(KeyCode::Char('r')));

    assert!(
        app.pending_disk_change.is_none(),
        "reload dismisses the prompt"
    );
    let content = app.active_editor().buffer().rope().to_string();
    assert!(
        content.contains("disk changed"),
        "reload must load disk content: {content}"
    );
    assert!(
        !content.contains("buffer edit"),
        "reload must discard buffer edits: {content}"
    );
    assert!(!app.active().dirty, "reloaded buffer must be clean");
    assert_eq!(app.active().disk_state, DiskState::Synced);
    let _ = std::fs::remove_file(&path);
}

#[test]
fn disk_change_prompt_diff_opens_readonly_split() {
    let (mut app, path) = raise_disk_change_prompt("diff");
    let before = app.windows.iter().filter(|w| w.is_some()).count();
    app.handle_disk_change_key(key(KeyCode::Char('d')));

    assert!(
        app.pending_disk_change.is_none(),
        "diff dismisses the prompt"
    );
    assert_eq!(
        app.windows.iter().filter(|w| w.is_some()).count(),
        before + 1,
        "diff must open a new split"
    );
    let win = app.focused_window();
    let slot = app.windows[win].as_ref().unwrap().slot;
    assert_eq!(app.slots[slot].editor.settings().filetype, "diff");
    assert!(!app.slots[slot].editor.is_modifiable());
    let _ = std::fs::remove_file(&path);
}

#[test]
fn disk_change_prompt_esc_keeps_buffer() {
    let (mut app, path) = raise_disk_change_prompt("esc");
    app.handle_disk_change_key(key(KeyCode::Esc));
    assert!(
        app.pending_disk_change.is_none(),
        "Esc dismisses the prompt"
    );
    assert!(
        app.active_editor()
            .buffer()
            .rope()
            .to_string()
            .contains("buffer edit"),
        "Esc must keep the buffer"
    );
    let _ = std::fs::remove_file(&path);
}

#[test]
fn disk_change_no_prompt_for_background_dirty_slot() {
    // Two files: `a` is edited+dirty, then we focus `b`. A disk change to the
    // background `a` must only warn (no interactive prompt — you can't answer
    // it for an unfocused buffer).
    let a = std::env::temp_dir().join("hjkl_dc_bg_a.txt");
    let b = std::env::temp_dir().join("hjkl_dc_bg_b.txt");
    std::fs::write(&a, "a one\n").unwrap();
    std::fs::write(&b, "b one\n").unwrap();
    let mut app = App::new(Some(a.clone()), false, None, None).unwrap();
    seed_buffer(&mut app, "a edited\n");
    app.active_mut().dirty = true;
    // Open + focus b.
    app.dispatch_ex(&format!("e {}", b.display()));
    assert_ne!(
        app.active().filename.as_deref(),
        Some(a.as_path()),
        "b must be focused"
    );

    write_and_wait(&a, "a changed\n");
    app.apply_fs_events(vec![hjkl_fs_watch::FsEvent::Modified(a.clone())]);

    assert!(
        app.pending_disk_change.is_none(),
        "a background dirty slot must not raise the interactive prompt"
    );
    let _ = std::fs::remove_file(&a);
    let _ = std::fs::remove_file(&b);
}