croft-software 0.2.182

VSCode-style TUI written in Rust
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
//! Editing a buffer: typing, the caret, selections, the clipboard, undo and
//! line operations.

use super::*;

/// #1161: on an `.xml` file both comment commands from the palette comment
/// the caret's line instead of saying the language has none.
#[test]
fn the_comment_commands_comment_an_xml_file() {
    use crate::widgets::command_palette::Command as Cmd;
    let tmp = tempfile::tempdir().unwrap();
    for name in ["doc.xml", "schema.xsd", "Info.plist"] {
        let f = tmp.path().join(name);
        std::fs::write(&f, "<root>\n  <item id=\"1\">hello</item>\n</root>\n").unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.editor.open_pinned(&f).unwrap();
        app.editor.cursor_row = 1;
        for cmd in [Cmd::ToggleBlockComment, Cmd::ToggleLineComment] {
            app.run_command(cmd);
            assert_eq!(
                app.editor.lines[1], "  <!-- <item id=\"1\">hello</item> -->",
                "{name} {cmd:?}"
            );
            assert!(!app.status.contains("no "), "{name}: {}", app.status);
            app.editor.cursor_row = 1;
            app.run_command(cmd);
            assert_eq!(
                app.editor.lines[1], "  <item id=\"1\">hello</item>",
                "{name}"
            );
            app.editor.cursor_row = 1;
        }
    }
    // Negative: a file with no comment at all says so.
    let f = tmp.path().join("data.unknownext");
    std::fs::write(&f, "{}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    app.run_command(Cmd::ToggleLineComment);
    assert_eq!(app.editor.lines[0], "{}");
    assert!(app.status.contains("no comment"), "{}", app.status);
}

#[test]
fn ctrl_c_is_editor_copy_key() {
    assert!(is_editor_copy_key(key(
        KeyCode::Char('c'),
        KeyModifiers::CONTROL
    )));
}

#[test]
fn cmd_c_is_editor_copy_key() {
    assert!(is_editor_copy_key(key(
        KeyCode::Char('c'),
        KeyModifiers::SUPER
    )));
}

#[test]
fn plain_c_is_not_editor_copy_key() {
    assert!(!is_editor_copy_key(key(
        KeyCode::Char('c'),
        KeyModifiers::NONE
    )));
}

#[test]
fn ctrl_x_is_editor_cut_key() {
    assert!(is_editor_cut_key(key(
        KeyCode::Char('x'),
        KeyModifiers::CONTROL
    )));
    assert!(is_editor_cut_key(key(
        KeyCode::Char('x'),
        KeyModifiers::SUPER
    )));
    assert!(!is_editor_cut_key(key(
        KeyCode::Char('x'),
        KeyModifiers::NONE
    )));
}

#[test]
fn ctrl_a_is_editor_select_all_key() {
    assert!(is_editor_select_all_key(key(
        KeyCode::Char('a'),
        KeyModifiers::CONTROL
    )));
    assert!(is_editor_select_all_key(key(
        KeyCode::Char('a'),
        KeyModifiers::SUPER
    )));
    assert!(!is_editor_select_all_key(key(
        KeyCode::Char('a'),
        KeyModifiers::NONE
    )));
}

#[test]
fn ctrl_z_is_editor_undo_key() {
    assert!(is_editor_undo_key(key(
        KeyCode::Char('z'),
        KeyModifiers::CONTROL
    )));
    assert!(is_editor_undo_key(key(
        KeyCode::Char('z'),
        KeyModifiers::SUPER
    )));
}

#[test]
fn plain_z_is_not_editor_undo_key() {
    assert!(!is_editor_undo_key(key(
        KeyCode::Char('z'),
        KeyModifiers::NONE
    )));
}

#[test]
fn shift_cmd_z_reserved_for_redo_not_undo() {
    let mods = KeyModifiers::SUPER | KeyModifiers::SHIFT;
    assert!(!is_editor_undo_key(key(KeyCode::Char('z'), mods)));
    // The shifted chord is redo (both Cmd and Ctrl surfaces), and the plain
    // command-modifier Z stays undo, not redo.
    assert!(is_editor_redo_key(key(KeyCode::Char('z'), mods)));
    assert!(is_editor_redo_key(key(
        KeyCode::Char('z'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT
    )));
    assert!(!is_editor_redo_key(key(
        KeyCode::Char('z'),
        KeyModifiers::SUPER
    )));
    assert!(!is_editor_redo_key(key(
        KeyCode::Char('z'),
        KeyModifiers::CONTROL
    )));
}

/// Cmd+C from the croft terminal pane must land the selection on the
/// real macOS clipboard. This is the user-visible regression test
/// for the long-standing "I copied from croft and pbpaste shows the
/// previous value" bug, where the old OSC 52 path was silently
/// dropped by the host terminal. The contract: a copy through
/// `App::copy_where_pasted`, which every copy croft makes goes through
/// (#2070), puts the text on the system pasteboard such
/// that `clipboard::read_string` (which is what Cmd+V uses) returns
/// the same bytes. If this ever fails again, copy/paste between
/// croft and other apps is broken and the test must catch it before
/// the binary ships.
#[cfg(target_os = "macos")]
#[test]
fn a_copy_writes_text_to_the_macos_system_pasteboard() {
    let _g = crate::clipboard::lock_clipboard_for_test();
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let sentinel = format!(
        "croft-copy-helper-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0)
    );
    assert_eq!(
        app.copy_where_pasted(&sentinel),
        CopyLanding::Clipboard,
        "on macOS, a copy must land via NSPasteboard rather than fall back to OSC 52 (whose host-terminal quirks can silently drop the write)"
    );
    let got = crate::clipboard::read_string().expect("read_string must see what we just wrote");
    assert_eq!(
        got, sentinel,
        "round-trip through the system pasteboard must be byte-exact - if this ever drifts, every Cmd+C from croft is silently lossy"
    );
}

// Exercises the macOS-native NSPasteboard backend (`clipboard::macos`), which
// only exists on macOS — gate it like the sibling native tests in
// `clipboard.rs` so the Linux/Android test binaries still compile and run
// everything else (an ungated macOS-only test fails to *compile* off-macOS,
// poisoning the whole test target rather than just skipping).
#[cfg(target_os = "macos")]
#[test]
fn lock_clipboard_for_test_restores_prior_clipboard_text_on_drop() {
    // Tests that hit the real NSPasteboard must never leave their
    // sentinels behind. This test simulates a user already having
    // text on the clipboard, runs a guarded section that writes a
    // sentinel, drops the guard, and asserts the clipboard now
    // reads back the simulated "user" text rather than the test
    // sentinel.
    //
    // To avoid leaking the simulated text into the developer's real
    // clipboard, capture the genuine pre-test contents first and
    // restore them at the very end via a Drop guard so even a panic
    // in the middle leaves the host clipboard untouched.
    struct RestoreClip(Option<String>);
    impl Drop for RestoreClip {
        fn drop(&mut self) {
            match self.0.take() {
                Some(s) => {
                    crate::clipboard::macos::write_string_native(&s);
                }
                None => crate::clipboard::macos::clear_native(),
            }
        }
    }
    let _restore = RestoreClip(crate::clipboard::macos::read_string_native());

    let pre = format!("user-preexisting-clip-{}", std::process::id());
    crate::clipboard::macos::write_string_native(&pre);
    {
        let _g = crate::clipboard::lock_clipboard_for_test();
        let sentinel = "test-sentinel-should-not-leak";
        assert!(
            crate::clipboard::write_string(sentinel),
            "guard-held write must hit the real NSPasteboard"
        );
        assert_eq!(
            crate::clipboard::read_string().as_deref(),
            Some(sentinel),
            "while the guard is held the test reads what it just wrote"
        );
    }
    let after = crate::clipboard::macos::read_string_native();
    assert_eq!(
        after.as_deref(),
        Some(pre.as_str()),
        "dropping the guard MUST restore the pre-test clipboard so a cargo test run never leaves a test sentinel on the developer's system clipboard for the next paste to surface"
    );
}

#[test]
fn cmd_backspace_is_recognized_as_delete_node() {
    // macOS Finder convention: ⌘⌫ moves the selection to the Trash.
    assert!(is_delete_node_key(key(
        KeyCode::Backspace,
        KeyModifiers::SUPER
    )));
}

#[test]
fn plain_backspace_is_delete_node_on_mac_layouts() {
    // On Mac keyboards the key labeled "delete" reports as Backspace; in
    // the tree pane (the only context this helper is called from) it must
    // trigger deletion to match the user's expectation.
    assert!(is_delete_node_key(key(
        KeyCode::Backspace,
        KeyModifiers::NONE
    )));
}

/// #1563: Shift+Down from line 1 stopped at the start of the last line, so
/// the selection, and Run Selected Text on it, dropped the script's `done`.
/// Down on the last line now goes to its end, as in VS Code, so Shift+Down
/// selects through it.
#[test]
fn shift_down_selects_through_the_end_of_the_last_line() {
    let (_tmp, mut app) = app_with_run_script();
    let last = app.editor.lines.len() - 1;
    assert_eq!(app.editor.lines[last], "done");
    for _ in 0..6 {
        app.handle_key(key(KeyCode::Down, KeyModifiers::SHIFT))
            .unwrap();
    }
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (last, 4));
    assert_eq!(
        app.editor.selection_text(),
        "echo one\necho two\nfor i in 1 2; do\n  echo loop $i\ndone"
    );
}

/// #1563: Down on the last line goes to its end; Up on the first line goes
/// to its start, and Shift+Up selects back to the start of the file.
#[test]
fn down_on_the_last_line_and_up_on_the_first_reach_the_line_ends() {
    let (_tmp, mut app) = app_with_run_script();
    let last = app.editor.lines.len() - 1;
    app.editor.cursor_row = last;
    app.editor.cursor_col = 1;
    app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
        .unwrap();
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (last, 4));

    app.editor.cursor_row = 0;
    app.editor.cursor_col = 8;
    app.handle_key(key(KeyCode::Up, KeyModifiers::NONE))
        .unwrap();
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (0, 0));

    app.editor.cursor_row = 1;
    app.editor.cursor_col = 4;
    for _ in 0..3 {
        app.handle_key(key(KeyCode::Up, KeyModifiers::SHIFT))
            .unwrap();
    }
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (0, 0));
    assert_eq!(app.editor.selection_text(), "echo one\necho");
}

/// Negative: Down between lines keeps the caret's column rather than
/// jumping to the line end; only the last line has the new edge.
#[test]
fn down_between_lines_keeps_the_column() {
    let (_tmp, mut app) = app_with_run_script();
    app.editor.cursor_col = 5;
    app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
        .unwrap();
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 5));
    app.handle_key(key(KeyCode::Up, KeyModifiers::NONE))
        .unwrap();
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (0, 5));
}

/// Guard (#843): `Ctrl`+`A` in the editor is still line start, never select
/// all: the reason LINUX.md lists Cmd+A as having no `Ctrl` form there.
#[test]
fn ctrl_a_in_the_editor_is_line_start_not_select_all() {
    let mut app = editor_app_with_lines(&["hello world", "next"]);
    app.editor.cursor_col = 5;
    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(app.editor.cursor_col, 0);
    assert!(app.editor.selection.is_none());
}

/// Guard (#843): `Ctrl`+`Enter` takes only what Cmd+Enter does. In a buffer
/// that is not Markdown it still breaks the line; in a fence `Ctrl`+`Shift`+
/// `Enter` still opens a line above, and neither `Ctrl`+`Alt`+`Enter` nor a
/// bare `Enter` (what a legacy terminal sends for `Ctrl`+`Enter`) runs it.
#[test]
fn ctrl_enter_leaves_other_buffers_and_other_enters_alone() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "notes.txt", "abcdef");
    app.editor.cursor_col = 3;
    app.handle_key(key(KeyCode::Enter, KeyModifiers::CONTROL))
        .unwrap();
    assert!(app.pending_run_block.is_none());
    // Outside Markdown it is Insert Line Below (#1571); on macOS `Ctrl`
    // stays the terminal's, so there it is a plain line break.
    let want: &[&str] = if cfg!(target_os = "macos") {
        &["abc", "def"]
    } else {
        &["abcdef", ""]
    };
    assert_eq!(app.editor.lines, want, "outside Markdown: no run");

    for mods in [
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
        KeyModifiers::CONTROL | KeyModifiers::ALT,
        KeyModifiers::NONE,
    ] {
        let mut app = markdown_fence_app(tmp.path());
        let rows = app.editor.lines.len();
        app.handle_key(key(KeyCode::Enter, mods)).unwrap();
        assert!(
            app.pending_run_block.is_none(),
            "{mods:?}+Enter ran the fence"
        );
        if mods != KeyModifiers::CONTROL | KeyModifiers::ALT {
            assert_eq!(
                app.editor.lines.len(),
                rows + 1,
                "{mods:?}+Enter adds a line"
            );
        }
    }
}

/// #1571: `Ctrl`+`Enter` (`Cmd`+`Enter` on macOS) is VS Code's Insert Line
/// Below: the caret mid-line opens an indented line under it and leaves the
/// current line whole. It used to split the line like `Enter`.
#[test]
fn cmd_enter_inserts_a_line_below_without_splitting_the_line() {
    let chords = if cfg!(target_os = "macos") {
        vec![KeyModifiers::SUPER]
    } else {
        vec![KeyModifiers::CONTROL, KeyModifiers::SUPER]
    };
    for mods in chords {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = app_with_open_file(tmp.path(), "i.py", "total = price * qty\nprint(total)\n");
        app.editor.cursor_row = 0;
        app.editor.cursor_col = 8;
        app.handle_key(key(KeyCode::Enter, mods)).unwrap();
        assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 0));
        app.handle_key(key(KeyCode::Char('X'), KeyModifiers::SHIFT))
            .unwrap();
        assert_eq!(
            app.editor.lines,
            ["total = price * qty", "X", "print(total)"],
            "{mods:?}+Enter"
        );
        assert_eq!(app.status, "Opened line below");
    }
}

/// #1571: the new line takes the current line's indent, as VS Code's does.
#[test]
fn cmd_enter_keeps_the_indent_of_the_current_line() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "i.py", "def f():\n    x = 1\n");
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 5;
    app.handle_key(key(KeyCode::Enter, KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(app.editor.lines, ["def f():", "    x = 1", "    "]);
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (2, 4));
}

/// #1571: in Markdown prose, outside every runnable fence, `Cmd`+`Enter`
/// is Insert Line Below; only a runnable fence under the caret claims it.
#[test]
fn cmd_enter_in_markdown_prose_inserts_a_line_below() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = markdown_fence_app(tmp.path());
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 2;
    app.handle_key(key(KeyCode::Enter, KeyModifiers::SUPER))
        .unwrap();
    assert!(app.pending_run_block.is_none());
    assert_eq!(app.status, "Opened line below");
    assert_eq!(app.editor.lines[..3], ["# Run", "", ""]);
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 0));
}

/// Guard (#843): only the bare `Ctrl`+`K` leads. `Ctrl`+`Shift`+`K` is still
/// Delete Line, and `Ctrl`+`Alt`+`K` arms nothing.
#[test]
fn ctrl_shift_k_still_deletes_the_line_and_ctrl_alt_k_never_leads() {
    let mut app = editor_app_with_lines(&["one", "two"]);
    app.handle_key(key(
        KeyCode::Char('K'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert!(app.cmd_k_leader.is_none());
    assert_eq!(app.editor.lines, ["two"]);
    app.handle_key(key(
        KeyCode::Char('k'),
        KeyModifiers::CONTROL | KeyModifiers::ALT,
    ))
    .unwrap();
    assert!(app.cmd_k_leader.is_none());
}

/// Guard (#843): the palette's "Kill to End of Line" at the end of a line
/// kills nothing and never joins the next line up, as `Ctrl`+`K` did not.
#[test]
fn kill_to_end_of_line_at_the_end_of_a_line_changes_nothing() {
    use crate::widgets::command_palette::Command;
    let mut app = editor_app_with_lines(&["hello", "next"]);
    app.editor.cursor_col = 5;
    app.status.clear();
    app.run_command(Command::KillToEndOfLine);
    assert_eq!(app.editor.lines, ["hello", "next"]);
    assert!(app.status.is_empty(), "{}", app.status);
}

#[test]
fn editor_shift_alt_down_duplicates_the_current_line_via_handle_key() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.lines = vec![String::from("alpha"), String::from("beta")];
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 3;
    app.handle_key(key(KeyCode::Down, KeyModifiers::ALT | KeyModifiers::SHIFT))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["alpha", "alpha", "beta"]);
    assert_eq!(
        (app.editor.cursor_row, app.editor.cursor_col),
        (1, 3),
        "cursor must follow onto the duplicated line"
    );
}

#[test]
fn editor_shift_alt_up_duplicates_the_current_line_via_handle_key() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.lines = vec![String::from("alpha"), String::from("beta")];
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 2;
    app.handle_key(key(KeyCode::Up, KeyModifiers::ALT | KeyModifiers::SHIFT))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["alpha", "beta", "beta"]);
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 2));
}

#[test]
fn editor_alt_right_jumps_one_word_forward() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.lines = vec![String::from("hello world rest")];
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    app.handle_key(key(KeyCode::Right, KeyModifiers::ALT))
        .unwrap();
    assert_eq!(app.editor.cursor_col, 5);
    app.handle_key(key(KeyCode::Right, KeyModifiers::ALT))
        .unwrap();
    assert_eq!(app.editor.cursor_col, 11);
}

#[test]
fn editor_cmd_gg_jumps_to_top_of_file() {
    let mut app = editor_app_with_lines(&["a", "b", "c", "d"]);
    app.editor.cursor_row = 3;
    app.handle_key(key(KeyCode::Char('g'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('g'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (0, 0));
}

#[test]
fn editor_cmd_g_then_plain_g_also_jumps_to_top() {
    let mut app = editor_app_with_lines(&["a", "b", "c", "d"]);
    app.editor.cursor_row = 3;
    app.handle_key(key(KeyCode::Char('g'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('g'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (0, 0));
}

#[test]
fn editor_cmd_g_count_g_jumps_to_specific_line() {
    let mut app = editor_app_with_lines(&["a", "b", "c", "d", "e"]);
    app.handle_key(key(KeyCode::Char('g'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('3'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('g'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (2, 0));
}

#[test]
fn editor_cmd_g_multidigit_count_g_jumps_to_specific_line() {
    let mut app = editor_app_with_lines(&(0..30).map(|_| "x").collect::<Vec<_>>());
    app.handle_key(key(KeyCode::Char('g'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('1'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('2'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('g'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.cursor_row, 11);
}

/// #902: VS Code's Go to Line, `Ctrl+G 25 Enter`, lands on line 25 as
/// `Ctrl+G 25 g` does, instead of cancelling the chord and passing the Enter
/// on as a newline.
#[test]
fn editor_ctrl_g_count_enter_jumps_to_the_line_without_a_newline() {
    let lines: Vec<String> = (1..=30).map(|n| format!("line {n}")).collect();
    let mut app = editor_app_with_lines(&lines.iter().map(String::as_str).collect::<Vec<_>>());
    app.editor.cursor_row = 2;
    app.handle_key(key(KeyCode::Char('g'), KeyModifiers::CONTROL))
        .unwrap();
    for d in ['2', '5'] {
        app.handle_key(key(KeyCode::Char(d), KeyModifiers::NONE))
            .unwrap();
    }
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.lines, lines,
        "the Enter must not reach the buffer"
    );
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (24, 0));
    assert_eq!(app.status, "Line 25");
}

/// #902: a key that cancels a chord after its count was typed goes with the
/// swallowed digits instead of editing the buffer on its own. Without a count
/// the key keeps its meaning, except Esc, which only cancels.
#[test]
fn editor_key_cancelling_a_counted_chord_does_not_edit_the_buffer() {
    let g = key(KeyCode::Char('g'), KeyModifiers::SUPER);
    let y = key(KeyCode::Char('y'), KeyModifiers::SUPER);
    let plain = |c| key(KeyCode::Char(c), KeyModifiers::NONE);
    let leaders = [
        vec![g, plain('1'), plain('2')],
        vec![y, plain('2')],
        vec![key(KeyCode::Char('3'), KeyModifiers::SUPER)],
    ];
    let cancels = [
        key(KeyCode::Tab, KeyModifiers::NONE),
        key(KeyCode::Backspace, KeyModifiers::NONE),
        key(KeyCode::Enter, KeyModifiers::NONE),
        plain('x'),
        key(KeyCode::Esc, KeyModifiers::NONE),
    ];
    for leader in &leaders {
        for &cancel in &cancels {
            if leader[0] == g && cancel.code == KeyCode::Enter {
                continue; // completes Go to Line, tested above
            }
            let mut app = editor_app_with_lines(&["alpha", "beta", "gamma"]);
            app.editor.cursor_row = 1;
            app.editor.cursor_col = 2;
            for &k in leader.iter().chain([&cancel]) {
                app.handle_key(k).unwrap();
            }
            let case = format!("{leader:?} then {cancel:?}");
            assert_eq!(app.editor.lines, vec!["alpha", "beta", "gamma"], "{case}");
            assert_eq!(
                (app.editor.cursor_row, app.editor.cursor_col),
                (1, 2),
                "{case}"
            );
            assert_eq!(app.status, "Chord cancelled", "{case}");
        }
    }

    let mut app = editor_app_with_lines(&["alpha"]);
    app.handle_key(g).unwrap();
    app.handle_key(plain('x')).unwrap();
    assert_eq!(app.editor.lines, vec!["xalpha"], "no count: the key types");
    app.editor.start_selection_at_cursor();
    app.editor.move_right();
    app.editor.extend_selection_to_cursor();
    app.handle_key(g).unwrap();
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.editor.selection.is_some(),
        "Esc cancels the chord and nothing else"
    );
    assert_eq!(app.status, "Chord cancelled");
}

#[test]
fn editor_cmd_shift_g_jumps_to_bottom_of_file() {
    let mut app = editor_app_with_lines(&["a", "b", "c", "d"]);
    app.handle_key(key(
        KeyCode::Char('G'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(app.editor.cursor_row, 3);
    assert_ne!(
        app.sidebar_view,
        SidebarView::SourceControl,
        "cmd+shift+g in editor pane must NOT hijack to source control"
    );
}

#[test]
fn editor_cmd_d_now_selects_the_word_instead_of_deleting() {
    // Cmd+D moved from the old `Cmd+d d` delete-line convenience to VS Code's
    // "Add Selection to Next Find Match"; delete-line now lives on Cmd+Shift+K.
    let mut app = editor_app_with_lines(&["alpha", "beta", "gamma"]);
    app.editor.cursor_row = 1;
    app.handle_key(key(KeyCode::Char('d'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(
        app.editor.lines,
        vec!["alpha", "beta", "gamma"],
        "Cmd+D no longer deletes the line"
    );
    assert!(
        app.editor.selection.is_some(),
        "Cmd+D selects the word under the cursor"
    );
}

#[test]
fn editor_cmd_yy_does_not_modify_buffer() {
    let mut app = editor_app_with_lines(&["alpha", "beta", "gamma"]);
    app.editor.cursor_row = 1;
    app.handle_key(key(KeyCode::Char('y'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('y'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["alpha", "beta", "gamma"]);
    assert!(app.status.starts_with("Yanked"));
}

#[test]
fn editor_ctrl_a_jumps_to_start_of_line() {
    let mut app = editor_app_with_lines(&["hello world"]);
    app.editor.cursor_col = 7;
    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(app.editor.cursor_col, 0);
}

#[test]
fn editor_ctrl_e_jumps_to_end_of_line() {
    let mut app = editor_app_with_lines(&["hello world"]);
    app.editor.cursor_col = 3;
    app.handle_key(key(KeyCode::Char('e'), KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(app.editor.cursor_col, 11);
}

/// `Ctrl+K` kills where it is not the `Cmd+K` leader: on macOS, and in vim
/// mode off it (#843).
#[test]
fn editor_ctrl_k_kills_to_end_of_line() {
    let mut app = editor_app_with_lines(&["hello world", "next"]);
    app.vim.enabled = cfg!(not(target_os = "macos"));
    app.editor.cursor_col = 5;
    app.handle_key(key(KeyCode::Char('k'), KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["hello", "next"]);
}

#[test]
fn editor_cmd_count_gg_jumps_to_line_with_leading_count() {
    let mut app = editor_app_with_lines(&["a", "b", "c", "d", "e"]);
    app.handle_key(key(KeyCode::Char('3'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('g'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('g'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(app.editor.cursor_row, 2);
}

#[test]
fn editor_cmd_count_yy_yanks_n_lines_with_leading_count() {
    let mut app = editor_app_with_lines(&["a", "b", "c", "d"]);
    app.editor.cursor_row = 0;
    app.handle_key(key(KeyCode::Char('2'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('y'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('y'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["a", "b", "c", "d"]);
    assert!(app.status.contains("Yanked 2"));
}

#[test]
fn editor_cmd_count_then_shift_g_jumps_to_specific_line() {
    let mut app = editor_app_with_lines(&["a", "b", "c", "d", "e"]);
    app.handle_key(key(KeyCode::Char('4'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(
        KeyCode::Char('G'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(app.editor.cursor_row, 3);
}

#[test]
fn editor_ctrl_u_kills_to_start_of_line() {
    let mut app = editor_app_with_lines(&["hello world"]);
    app.editor.cursor_col = 6;
    app.handle_key(key(KeyCode::Char('u'), KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["world"]);
    assert_eq!(app.editor.cursor_col, 0);
}

#[test]
fn editor_cmd_o_opens_line_below_with_indent() {
    let mut app = editor_app_with_lines(&["    foo", "bar"]);
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 4;
    app.handle_key(key(KeyCode::Char('o'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["    foo", "    ", "bar"]);
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 4));
}

/// #956: Enter leaves only indentation on its new line; switching to
/// another tab leaves that line, so the tab switched away from is saved
/// with it blank. The tab still being typed in keeps it under the caret.
#[test]
fn switching_tabs_clears_the_indentation_enter_left_behind() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.py");
    let b = tmp.path().join("b.py");
    std::fs::write(&a, "def f():\n    return 1\n").unwrap();
    std::fs::write(&b, "x = 1\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&a).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 12;
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines[2], "    ", "the caret's line keeps it");
    let a_tab = app.editor.active_index();
    app.editor.open_in_new_tab(&b).unwrap();
    app.trim_auto_indents();
    assert_eq!(
        app.editor.editors[a_tab].lines[2], "",
        "a.py's line was left"
    );
}

/// #956: moving off the line with a key, through the app's key handling,
/// clears what Enter left on it.
#[test]
fn arrowing_off_a_line_enter_only_indented_clears_it() {
    let mut app = editor_app_with_lines(&["def f():", "    return 1", "x = 2"]);
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 12;
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines[2], "    ");
    app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines, ["def f():", "    return 1", "", "x = 2"]);
}

#[test]
fn editor_cmd_shift_enter_opens_line_above_with_indent() {
    // Open-line-above moved off Cmd+Shift+O (now Go to Symbol) onto its real
    // VS Code chord, Cmd+Shift+Enter.
    let mut app = editor_app_with_lines(&["foo", "    bar"]);
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 6;
    app.handle_key(key(
        KeyCode::Enter,
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(app.editor.lines, vec!["foo", "    ", "    bar"]);
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 4));
}

#[test]
fn editor_cmd_a_still_selects_all() {
    let mut app = editor_app_with_lines(&["hello", "world"]);
    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(app.editor.selection_text(), "hello\nworld");
}

#[test]
fn editor_alt_left_jumps_one_word_backward() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.lines = vec![String::from("hello world rest")];
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 16;
    app.handle_key(key(KeyCode::Left, KeyModifiers::ALT))
        .unwrap();
    assert_eq!(app.editor.cursor_col, 12);
    app.handle_key(key(KeyCode::Left, KeyModifiers::ALT))
        .unwrap();
    assert_eq!(app.editor.cursor_col, 6);
}

/// #909: Ctrl is the word modifier on Linux, as in VS Code there, so
/// Ctrl+arrows step and select by word instead of by character.
#[test]
fn editor_ctrl_arrows_step_and_select_by_word() {
    let mut app = editor_app_with_lines(&["alpha beta gamma delta"]);
    for _ in 0..2 {
        app.handle_key(key(KeyCode::Right, KeyModifiers::CONTROL))
            .unwrap();
    }
    assert_eq!(app.editor.cursor_col, 10);
    app.handle_key(key(
        KeyCode::Left,
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(app.editor.selection_text(), "beta");
    app.handle_key(key(KeyCode::Left, KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!((app.editor.cursor_col, app.editor.selection), (0, None));
}

/// #909: Ctrl+Backspace / Ctrl+Delete (and macOS's Opt+Backspace) delete a
/// word, not one character.
#[test]
fn editor_ctrl_backspace_and_delete_delete_a_word() {
    let mut app = editor_app_with_lines(&["alpha beta gamma delta"]);
    app.editor.cursor_col = 22;
    app.handle_key(key(KeyCode::Backspace, KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["alpha beta gamma "]);
    app.handle_key(key(KeyCode::Backspace, KeyModifiers::ALT))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["alpha beta "]);
    app.editor.cursor_col = 0;
    app.handle_key(key(KeyCode::Delete, KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(app.editor.lines, vec![" beta "]);
    app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Delete, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["beta "], "plain keys still take one");
}

/// #909: Ctrl+Home / Ctrl+End go to the start / end of the document, and
/// with Shift select there, instead of acting like Home / End.
#[test]
fn editor_ctrl_home_and_end_go_to_the_ends_of_the_document() {
    let mut app = editor_app_with_lines(&["alpha beta", "second line", "third"]);
    app.editor.cursor_row = 2;
    app.editor.cursor_col = 3;
    app.handle_key(key(KeyCode::Home, KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (0, 0));
    app.handle_key(key(
        KeyCode::End,
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (2, 5));
    assert_eq!(
        app.editor.selection_text(),
        "alpha beta\nsecond line\nthird"
    );
    app.handle_key(key(KeyCode::Home, KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (0, 0));
    assert!(app.editor.selection.is_none());
}

#[test]
fn editor_shift_alt_right_runs_expand_selection_not_word_extension() {
    // #254 reassigned Shift+Alt+Right from word-wise extension to VS
    // Code's Expand Selection (the same collision VS Code resolves the
    // same way). With no path/language, the textual fallback grows to
    // the line span immediately — no LSP round trip.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.lines = vec![String::from("hello world")];
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    app.handle_key(key(KeyCode::Right, KeyModifiers::ALT | KeyModifiers::SHIFT))
        .unwrap();
    assert_eq!(
        app.editor.selection_text(),
        "hello world",
        "Shift+Option+Right expands to the enclosing range (the line here)"
    );
    // Shift+Alt+Left retraces to the gesture's start.
    app.handle_key(key(KeyCode::Left, KeyModifiers::ALT | KeyModifiers::SHIFT))
        .unwrap();
    assert!(
        app.editor.selection.is_none(),
        "shrink retraced to the caret"
    );
}

#[test]
fn cmd_v_is_recognised_as_editor_paste_key() {
    assert!(is_editor_paste_key(key(
        KeyCode::Char('v'),
        KeyModifiers::SUPER
    )));
    assert!(is_editor_paste_key(key(
        KeyCode::Char('v'),
        KeyModifiers::CONTROL
    )));
    assert!(is_editor_paste_key(key(
        KeyCode::Char('\u{16}'),
        KeyModifiers::NONE
    )));
    assert!(!is_editor_paste_key(key(
        KeyCode::Char('v'),
        KeyModifiers::NONE
    )));
    assert!(!is_editor_paste_key(key(
        KeyCode::Char('a'),
        KeyModifiers::SUPER
    )));
}

/// #933: where the host clipboard can't be read (Linux with no wl-paste,
/// xclip or xsel, as over SSH), Ctrl+V pastes what croft itself last
/// copied. Before, a copy went out by OSC 52 only and Ctrl+V found nothing.
#[test]
fn ctrl_v_pastes_croft_s_own_copy_where_the_host_clipboard_cant_be_read() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("c.py");
    std::fs::write(&f, "one\ntwo").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    app.focus = Pane::Editor;
    app.clipboard_reader = || None;
    let ctrl_v = key(KeyCode::Char('v'), KeyModifiers::CONTROL);
    // Negative: nothing copied yet, so nothing to paste, and it says so.
    app.handle_key(ctrl_v).unwrap();
    assert_eq!(app.editor.lines, vec!["one", "two"]);
    assert!(app.status.contains("read failed"), "{}", app.status);
    app.handle_key(key(KeyCode::End, KeyModifiers::SHIFT))
        .unwrap();
    assert_eq!(app.editor.selection_text(), "one", "precondition");
    app.handle_key(key(KeyCode::Char('c'), KeyModifiers::CONTROL))
        .unwrap();
    app.editor.clear_selection();
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 3;
    app.handle_key(ctrl_v).unwrap();
    assert_eq!(app.editor.lines, vec!["one", "twoone"]);
}

#[test]
fn typing_after_select_all_replaces_query() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.search.query = String::from("alpha");
    app.handle_search_key(key(KeyCode::Char('a'), KeyModifiers::SUPER));
    app.handle_search_key(key(KeyCode::Char('z'), KeyModifiers::NONE));
    assert_eq!(app.search.query, "z");
}

#[test]
fn scratch_buffer_saves_under_the_workspace_root_with_a_safe_name() {
    // A scratch buffer (MCP output / Git Output) must anchor under the open
    // project, where Save As offers to keep it, not at a bare filename in
    // croft's cwd, and must sanitise path separators in the title so the name
    // is a valid single file.
    let tmp = tempfile::tempdir().unwrap();
    let app = App::new(tmp.path().to_path_buf()).unwrap();
    let p = app.scratch_buffer_path("Web: a/b.md");
    assert_eq!(p, tmp.path().join("Web: a-b.md"));
}

#[test]
fn delete_line_deletes_every_carets_line() {
    // Cmd+D (Add Selection to Next Match) and Cmd+Shift+K (Delete Line) landed
    // in the same commit, but Delete Line only ever removed the primary
    // cursor's line: `delete_lines` calls `clear_selection`, which clears the
    // selection and leaves `carets` untouched. VS Code's deleteLines removes
    // every cursor's line, so the two bindings must compose.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let file = tmp.path().join("a.txt");
    std::fs::write(&file, "foo\nbar\nfoo\nbaz\n").unwrap();
    app.editor.open(&file).unwrap();
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;

    // Cmd+D twice: the first selects the word under the cursor, the second
    // adds the next match, demoting row 0 to a secondary caret.
    app.start_select_next_occurrence();
    app.start_select_next_occurrence();
    assert_eq!(app.editor.carets.len(), 1, "row 0 is now a secondary caret");
    assert_eq!(
        app.editor.cursor_row, 2,
        "the primary moved to the next match"
    );

    app.delete_current_line();

    assert_eq!(
        app.editor.lines,
        vec![String::from("bar"), String::from("baz")],
        "both matched lines go, not just the primary's"
    );
    assert!(
        app.editor.carets.is_empty(),
        "no stale caret is left painted on a line that no longer exists"
    );
}

#[test]
fn relative_clipboard_text_is_relative_inside_root_and_absolute_outside() {
    use std::path::Path;
    // Inside the workspace root: drop the root prefix.
    assert_eq!(
        relative_clipboard_text(Path::new("/ws/src/a.rs"), Path::new("/ws")),
        "src/a.rs"
    );
    // Outside the root: fall back to the absolute path, never a `../` walk.
    assert_eq!(
        relative_clipboard_text(Path::new("/other/a.rs"), Path::new("/ws")),
        "/other/a.rs"
    );
    // The root itself relativizes to empty.
    assert_eq!(
        relative_clipboard_text(Path::new("/ws"), Path::new("/ws")),
        ""
    );
}

/// Negative: with the editor focused, Ctrl+Z is still undo and never the
/// jump.
#[test]
fn ctrl_z_in_the_editor_still_undoes_and_opens_no_jump() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("a.txt");
    std::fs::write(&file, "one\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_at(&file, 0, 0).unwrap();
    app.focus = Pane::Editor;
    app.editor.cursor_col = 3;
    app.editor.insert_char('!');
    assert_eq!(app.editor.lines[0], "one!");
    app.handle_key(key(KeyCode::Char('z'), KeyModifiers::CONTROL))
        .unwrap();
    assert!(app.zoxide_jump.is_none());
    assert_eq!(app.editor.lines[0], "one", "Ctrl+Z undid the edit");
}

#[test]
fn shift_tab_in_editor_dedents_the_current_python_line() {
    let tmp = tempfile::tempdir().unwrap();
    // Two 4-space levels so indent detection (#211) reads the file's step
    // as 4; the old single 8-space jump now detects (correctly) as one
    // 8-wide level.
    let mut app = app_with_open_file(
        tmp.path(),
        "snippet.py",
        "def f():\n    if x:\n        pass\n",
    );
    app.editor.cursor_row = 2;
    app.editor.cursor_col = 8;
    // Shift+Tab reaches the editor as BackTab.
    app.handle_editor_key(key(KeyCode::BackTab, KeyModifiers::SHIFT));
    assert_eq!(
        app.editor.lines[2], "    pass",
        "Shift+Tab must outdent the line one level"
    );
    assert_eq!(app.editor.cursor_col, 4);
}

#[test]
fn tab_in_editor_indents_a_multiline_python_selection() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "block.py", "a = 1\nb = 2\n");
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 5;
    app.editor.selection = Some(crate::widgets::editor::EditorSelection {
        anchor: (0, 0),
        head: (1, 5),
    });
    app.handle_editor_key(key(KeyCode::Tab, KeyModifiers::NONE));
    assert_eq!(app.editor.lines[0], "    a = 1");
    assert_eq!(app.editor.lines[1], "    b = 2");
}

#[test]
fn open_line_above_relocated_from_cmd_shift_o_to_cmd_shift_enter() {
    // The VS Code-correct chord: Cmd/Ctrl+Shift+Enter inserts a line above.
    assert!(is_editor_open_line_above_key(key(
        KeyCode::Enter,
        KeyModifiers::SUPER | KeyModifiers::SHIFT
    )));
    assert!(is_editor_open_line_above_key(key(
        KeyCode::Enter,
        KeyModifiers::CONTROL | KeyModifiers::SHIFT
    )));
    // Cmd+Shift+O no longer triggers it (it now opens Go to Symbol).
    assert!(!is_editor_open_line_above_key(key(
        KeyCode::Char('o'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT
    )));
}

/// #1007: without the kitty keyboard protocol Ctrl+/ arrives as 0x1F,
/// which crossterm reads as Ctrl+7: it comments the line instead of
/// switching to tab 7, and Ctrl+\ and Ctrl+] (Ctrl+4, Ctrl+5) switch no
/// tab either. A terminal that does speak the protocol keeps Ctrl+7 as
/// tab 7.
#[test]
fn legacy_ctrl_slash_comments_the_line_instead_of_switching_tabs() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let files: Vec<PathBuf> = (0..7)
        .map(|i| {
            let p = tmp.path().join(format!("f{i}.py"));
            std::fs::write(&p, "x = 1\n").unwrap();
            p
        })
        .collect();
    for f in &files {
        app.editor.open_pinned(f).unwrap();
    }
    app.editor.select(0);
    app.focus_pane(Pane::Editor);
    let shown = |app: &App| app.editor.path.clone();

    app.legacy_ctrl_punct = true;
    for digit in ['4', '5'] {
        app.handle_key(key(KeyCode::Char(digit), KeyModifiers::CONTROL))
            .unwrap();
        assert_eq!(shown(&app).as_ref(), Some(&files[0]), "Ctrl+{digit}");
    }
    app.handle_key(key(KeyCode::Char('7'), KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(shown(&app).as_ref(), Some(&files[0]));
    assert_eq!(app.editor.lines[0], "# x = 1");

    app.legacy_ctrl_punct = false;
    app.handle_key(key(KeyCode::Char('7'), KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(shown(&app).as_ref(), Some(&files[6]), "a real Ctrl+7");
}

/// #1181: Ctrl+/ in a file with no comment syntax says so, as the palette
/// command does, instead of doing nothing silently; in a file croft has no
/// grammar for but knows the comment of, it comments.
#[test]
fn ctrl_slash_reports_a_file_with_no_comment_and_comments_one_by_extension() {
    let tmp = tempfile::tempdir().unwrap();
    let plain = tmp.path().join("notes.unknownext");
    std::fs::write(&plain, "hello\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&plain).unwrap();
    app.focus_pane(Pane::Editor);
    app.handle_key(key(KeyCode::Char('/'), KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(app.editor.lines[0], "hello");
    assert_eq!(
        app.status,
        "Toggle Line Comment: no comment for this language"
    );
    let kt = tmp.path().join("App.kt");
    std::fs::write(&kt, "class App\n").unwrap();
    app.editor.open_pinned(&kt).unwrap();
    app.status.clear();
    app.handle_key(key(KeyCode::Char('/'), KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(app.editor.lines[0], "// class App");
    assert!(app.status.is_empty(), "{}", app.status);
}

/// #1181 negative: Ctrl+/ on a blank line of a language that has a comment
/// does nothing, without claiming the language has no comment.
#[test]
fn ctrl_slash_on_a_blank_line_does_not_report_no_comment() {
    let tmp = tempfile::tempdir().unwrap();
    for (name, text) in [("main.rs", "   \n"), ("index.html", "\n")] {
        let path = tmp.path().join(name);
        std::fs::write(&path, text).unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.editor.open_pinned(&path).unwrap();
        app.focus_pane(Pane::Editor);
        app.status.clear();
        app.handle_key(key(KeyCode::Char('/'), KeyModifiers::CONTROL))
            .unwrap();
        assert_eq!(app.editor.lines[0], text.trim_end_matches('\n'), "{name}");
        assert!(app.status.is_empty(), "{name}: {}", app.status);
    }
}

#[test]
fn running_move_line_down_command_reorders_buffer() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.lines = vec!["a".to_string(), "b".to_string(), "c".to_string()];
    app.editor.cursor_row = 0;
    app.run_command(crate::widgets::command_palette::Command::MoveLineDown);
    assert_eq!(app.editor.lines, vec!["b", "a", "c"]);
}

#[test]
fn cmd_d_selects_word_then_adds_the_next_match_as_a_caret() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("a.rs");
    std::fs::write(&f, "foo foo foo\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.cursor_col = 1; // inside the first "foo"
    app.handle_key(key(KeyCode::Char('d'), KeyModifiers::SUPER))
        .unwrap();
    assert!(
        app.editor.selection.is_some() && !app.editor.has_multi_cursor(),
        "first Cmd+D selects the word only"
    );
    app.handle_key(key(KeyCode::Char('d'), KeyModifiers::SUPER))
        .unwrap();
    assert!(
        app.editor.has_multi_cursor(),
        "second Cmd+D adds the next match as a caret"
    );
}

/// #1558: `Cmd+Shift+L` with the caret on `foo` selects every whole-word
/// `foo`, and typing replaces them all (not the `foo` inside `food`). It
/// used to do nothing.
#[test]
fn cmd_shift_l_selects_every_occurrence_of_the_word() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = occurrences_app(tmp.path());
    app.editor.cursor_col = 1;
    cmd_shift_l(&mut app);
    assert_eq!(app.editor.carets.len() + 1, 3);
    type_char(&mut app, 'X');
    assert_eq!(app.editor.lines, ["X = 1", "bar = X", "X += 2", "food = 3"]);
}

/// #1558: `Cmd+D` from a hand-made selection also matches plain text; from
/// the caret it still takes whole words.
#[test]
fn cmd_d_from_a_hand_made_selection_matches_as_text() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = occurrences_app(tmp.path());
    select(&mut app, (0, 1), (0, 3));
    for _ in 0..2 {
        app.handle_key(key(KeyCode::Char('d'), KeyModifiers::SUPER))
            .unwrap();
    }
    type_char(&mut app, 'Q');
    assert_eq!(
        app.editor.lines,
        ["fQ = 1", "bar = fQ", "fQ += 2", "food = 3"]
    );

    let mut app = occurrences_app(tmp.path());
    app.editor.cursor_col = 1;
    for _ in 0..4 {
        app.handle_key(key(KeyCode::Char('d'), KeyModifiers::SUPER))
            .unwrap();
    }
    assert_eq!(app.editor.carets.len() + 1, 3, "`food` is no whole `foo`");
}

/// #1558: the word `Cmd+D` selected is forgotten once that selection is
/// dropped, so selecting the same `foo` again by hand matches plain text and
/// reaches the `foo` inside `food`.
#[test]
fn cmd_d_after_esc_and_a_hand_made_reselection_matches_as_text() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = occurrences_app(tmp.path());
    app.editor.cursor_col = 1;
    app.handle_key(key(KeyCode::Char('d'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(app.editor.selection.unwrap().normalised(), ((0, 0), (0, 3)));
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(app.editor.selection.is_none());
    app.editor.cursor_col = 0;
    for _ in 0..3 {
        app.handle_key(key(KeyCode::Right, KeyModifiers::SHIFT))
            .unwrap();
    }
    assert_eq!(app.editor.selection.unwrap().normalised(), ((0, 0), (0, 3)));
    for _ in 0..4 {
        app.handle_key(key(KeyCode::Char('d'), KeyModifiers::SUPER))
            .unwrap();
    }
    assert_eq!(app.editor.carets.len() + 1, 4, "`food` holds a text `foo`");
}

/// #1558: `Shift+Alt+I` puts a caret at the end of each selected line, so
/// typing appends to all three; a selection ending at column 0 of the next
/// line leaves that line out.
#[test]
fn shift_alt_i_adds_a_cursor_at_each_line_end() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = occurrences_app(tmp.path());
    select(&mut app, (0, 0), (2, 8));
    app.handle_key(key(
        KeyCode::Char('I'),
        KeyModifiers::SHIFT | KeyModifiers::ALT,
    ))
    .unwrap();
    assert!(app.editor.selection.is_none_or(|s| s.anchor == s.head));
    type_char(&mut app, 'Z');
    assert_eq!(
        app.editor.lines,
        ["foo = 1Z", "bar = fooZ", "foo += 2Z", "food = 3"]
    );

    let mut app = occurrences_app(tmp.path());
    select(&mut app, (0, 0), (2, 0));
    assert!(run_palette_row_titled(&mut app, "Add Cursors to Line Ends"));
    type_char(&mut app, ';');
    assert_eq!(
        app.editor.lines,
        ["foo = 1;", "bar = foo;", "foo += 2", "food = 3"]
    );
}

/// #1570: `Ctrl+L` selects the caret's line through the start of the next,
/// each further press adds a line, and typing replaces them; it used to do
/// nothing. On the last line, which has no line after it, it selects to the
/// end. The palette and VS Code's `expandLineSelection` id reach it too.
#[test]
fn ctrl_l_selects_the_line_and_each_press_adds_the_next() {
    use crate::widgets::command_palette::Command;
    assert_eq!(
        Command::from_id("expand_line_selection"),
        Some(Command::ExpandLineSelection)
    );
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "h.py", "a = 1\nb = 2\nc = 3");
    app.handle_key(ctrl('l')).unwrap();
    assert_eq!(app.editor.selection.unwrap().normalised(), ((0, 0), (1, 0)));
    app.handle_key(ctrl('l')).unwrap();
    assert_eq!(app.editor.selection.unwrap().normalised(), ((0, 0), (2, 0)));
    app.handle_key(ctrl('l')).unwrap();
    assert_eq!(app.editor.selection.unwrap().normalised(), ((0, 0), (2, 5)));
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    (app.editor.cursor_row, app.editor.cursor_col) = (1, 2);
    assert!(run_palette_row_titled(&mut app, "Expand Line Selection"));
    type_char(&mut app, 'Z');
    assert_eq!(app.editor.lines, ["a = 1", "Zc = 3"]);
}

/// #1570: with carets on lines 1 and 2, the first `Ctrl+L` leaves two line
/// selections that only touch, and the second grows them into an overlap,
/// which becomes one selection, so typing replaces lines 1 to 3 once. The
/// overlap used to reach the edit kept apart: the lower replacement left the
/// upper one's end stale, and typing panicked, or in a longer file deleted
/// lines nobody selected.
#[test]
fn ctrl_l_merges_the_line_selections_of_two_carets_once_they_overlap() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "h.py", "a\nb\nc\nd");
    app.run_command(Command::AddCursorBelow);
    app.handle_key(ctrl('l')).unwrap();
    assert_eq!(app.editor.carets.len(), 1, "touching selections stay two");
    app.handle_key(ctrl('l')).unwrap();
    assert!(
        !app.editor.has_multi_cursor(),
        "the overlap is one selection"
    );
    assert_eq!(app.editor.selection.unwrap().normalised(), ((0, 0), (3, 0)));
    type_char(&mut app, 'Z');
    assert_eq!(app.editor.lines, ["Zd"]);
}

const COLUMN_PY: &str = "alpha = 1\nbeta  = 2\ngamma = 3\n";

fn column_chord(code: KeyCode, cmd: KeyModifiers) -> KeyEvent {
    key(code, cmd | KeyModifiers::SHIFT | KeyModifiers::ALT)
}

/// #1560: Ctrl+Shift+Alt+Down twice then Right twice makes a three-row,
/// two-column box, and typing replaces those columns on every row.
#[test]
fn column_select_keys_make_a_box_that_typing_fills() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "s.py", COLUMN_PY);
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    for code in [KeyCode::Down, KeyCode::Down, KeyCode::Right, KeyCode::Right] {
        app.handle_key(column_chord(code, KeyModifiers::CONTROL))
            .unwrap();
    }
    assert_eq!(app.editor.carets.len(), 2, "one selection per row");
    type_keys(&mut app, "Y");
    assert_eq!(&app.editor.lines[..3], ["Ypha = 1", "Yta  = 2", "Ymma = 3"]);
}

/// #1560: macOS's Cmd+Shift+Opt arrows do the same.
#[test]
fn cmd_shift_opt_arrows_make_the_same_box() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "s.py", COLUMN_PY);
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 1;
    for code in [KeyCode::Down, KeyCode::Right, KeyCode::Right] {
        app.handle_key(column_chord(code, KeyModifiers::SUPER))
            .unwrap();
    }
    assert_eq!(app.editor.selection.unwrap().normalised(), ((1, 1), (1, 3)));
    assert_eq!(app.editor.carets.len(), 1);
    assert_eq!(app.editor.carets[0].normalised(), ((0, 1), (0, 3)));
}

/// Negative (#1560): Ctrl+Alt+Down without Shift still adds one caret
/// below and selects nothing.
#[test]
fn ctrl_alt_down_without_shift_still_adds_a_caret_below() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "s.py", COLUMN_PY);
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    app.handle_key(key(
        KeyCode::Down,
        KeyModifiers::CONTROL | KeyModifiers::ALT,
    ))
    .unwrap();
    assert_eq!(app.editor.carets.len(), 1);
    assert_eq!(app.editor.carets[0].head, (1, 0));
    assert_eq!(app.editor.cursor_row, 0);
    assert!(app.editor.selection.is_none());
}

/// Negative (#1560): Up from the first row has nowhere to go, so the box
/// stays one row.
#[test]
fn column_select_up_from_the_first_row_keeps_one_row() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "s.py", COLUMN_PY);
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    app.handle_key(column_chord(KeyCode::Right, KeyModifiers::CONTROL))
        .unwrap();
    app.handle_key(column_chord(KeyCode::Up, KeyModifiers::CONTROL))
        .unwrap();
    assert!(app.editor.carets.is_empty());
    assert_eq!(app.editor.selection.unwrap().normalised(), ((0, 0), (0, 1)));
}

/// #1560: with Column Selection Mode on, plain Shift+arrows grow a box;
/// turned off again, they extend a stream selection as before.
#[test]
fn column_selection_mode_turns_shift_arrows_into_a_box() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "s.py", COLUMN_PY);
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    app.run_command(Command::ToggleColumnSelection);
    assert!(app.editor.column_selection_mode);
    for code in [KeyCode::Down, KeyCode::Right] {
        app.handle_key(key(code, KeyModifiers::SHIFT)).unwrap();
    }
    assert_eq!(app.editor.carets.len(), 1, "a box over two rows");
    assert_eq!(app.editor.selection.unwrap().normalised(), ((1, 0), (1, 1)));

    app.run_command(Command::ToggleColumnSelection);
    assert!(!app.editor.column_selection_mode);
    app.editor.carets.clear();
    app.editor.selection = None;
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    for code in [KeyCode::Down, KeyCode::Right] {
        app.handle_key(key(code, KeyModifiers::SHIFT)).unwrap();
    }
    assert!(app.editor.carets.is_empty(), "a stream selection again");
    assert_eq!(app.editor.selection.unwrap().normalised(), ((0, 0), (1, 1)));
}

/// #1560: the status bar says when Column Selection Mode is on.
#[test]
fn the_status_bar_shows_column_selection_mode() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "s.py", COLUMN_PY);
    let backend = ratatui::backend::TestBackend::new(140, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    let status_row = |term: &ratatui::Terminal<ratatui::backend::TestBackend>| {
        let buf = term.backend().buffer();
        let y = buf.area.height - 1;
        (0..buf.area.width)
            .map(|x| buf[(x, y)].symbol().to_string())
            .collect::<String>()
    };
    term.draw(|f| app.render(f)).unwrap();
    assert!(!status_row(&term).contains("Column Selection"));
    app.run_command(Command::ToggleColumnSelection);
    term.draw(|f| app.render(f)).unwrap();
    assert!(
        status_row(&term).contains("Column Selection"),
        "{}",
        status_row(&term)
    );
}

/// #1560: every column-select key and the mode toggle are palette commands
/// that drive the editor.
#[test]
fn column_select_commands_are_in_the_palette() {
    use crate::widgets::command_palette::{ALL_COMMANDS, Command};
    for (cmd, title) in [
        (Command::ColumnSelectUp, "Column Select Up"),
        (Command::ColumnSelectDown, "Column Select Down"),
        (Command::ColumnSelectLeft, "Column Select Left"),
        (Command::ColumnSelectRight, "Column Select Right"),
        (Command::ColumnSelectPageUp, "Column Select Page Up"),
        (Command::ColumnSelectPageDown, "Column Select Page Down"),
        (
            Command::ToggleColumnSelection,
            "View: Toggle Column Selection Mode",
        ),
    ] {
        assert!(ALL_COMMANDS.contains(&cmd), "{title}");
        assert_eq!(cmd.title(), title);
    }
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "s.py", COLUMN_PY);
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    app.run_command(Command::ColumnSelectDown);
    app.run_command(Command::ColumnSelectRight);
    assert_eq!(app.editor.carets.len(), 1);
}

#[test]
fn cmd_shift_k_deletes_the_current_line() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("a.rs");
    std::fs::write(&f, "one\ntwo\nthree\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.cursor_row = 1; // the "two" line
    app.handle_key(key(
        KeyCode::Char('k'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(
        app.editor.lines,
        vec!["one".to_string(), "three".to_string()],
        "Cmd+Shift+K removes the cursor's line"
    );
}

// --- Increment / Decrement Number ------------------------------------------

/// The Cmd+Opt+= / Cmd+Opt+- chords as crossterm decodes them (ALT|SUPER on
/// macOS; Ctrl+Alt on Linux arrives as ALT|CONTROL, which the predicate
/// accepts too).
#[test]
fn the_increment_chord_bumps_the_number_under_the_cursor() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "port = 8080");
    app.editor.cursor_col = 8;
    app.handle_key(key(
        KeyCode::Char('='),
        KeyModifiers::ALT | KeyModifiers::SUPER,
    ))
    .unwrap();
    assert_eq!(app.editor.lines, vec!["port = 8081"]);
}

#[test]
fn the_decrement_chord_bumps_the_number_down() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "port = 8080");
    app.editor.cursor_col = 8;
    app.handle_key(key(
        KeyCode::Char('-'),
        KeyModifiers::ALT | KeyModifiers::CONTROL,
    ))
    .unwrap();
    assert_eq!(app.editor.lines, vec!["port = 8079"]);
}

/// A chord that finds nothing to bump must say so rather than looking like
/// a dead key.
#[test]
fn the_increment_chord_explains_itself_when_there_is_no_number() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "let name = value;");
    app.handle_key(key(
        KeyCode::Char('='),
        KeyModifiers::ALT | KeyModifiers::SUPER,
    ))
    .unwrap();
    assert_eq!(app.editor.lines, vec!["let name = value;"]);
    assert!(
        app.status.contains("No number"),
        "status should explain the no-op, got {:?}",
        app.status
    );
}

#[test]
fn the_emmet_chord_expands_the_abbreviation_in_the_editor() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("page.html");
    std::fs::write(&f, "ul>li*2\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 7;
    app.handle_editor_key(key(
        KeyCode::Char('e'),
        KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT,
    ));
    assert_eq!(
        app.editor.lines,
        vec!["<ul>", "    <li></li>", "    <li></li>", "</ul>"]
    );
    assert_eq!(app.status, "Emmet: expanded abbreviation");
}

/// #1640: the climb-up `^` used to stop the scan, so only the part after it
/// expanded and `header>nav>a*2^` stayed on the line as text.
#[test]
fn the_emmet_chord_expands_an_abbreviation_that_climbs_up() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("climb.html");
    std::fs::write(&f, "header>nav>a*2^h1\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 17;
    app.handle_editor_key(key(
        KeyCode::Char('e'),
        KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT,
    ));
    assert_eq!(
        app.editor.lines,
        vec![
            "<header>",
            "    <nav>",
            "        <a href=\"\"></a>",
            "        <a href=\"\"></a>",
            "    </nav>",
            "    <h1></h1>",
            "</header>",
        ]
    );
    assert_eq!(app.status, "Emmet: expanded abbreviation");
}

/// #1640 negative: a caret in prose is left alone, with the usual status.
#[test]
fn the_emmet_chord_leaves_a_power_in_prose_alone() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("page.html");
    std::fs::write(&f, "<p>2^10\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 7;
    app.handle_editor_key(key(
        KeyCode::Char('e'),
        KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT,
    ));
    assert_eq!(app.editor.lines, vec!["<p>2^10"]);
    assert_eq!(app.status, "Emmet: no abbreviation at the cursor");
}

/// Silence would leave the user unable to tell "wrong language" from
/// "typo in the abbreviation".
#[test]
fn the_emmet_chord_says_so_when_there_is_nothing_to_expand() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("page.html");
    std::fs::write(&f, "div>(span\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 9;
    app.handle_editor_key(key(
        KeyCode::Char('e'),
        KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT,
    ));
    assert_eq!(app.editor.lines, vec!["div>(span"]);
    assert_eq!(app.status, "Emmet: no abbreviation at the cursor");
}

/// A buffer Emmet does not run in gets a status naming the language, not
/// the "no abbreviation" message that sends the user hunting for a typo.
#[test]
fn the_emmet_chord_names_an_unsupported_language() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("main.rs");
    std::fs::write(&f, "ul>li*2\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 7;
    app.handle_editor_key(key(
        KeyCode::Char('e'),
        KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT,
    ));
    assert_eq!(app.editor.lines, vec!["ul>li*2"]);
    assert_eq!(app.status, "Emmet: not available in Rust files");
}

const EMMET_PAGE: &str = "<ul>\n  <li>Home</li>\n  <li>About</li>\n</ul>\n<p>Some text</p>\n";

/// Run palette command `cmd`, then, if it opened a prompt, answer it.
fn run_emmet(app: &mut App, cmd: crate::widgets::command_palette::Command, answer: Option<&str>) {
    app.run_command(cmd);
    if let Some(answer) = answer {
        assert!(app.input_prompt.is_some(), "a prompt asks first");
        type_keys(app, answer);
        app.submit_input_prompt();
    }
}

/// #1557: the issue's example: Wrap with Abbreviation around the selected
/// `<ul>` with `nav.menu`.
#[test]
fn wrap_with_abbreviation_wraps_the_selected_lines() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "page.html", EMMET_PAGE);
    app.editor.selection = Some(crate::widgets::editor::EditorSelection {
        anchor: (0, 0),
        head: (3, 5),
    });
    run_emmet(
        &mut app,
        Command::EmmetWrapWithAbbreviation,
        Some("nav.menu"),
    );
    assert_eq!(
        app.editor.lines.join("\n"),
        "<nav class=\"menu\">\n  <ul>\n    <li>Home</li>\n    <li>About</li>\n  </ul>\n</nav>\n<p>Some text</p>"
    );
    assert!(app.status.contains("wrapped"), "{}", app.status);
    app.editor.undo();
    assert_eq!(
        app.editor.lines.join("\n"),
        EMMET_PAGE.trim_end(),
        "one undo step"
    );
}

/// #1557: with nothing selected, Wrap with Abbreviation takes the element
/// around the caret, a caret just past `</ul>` included; outside any
/// element it takes the caret's line.
#[test]
fn with_nothing_selected_wrap_takes_the_element_at_the_caret() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "page.html", EMMET_PAGE);
    app.editor.cursor_row = 3;
    app.editor.cursor_col = 5;
    run_emmet(&mut app, Command::EmmetWrapWithAbbreviation, Some("nav"));
    assert_eq!(
        app.editor.lines.join("\n"),
        "<nav>\n  <ul>\n    <li>Home</li>\n    <li>About</li>\n  </ul>\n</nav>\n<p>Some text</p>"
    );
    let mut app = app_with_open_file(
        tmp.path(),
        "page.html",
        "<ul>\n  <li>Home</li>\n</ul>\nplain words\n",
    );
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 7;
    run_emmet(&mut app, Command::EmmetWrapWithAbbreviation, Some("b"));
    assert_eq!(
        app.editor.lines.join("\n"),
        "<ul>\n  <b>\n    <li>Home</li>\n  </b>\n</ul>\nplain words"
    );
    app.editor.cursor_row = 5;
    app.editor.cursor_col = 3;
    run_emmet(&mut app, Command::EmmetWrapWithAbbreviation, Some("p"));
    assert_eq!(
        app.editor.lines.join("\n"),
        "<ul>\n  <b>\n    <li>Home</li>\n  </b>\n</ul>\n<p>\n  plain words\n</p>"
    );
}

/// #1557: Remove Tag, Update Tag and Go to Matching Pair from the palette,
/// with the caret in the `<ul>`.
#[test]
fn remove_and_update_tag_and_go_to_matching_pair() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "page.html", EMMET_PAGE);
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 1;
    run_emmet(&mut app, Command::EmmetMatchTag, None);
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (3, 0));
    run_emmet(&mut app, Command::EmmetUpdateTag, Some("ol"));
    assert_eq!(app.editor.lines[0], "<ol>");
    assert_eq!(app.editor.lines[3], "</ol>");
    run_emmet(&mut app, Command::EmmetRemoveTag, None);
    assert_eq!(
        app.editor.lines.join("\n"),
        "<li>Home</li>\n<li>About</li>\n<p>Some text</p>"
    );
}

/// #1557: Balance outward grows the selection from the caret to the
/// element's content and then the element; inward walks it back.
#[test]
fn balance_outward_and_inward_step_the_selection() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "page.html", EMMET_PAGE);
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 7;
    run_emmet(&mut app, Command::EmmetBalanceOutward, None);
    assert_eq!(app.editor.selection_text(), "Home");
    run_emmet(&mut app, Command::EmmetBalanceOutward, None);
    assert_eq!(app.editor.selection_text(), "<li>Home</li>");
    run_emmet(&mut app, Command::EmmetBalanceInward, None);
    assert_eq!(app.editor.selection_text(), "Home");
}

/// #1557 negative: outside markup the commands say Emmet is not offered,
/// ask nothing and change nothing; in markup with no tag around the caret,
/// Remove Tag says so.
#[test]
fn emmet_editing_commands_leave_other_files_alone() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "notes.txt", "<ul>\n</ul>\n");
    for cmd in [
        Command::EmmetWrapWithAbbreviation,
        Command::EmmetUpdateTag,
        Command::EmmetRemoveTag,
        Command::EmmetMatchTag,
        Command::EmmetBalanceOutward,
    ] {
        app.run_command(cmd);
        assert!(app.input_prompt.is_none(), "{cmd:?} asks nothing");
        assert!(
            app.status.contains("not available"),
            "{cmd:?}: {}",
            app.status
        );
    }
    assert_eq!(app.editor.lines.join("\n"), "<ul>\n</ul>");
    let mut html = app_with_open_file(tmp.path(), "plain.html", "just text\n");
    run_emmet(&mut html, Command::EmmetRemoveTag, None);
    assert!(html.status.contains("no tag"), "{}", html.status);
    assert_eq!(html.editor.lines.join("\n"), "just text");
}

/// #1557: the commands are in the palette and VS Code's Emmet keybindings
/// import onto them.
#[test]
fn emmet_editing_commands_are_in_the_palette_and_import() {
    use crate::widgets::command_palette::{ALL_COMMANDS, Command};
    for (cmd, title, vscode) in [
        (
            Command::EmmetWrapWithAbbreviation,
            "Emmet: Wrap with Abbreviation",
            "editor.emmet.action.wrapWithAbbreviation",
        ),
        (
            Command::EmmetRemoveTag,
            "Emmet: Remove Tag",
            "editor.emmet.action.removeTag",
        ),
        (
            Command::EmmetUpdateTag,
            "Emmet: Update Tag",
            "editor.emmet.action.updateTag",
        ),
        (
            Command::EmmetBalanceOutward,
            "Emmet: Balance (outward)",
            "editor.emmet.action.balanceOut",
        ),
        (
            Command::EmmetBalanceInward,
            "Emmet: Balance (inward)",
            "editor.emmet.action.balanceIn",
        ),
        (
            Command::EmmetMatchTag,
            "Emmet: Go to Matching Pair",
            "editor.emmet.action.matchTag",
        ),
    ] {
        assert!(ALL_COMMANDS.contains(&cmd), "{cmd:?}");
        assert_eq!(cmd.title(), title);
        let mut report = crate::import_vscode::Report::default();
        crate::import_vscode::convert_keybindings(
            &serde_json::json!([{ "key": "ctrl+alt+w", "command": vscode }]),
            &mut report,
        );
        assert_eq!(
            report.keybindings,
            vec![(String::from("ctrl+alt+w"), String::from(cmd.id()), None)],
            "{vscode}"
        );
    }
}

#[test]
fn tab_switches_focus_between_the_find_and_replace_fields() {
    use crate::widgets::editor_find::FindField;
    let tmp = tempfile::tempdir().unwrap();
    // The caret opens off any word, so nothing is seeded and focus starts
    // in the query row (a seeded query would start in the replace row).
    let mut app = app_with_open_file(tmp.path(), "a.txt", "- alpha beta");
    app.handle_key(replace_chord()).unwrap();
    for c in "alpha".chars() {
        app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
            .unwrap();
    }
    assert_eq!(
        app.editor_find.as_ref().unwrap().query,
        "alpha",
        "typing lands in the query row first"
    );
    app.handle_key(key(KeyCode::Tab, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor_find.as_ref().unwrap().focus,
        FindField::Replace,
        "Tab moves focus to the replace row"
    );
    for c in "x".chars() {
        app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
            .unwrap();
    }
    assert_eq!(
        app.editor_find.as_ref().unwrap().replace,
        "x",
        "typing lands in the replace row once focused"
    );
    assert_eq!(
        app.editor_find.as_ref().unwrap().query,
        "alpha",
        "the query is untouched by replace-row typing"
    );
}

const LOG_PY: &str = "import logging\nlog = logging.getLogger(__name__)\n\nlog.debug(\"start\")\nlog.info(\"loaded config\")\nlog.debug(\"done\")\nlog.info(\"ready\")\n";

/// #1592: with the caret in a word and nothing selected, Replace starts in
/// the Find field with the word selected, so "debug, Tab, info" changes
/// debug to info and not the other way round.
#[test]
fn replace_from_a_caret_in_a_word_starts_in_the_find_field() {
    use crate::widgets::editor_find::FindField;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "app.py", LOG_PY);
    app.editor.cursor_row = 3;
    app.editor.cursor_col = 12;
    app.handle_key(replace_chord()).unwrap();
    let s = app.editor_find.as_ref().unwrap();
    assert_eq!(s.query, "start", "the word at the caret is still the seed");
    assert_eq!(s.focus, FindField::Query);
    type_keys(&mut app, "debug");
    app.handle_key(key(KeyCode::Tab, KeyModifiers::NONE))
        .unwrap();
    type_keys(&mut app, "info");
    let s = app.editor_find.as_ref().unwrap();
    assert_eq!((s.query.as_str(), s.replace.as_str()), ("debug", "info"));
    app.editor_find_replace_all();
    assert_eq!(app.editor.lines[3], "log.info(\"start\")");
    assert_eq!(app.editor.lines[5], "log.info(\"done\")");
    assert_eq!(app.editor.lines[4], "log.info(\"loaded config\")");
}

/// Negative (#1592): a one-line selection is a chosen find text, so Replace
/// still starts in the Replace field.
#[test]
fn replace_from_a_selection_starts_in_the_replace_field() {
    use crate::widgets::editor_find::FindField;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "app.py", LOG_PY);
    app.editor.selection = Some(crate::widgets::editor::EditorSelection {
        anchor: (3, 4),
        head: (3, 9),
    });
    app.editor.cursor_row = 3;
    app.editor.cursor_col = 9;
    app.handle_key(replace_chord()).unwrap();
    let s = app.editor_find.as_ref().unwrap();
    assert_eq!(s.query, "debug");
    assert_eq!(s.focus, FindField::Replace);
}

/// Negative (#1592): a find text typed in an open bar is chosen too, so
/// the Replace chord moves on to the Replace field.
#[test]
fn replace_on_an_open_find_bar_moves_to_the_replace_field() {
    use crate::widgets::editor_find::FindField;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "app.py", LOG_PY);
    app.editor.cursor_row = 3;
    app.editor.cursor_col = 12;
    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    type_keys(&mut app, "debug");
    app.handle_key(replace_chord()).unwrap();
    let s = app.editor_find.as_ref().unwrap();
    assert_eq!(s.query, "debug");
    assert_eq!(s.focus, FindField::Replace);
}

/// Negative (#1592): a multi-line selection seeds nothing, so Replace
/// starts in an empty Find field.
#[test]
fn replace_from_a_multi_line_selection_starts_in_an_empty_find_field() {
    use crate::widgets::editor_find::FindField;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "app.py", LOG_PY);
    app.editor.selection = Some(crate::widgets::editor::EditorSelection {
        anchor: (3, 0),
        head: (4, 3),
    });
    app.editor.cursor_row = 4;
    app.editor.cursor_col = 3;
    app.handle_key(replace_chord()).unwrap();
    assert_eq!(app.editor_find.as_ref().unwrap().focus, FindField::Query);
}

/// #1577: a replacement longer than the needle moves the range's end with
/// it, so a range ending mid-line still holds every replaced match and
/// nothing past it.
#[test]
fn the_range_follows_a_longer_replacement() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "f.py", FIND_IN_SELECTION_SRC);
    app.editor.selection = Some(crate::widgets::editor::EditorSelection {
        anchor: (3, 0),
        head: (4, 12),
    });
    // Off any word, so nothing is seeded and the query is typed.
    (app.editor.cursor_row, app.editor.cursor_col) = (5, 0);
    app.handle_key(replace_chord()).unwrap();
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    alt_l(&mut app);
    assert_eq!(find_count(&app), 2);
    app.handle_key(key(KeyCode::Tab, KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Enter, KeyModifiers::ALT | KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(app.editor.lines[3], "def b(xx):");
    assert_eq!(app.editor.lines[4], "    return xx * 2");
    assert_eq!(app.editor.find_range, Some(((3, 0), (4, 13))));
    assert_eq!(find_count(&app), 4, "both doubled matches, still in range");
    assert_eq!(app.editor.lines[0], "def a(x):");
    assert_eq!(app.editor.lines[7], "    return x - 3");

    // One at a time too: each Enter in the replace row moves the end on.
    let mut app = app_with_open_file(tmp.path(), "g.py", FIND_IN_SELECTION_SRC);
    (app.editor.cursor_row, app.editor.cursor_col) = (5, 0);
    app.handle_key(replace_chord()).unwrap();
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    // Selected after the bar opened, so the one-line selection does not
    // seed the query.
    app.editor.selection = Some(crate::widgets::editor::EditorSelection {
        anchor: (4, 0),
        head: (4, 12),
    });
    alt_l(&mut app);
    app.handle_key(key(KeyCode::Tab, KeyModifiers::NONE))
        .unwrap();
    for c in "value".chars() {
        app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
            .unwrap();
    }
    for _ in 0..3 {
        app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
            .unwrap();
    }
    assert_eq!(app.editor.lines[4], "    return value * 2");
    assert_eq!(app.editor.find_range, Some(((4, 0), (4, 16))));
    assert_eq!(app.editor.lines[7], "    return x - 3", "past the range");
}

/// #1577: a regex replacement's `\r` breaks the line, and the range's end
/// moves down with it, so the selection's later matches stay in it.
#[test]
fn the_range_follows_a_carriage_return_replacement() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = find_in_selection_app(tmp.path());
    app.editor_find.as_mut().unwrap().opts.use_regex = true;
    alt_l(&mut app);
    assert_eq!(app.editor.active_search_match, Some((3, 6, 1)));
    app.handle_key(key(KeyCode::Tab, KeyModifiers::NONE))
        .unwrap();
    for c in "a\\rb".chars() {
        app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
            .unwrap();
    }
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines[3], "def b(a");
    assert_eq!(app.editor.lines[4], "b):");
    assert_eq!(app.editor.find_range, Some(((3, 0), (6, 0))));
    assert_eq!(find_count(&app), 1, "the `x` the break pushed down");
}

#[test]
fn tab_expands_a_user_snippet_and_places_the_caret() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.snippets = crate::snippets::SnippetSet::from_json(
        r#"{ "Log": { "prefix": "log", "body": "console.log($1)" } }"#,
    );
    app.editor.insert_str("log");
    app.handle_editor_tab();
    assert_eq!(app.editor.lines[app.editor.cursor_row], "console.log()");
    assert_eq!(
        app.editor.cursor_col, 12,
        "caret lands inside the parentheses at $1"
    );
}

/// #914: variables expand to their values, from the buffer and from the
/// workspace, instead of their names; an unknown one is a placeholder
/// visited after the snippet's own stops, as in VS Code.
#[test]
fn tab_expands_snippet_variables_from_the_buffer_and_the_workspace() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join("pkg")).unwrap();
    let f = tmp.path().join("pkg/t.py");
    std::fs::write(&f, "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.snippets = crate::snippets::SnippetSet::from_json(
        r#"{ "Mirror": { "prefix": "mirror", "scope": "python",
             "body": "${1:x} = x + 1  $LINE_COMMENT $TM_FILENAME $RELATIVE_FILEPATH $CLIPBOARD $NOPE" } }"#,
    );
    crate::clipboard::test_clip::mock_write("clip");
    app.editor.insert_str("mirror");
    app.handle_editor_tab();
    assert_eq!(app.editor.lines[0], "x = x + 1  # t.py pkg/t.py clip NOPE");
    assert_eq!(app.editor.selection_text(), "x");
    app.handle_editor_tab();
    assert_eq!(app.editor.selection_text(), "NOPE");
}

// ── #1484: a repo's own snippets expand ──

const TEAM_SNIPPETS_1484: &str = r#"{
  // committed by the team
  "Team logger": {
    "scope": "python",
    "prefix": "tlog",
    "body": ["log = get_logger(__name__)", "log.info(\"$1\")$0"]
  }
}"#;

/// Open `name` in an app on `root` and expand `typed` with Tab; the first
/// line after.
fn expand_in_project_1484(root: &std::path::Path, name: &str, typed: &str) -> String {
    let f = root.join(name);
    std::fs::write(&f, "").unwrap();
    let mut app = App::new(root.to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.editor.insert_str(typed);
    app.handle_editor_tab();
    app.editor.lines[0].clone()
}

#[test]
fn a_vscode_code_snippets_file_expands_in_its_repo() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
    std::fs::write(
        tmp.path().join(".vscode/team.code-snippets"),
        TEAM_SNIPPETS_1484,
    )
    .unwrap();
    assert_eq!(
        expand_in_project_1484(tmp.path(), "app.py", "tlog"),
        "log = get_logger(__name__)"
    );
}

#[test]
fn a_croft_snippets_json_in_the_repo_expands() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
    std::fs::write(tmp.path().join(".croft/snippets.json"), TEAM_SNIPPETS_1484).unwrap();
    assert_eq!(
        expand_in_project_1484(tmp.path(), "app.py", "tlog"),
        "log = get_logger(__name__)"
    );
}

/// #1484 negative: a project snippet keeps its scope, and only files in
/// the two project places count.
#[test]
fn project_snippets_keep_their_scope_and_their_folder() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
    std::fs::write(
        tmp.path().join(".vscode/team.code-snippets"),
        TEAM_SNIPPETS_1484,
    )
    .unwrap();
    // Tab with nothing to expand indents instead.
    assert_eq!(
        expand_in_project_1484(tmp.path(), "main.rs", "tlog").trim_end(),
        "tlog"
    );

    let other = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(other.path().join(".vscode")).unwrap();
    std::fs::write(other.path().join("team.code-snippets"), TEAM_SNIPPETS_1484).unwrap();
    std::fs::write(other.path().join(".vscode/team.json"), TEAM_SNIPPETS_1484).unwrap();
    assert_eq!(
        expand_in_project_1484(other.path(), "app.py", "tlog").trim_end(),
        "tlog"
    );
}

/// #1484: a snippets file pulled into `.vscode` while croft runs applies
/// within the config watch's interval, and the next check is quiet.
#[test]
fn a_project_snippets_file_added_later_is_picked_up() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("app.py");
    std::fs::write(&f, "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.config_watch = crate::config_sync::ConfigWatch::new(Vec::new());
    app.watch_project_snippets();
    app.editor.open(&f).unwrap();
    std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
    std::fs::write(
        tmp.path().join(".vscode/team.code-snippets"),
        TEAM_SNIPPETS_1484,
    )
    .unwrap();
    let t0 = std::time::Instant::now();
    assert!(app.tick_config_watch_at(t0 + crate::config_sync::ConfigWatch::INTERVAL * 2));
    assert_eq!(app.status, "Project snippets reloaded");
    app.editor.insert_str("tlog");
    app.handle_editor_tab();
    assert_eq!(app.editor.lines[0], "log = get_logger(__name__)");
    assert!(!app.tick_config_watch_at(t0 + crate::config_sync::ConfigWatch::INTERVAL * 4));
}

/// #1484 negative: saving `.vscode/settings.json` touches the folder the
/// watch looks at, but no snippet changed, so the status says nothing
/// about snippets.
#[test]
fn a_settings_change_in_vscode_does_not_announce_snippets() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.config_watch = crate::config_sync::ConfigWatch::new(Vec::new());
    app.watch_project_snippets();
    app.status = String::from("Ready");
    std::thread::sleep(std::time::Duration::from_millis(20));
    std::fs::write(tmp.path().join(".vscode/settings.json"), "{}").unwrap();
    let t0 = std::time::Instant::now();
    app.tick_config_watch_at(t0 + crate::config_sync::ConfigWatch::INTERVAL * 2);
    assert_eq!(app.status, "Ready");
}

/// #1484: re-rooting swaps the old repository's snippets for the new one's.
#[test]
fn changing_the_workspace_root_reloads_project_snippets() {
    let old = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(old.path().join(".vscode")).unwrap();
    std::fs::write(
        old.path().join(".vscode/team.code-snippets"),
        TEAM_SNIPPETS_1484,
    )
    .unwrap();
    let new = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(new.path().join(".croft")).unwrap();
    std::fs::write(
        new.path().join(".croft/snippets.json"),
        TEAM_SNIPPETS_1484.replace("tlog", "nlog"),
    )
    .unwrap();
    let mut app = App::new(old.path().to_path_buf()).unwrap();
    app.change_workspace_root(new.path().to_path_buf());
    let f = new.path().join("app.py");
    std::fs::write(&f, "").unwrap();
    app.editor.open(&f).unwrap();
    app.editor.insert_str("tlog");
    app.handle_editor_tab();
    assert_eq!(app.editor.lines[0].trim_end(), "tlog");
    let g = new.path().join("b.py");
    std::fs::write(&g, "").unwrap();
    app.editor.open(&g).unwrap();
    app.editor.insert_str("nlog");
    app.handle_editor_tab();
    assert_eq!(app.editor.lines[0], "log = get_logger(__name__)");
}

/// #1484: a `.croft/snippets.json` created while croft runs applies, though
/// it did not exist when the watch began.
#[test]
fn a_croft_snippets_json_created_later_is_picked_up() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.config_watch = crate::config_sync::ConfigWatch::new(Vec::new());
    app.watch_project_snippets();
    std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
    std::fs::write(tmp.path().join(".croft/snippets.json"), TEAM_SNIPPETS_1484).unwrap();
    let t0 = std::time::Instant::now();
    assert!(app.tick_config_watch_at(t0 + crate::config_sync::ConfigWatch::INTERVAL * 2));
    assert_eq!(app.status, "Project snippets reloaded");
}

#[test]
fn a_multi_line_validated_range_falls_back_to_the_word_prompt() {
    // The server may validate a span crossing lines; there is no single-line
    // text to pre-fill from, so the word-under-cursor fallback takes over
    // rather than opening a prompt with an empty buffer.
    use crate::lsp::manager::PrepareRenameResult;
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("lib.rs");
    std::fs::write(&path, "fn main() {\n    let value = 1;\n}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&path).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 9; // inside `value`
    app.prepare_rename_request = Some(CaretRequest {
        id: 4,
        at: CaretSpot {
            path: path.clone(),
            row: 1,
            col: 9,
            seq: app.editor.edit_seq,
        },
    });
    assert!(app.apply_prepare_rename_verdict(PrepareRenameResult {
        request_id: 4,
        unsupported: false,
        error: None,
        target: Some(((1, 8, 2, 4), None)),
    }));
    assert_eq!(
        app.prompt.as_ref().expect("fallback prompt opened").buffer,
        "value",
        "a cross-line range yields no pre-fill text, so the fallback runs"
    );
}

/// Moving the caret or editing is a new position, asked once more; a
/// non-empty answer there still installs its ranges.
#[test]
fn a_moved_caret_or_an_edit_asks_once_more_and_ranges_still_install() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = linked_ts_app(tmp.path());
    app.tick_linked_editing();
    assert!(linked_wake(&mut app).is_some());

    app.editor.cursor_col = 8;
    app.tick_linked_editing();
    let moved: Vec<u64> = (0..20).filter_map(|_| linked_wake(&mut app)).collect();
    assert_eq!(
        moved.len(),
        1,
        "the moved caret asks exactly once: {moved:?}"
    );

    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    app.tick_linked_editing();
    let id = linked_tick_only(&mut app).expect("an edit asks again");
    answer_linked(&app, id, vec![(1, 0, 1, 7), (1, 9, 1, 16)]);
    app.drain_lsp_linked_editing();
    assert!(app.editor.has_linked_ranges(), "a real answer installs");
    let more: Vec<u64> = (0..20).filter_map(|_| linked_wake(&mut app)).collect();
    assert!(
        more.is_empty(),
        "inside the installed set nothing is asked: {more:?}"
    );
}

#[test]
fn editing_drops_stale_document_links() {
    use crate::lsp::manager::DocumentLinkItem;
    // Link ranges are measured against the text the server saw; an edit
    // shifts them, so a Ctrl+click would otherwise follow the wrong span
    // until the next batch lands.
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("a.rs");
    std::fs::write(
        &path,
        "// link here
",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&path).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.apply_document_links(
        path.clone(),
        vec![DocumentLinkItem {
            line: 0,
            character: 3,
            end_line: 0,
            end_character: 12,
            target: String::from("https://example.com"),
        }],
    );
    assert_eq!(
        app.editor.document_link_at(0, 5),
        Some("https://example.com"),
        "the link is live before the edit"
    );
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    app.editor.insert_char('x');
    assert_eq!(
        app.editor.document_link_at(0, 5),
        None,
        "the edit dropped the stale ranges"
    );
}

/// #257 round-3 review finding: a step that runs out of budget must leave
/// the user where they are. Marking the count partial and then clearing the
/// active match left the bar reading "1+ matches" with nothing highlighted
/// and no way back to the match they were on.
#[test]
fn a_step_that_runs_out_of_reach_keeps_the_match_it_already_had() {
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("far.log");
    // One match at the very top, then far more filler than a sweep may read,
    // so stepping forward from it exhausts the budget without finding another.
    let mut body = String::from("\u{1b}[31mERROR\u{1b}[0m first and only\n");
    let filler = "quiet line with nothing of interest ".repeat(4);
    for _ in 0..(crate::log_view::FIND_SCAN_BYTES / filler.len() + 3000) {
        body.push_str(&filler);
        body.push('\n');
    }
    std::fs::write(&p, &body).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.open(&p).unwrap();
    assert!(app.editor.log.is_some());

    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    for ch in "ERROR".chars() {
        app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
            .unwrap();
    }
    assert_eq!(
        app.editor.active_search_match.map(|(r, _, _)| r),
        Some(0),
        "typing lands on the only match"
    );

    // Enter steps forward, runs out of budget, and finds nothing more.
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.active_search_match.map(|(r, _, _)| r),
        Some(0),
        "an out-of-reach step must leave the highlight where it was, not \
         clear it and leave the user with a count and nothing to look at"
    );
    assert!(
        app.editor_find
            .as_ref()
            .is_some_and(|s| s.count_truncated()),
        "and the bar must say the search did not cover the whole file"
    );
}

/// #404 review: a wide character whose first half lands on the body's last
/// cell does not fit whole, and `set_stringn` drops it entirely. The
/// selection band must not colour that cell, or the annotator paints where
/// the painter deliberately put nothing, the same disagreement the cell map
/// exists to close, at the boundary.
#[test]
fn a_wide_character_clipped_at_the_right_edge_gets_no_selection_band() {
    use ratatui::layout::Rect;
    use ratatui::widgets::Widget;

    let tmp = tempfile::tempdir().unwrap();
    let area = Rect {
        x: 0,
        y: 0,
        width: 40,
        height: 8,
    };
    // Learn the body width from a probe render, so the fixture puts the
    // wide character exactly on the last cell whatever the chrome costs.
    let probe = tmp.path().join("probe.log");
    std::fs::write(&probe, "\u{1b}[31mx\u{1b}[0m\n").unwrap();
    let mut e = crate::widgets::editor::Editor::new();
    e.open(&probe).unwrap();
    let mut buf = ratatui::buffer::Buffer::empty(area);
    (&mut e).render(area, &mut buf);
    let width = e.log.as_ref().unwrap().last_body.width as usize;
    assert!(width > 2);

    let p = tmp.path().join("edge.log");
    let text = format!("{}\u{4e2d}", "x".repeat(width - 1));
    std::fs::write(&p, format!("\u{1b}[31m{text}\u{1b}[0m\n")).unwrap();
    let mut e = crate::widgets::editor::Editor::new();
    e.open(&p).unwrap();
    let chars = text.chars().count();
    e.log.as_mut().unwrap().selection = Some(((0, 0), (0, chars)));
    let mut buf = ratatui::buffer::Buffer::empty(area);
    (&mut e).render(area, &mut buf);
    let body = e.log.as_ref().unwrap().last_body;
    let last = body.x + body.width - 1;
    let selected_bg = crate::theme::Theme::BLACK.selection();
    assert_eq!(
        buf[(last, body.y)].symbol(),
        " ",
        "the painter drops a wide character that does not fit whole"
    );
    assert_ne!(
        buf[(last, body.y)].style().bg,
        Some(selected_bg),
        "so the band must not colour the cell it left blank"
    );
    assert_eq!(
        buf[(last - 1, body.y)].style().bg,
        Some(selected_bg),
        "while the character before it is selected as usual"
    );
}

/// #369: a mirrored tab undoes as far as the tab that was typed in.
///
/// A typing burst is one undo step where it was typed, so it is one step in
/// the file's tab too, and a selection away from the edit survives it.
#[test]
fn a_mirrored_typing_burst_is_one_undo_step_and_keeps_a_distant_selection() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, _) = app_with_symbol_tab_on_b(&tmp);
    app.sync_symbol_views();
    let before = app.editor.lines.clone();
    let mut sel = crate::widgets::editor::EditorSelection::new(0, 0);
    sel.head = (0, 4);
    app.editor.editors[0].selection = Some(sel);

    app.editor.cursor_row = 4;
    app.editor.cursor_col = 5;
    for c in ['a', 'b', 'c'] {
        app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
            .unwrap();
    }
    assert_eq!(app.editor.editors[0].lines[4], "    2abc");
    assert_eq!(
        app.editor.editors[0].selection,
        Some(sel),
        "a selection clear of the edit is kept"
    );
    assert!(app.editor.editors[0].undo());
    assert!(app.editor.editors[1].undo());
    assert_eq!(app.editor.editors[1].lines, before);
    assert_eq!(
        app.editor.editors[0].lines, before,
        "one undo takes back the whole burst in the file's tab too"
    );
}

#[test]
fn a_rewrite_that_only_changes_bytes_still_refreshes_the_byte_facts() {
    // A switch back from CRLF changes no line text, so the rows come back
    // identical -- but `right_crlf` and the "bytes differ, lines equal"
    // banner feed the hunk patch and the header. The
    // same-content skip must see those facts as content, or stage/revert
    // would build a patch from bytes no longer on disk.
    let (tmp, f) = repo_with_seed("a\nb\n");
    let root = tmp.path().to_path_buf();
    let mut app = App::new(root.clone()).unwrap();
    std::fs::write(&f, "a\r\nb\r\n").unwrap();
    app.editor
        .open_head_diff_with_text(
            std::path::PathBuf::from("seed.txt (HEAD)"),
            "a\nb\n",
            &f,
            true,
        )
        .unwrap();
    app.tag_open_diff(crate::widgets::diff::DiffSource::HeadVsWorking {
        root: root.clone(),
        rel: String::from("seed.txt"),
    });
    let d = app.editor.diff.as_ref().unwrap();
    assert!(
        d.right_crlf.iter().all(|&cr| cr) && d.bytes_differ_but_lines_equal,
        "precondition: {d:?}"
    );

    rewrite_later(&f, "a\nb\n");
    assert!(
        app.refresh_open_diff_views(false, &[], &no_paths()),
        "the byte-only rewrite counts as a change"
    );
    let d = app.editor.diff.as_ref().unwrap();
    assert!(
        !d.right_crlf.iter().any(|&cr| cr),
        "the working side is LF again"
    );
    assert!(
        !d.bytes_differ_but_lines_equal,
        "and the banner's fact is cleared"
    );
    assert!(
        !app.refresh_open_diff_views(false, &[], &no_paths()),
        "and it is not rebuilt again"
    );
}

// --- #1218: a multi-line paste keeps its shape under the caret ----------------

fn shop_app(tmp: &std::path::Path) -> App {
    let mut app = app_with_open_file(
        tmp,
        "shop.py",
        "class Shop:\n    def total(self, items):\n        if items:\n            n = 0\n            \n        return 0\n",
    );
    app.focus_pane(Pane::Editor);
    app.editor.cursor_row = 4;
    app.editor.cursor_col = 12;
    app
}

#[test]
fn a_bracketed_paste_into_a_nested_block_keeps_the_block_shape() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = shop_app(tmp.path());
    app.handle_paste("for x in items:\n    if x:\n        print(x)");
    assert_eq!(
        &app.editor.lines[4..7],
        &[
            "            for x in items:",
            "                if x:",
            "                    print(x)",
        ]
    );
}

#[test]
fn with_paste_reindent_off_a_paste_is_verbatim() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = shop_app(tmp.path());
    app.paste_reindent = false;
    app.handle_paste("for x in items:\n    if x:\n        print(x)");
    assert_eq!(app.editor.lines[5], "    if x:");
}

#[test]
fn a_multiline_paste_can_go_in_as_one_line() {
    let (mut app, _tmp) = plain_paste_app();
    app.handle_paste("echo a\r\n  echo b\r\n\r\n");
    app.handle_key(key(KeyCode::Char('l'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(pasted(&app), "echo a   echo b");
}

#[test]
fn a_cancelled_multiline_paste_writes_nothing() {
    let (mut app, _tmp) = plain_paste_app();
    app.handle_paste(TWO_LINES);
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(pasted(&app), "");
    assert!(app.pending_terminal_paste.is_none());
    // The next key is typing again, not an answer to the popup.
    app.handle_key(key(KeyCode::Char('l'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(pasted(&app), "l");
}

#[test]
fn the_confirmation_says_how_many_lines_will_run() {
    let (mut app, _tmp) = plain_paste_app();
    app.handle_paste(TWO_LINES);
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let screen: String = term
        .backend()
        .buffer()
        .content()
        .iter()
        .map(|c| c.symbol())
        .collect();
    assert!(screen.contains("PASTE 2 LINES"), "{screen}");
}

#[test]
fn a_bracketed_paste_or_a_single_line_goes_straight_in() {
    // Negative: a shell that brackets pastes runs nothing until Enter, and
    // one line with no line break runs nothing either.
    let (mut app, _tmp) = plain_paste_app();
    app.handle_paste("echo one-line");
    assert_eq!(pasted(&app), "echo one-line");
    app.terminals[0].feed_bytes_for_test(b"\x1b[?2004h");
    app.handle_paste(TWO_LINES);
    assert!(app.pending_terminal_paste.is_none());
    assert!(
        pasted(&app).ends_with(&format!("\x1b[200~{TWO_LINES}\x1b[201~")),
        "{:?}",
        pasted(&app)
    );
}

#[test]
fn a_second_paste_while_asking_is_refused_and_the_first_still_waits() {
    // The popup holds the first paste; a later one, multi-line or not,
    // neither replaces it nor slips into the shell behind the popup.
    let (mut app, _tmp) = plain_paste_app();
    app.handle_paste(TWO_LINES);
    app.handle_paste("rm -rf build\nls\n");
    app.handle_paste("echo sneaked");
    assert_eq!(pasted(&app), "", "nothing reaches the shell");
    assert_eq!(app.status, "Resolve the pending paste before pasting again");
    assert_eq!(
        app.pending_terminal_paste.as_deref(),
        Some(TWO_LINES.as_bytes()),
        "the first paste is the one still asked about"
    );
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(pasted(&app), TWO_LINES);
}

#[test]
fn once_the_paste_is_answered_clicks_and_pastes_work_again() {
    // Negative: the guards last only while the popup is up.
    let (mut app, _tmp) = two_pane_paste_app();
    app.handle_paste(TWO_LINES);
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    app.handle_paste("echo again");
    assert_eq!(pasted(&app), "echo again");
    let other = app.terminal_rail_rects[1];
    left_click(&mut app, other.x + 1, other.y);
    assert_eq!(app.active_terminal, 1, "the rail row switches panes again");
}

fn caret_on_screen(app: &App) -> bool {
    let bar = usize::from(app.editor.last_scrollbar.width > 0);
    let width = (app.editor.last_inner.width as usize)
        .saturating_sub(app.editor.last_gutter_width as usize + 2 + bar);
    app.editor.cursor_col >= app.editor.scroll_col
        && app.editor.cursor_col < app.editor.scroll_col + width
}

#[test]
fn end_on_a_wide_line_scrolls_the_caret_into_view() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, _term) = wide_line_app(tmp.path());
    app.handle_key(key(KeyCode::End, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.cursor_col, 609);
    assert!(app.editor.scroll_col > 0, "the view follows the caret");
    assert!(
        caret_on_screen(&app),
        "scroll_col {}",
        app.editor.scroll_col
    );
}

#[test]
fn typing_past_the_right_edge_keeps_the_caret_in_view() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, _term) = wide_line_app(tmp.path());
    app.editor.cursor_col = 60;
    for _ in 0..40 {
        app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
            .unwrap();
    }
    assert_eq!(app.editor.cursor_col, 100);
    assert!(
        caret_on_screen(&app),
        "scroll_col {}",
        app.editor.scroll_col
    );
}

#[test]
fn shift_end_extends_the_selection_and_follows_the_caret() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, _term) = wide_line_app(tmp.path());
    app.handle_key(key(KeyCode::End, KeyModifiers::SHIFT))
        .unwrap();
    assert!(app.editor.selection.is_some());
    assert!(
        caret_on_screen(&app),
        "scroll_col {}",
        app.editor.scroll_col
    );
}

#[test]
fn enter_at_the_end_of_a_wide_line_scrolls_back_to_column_one() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, _term) = wide_line_app(tmp.path());
    app.handle_key(key(KeyCode::End, KeyModifiers::NONE))
        .unwrap();
    app.editor.scroll_col = 560;
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 0));
    assert_eq!(app.editor.scroll_col, 0);
}

#[test]
fn end_on_a_short_line_leaves_the_view_alone() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, _term) = wide_line_app(tmp.path());
    app.editor.cursor_row = 1;
    app.handle_key(key(KeyCode::End, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.cursor_col, 5);
    assert_eq!(app.editor.scroll_col, 0);
}

#[test]
fn ctrl_a_selects_the_query_and_ctrl_backspace_deletes_a_word() {
    let (mut app, _tmp) = find_seed_app(2, 0);
    app.handle_key(ctrl('f')).unwrap();
    type_keys(&mut app, "write rows");
    app.handle_key(key(KeyCode::Backspace, KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(find_query(&app), "write ");
    app.handle_key(ctrl('a')).unwrap();
    type_keys(&mut app, "read");
    assert_eq!(find_query(&app), "read");
}

// ── #1483: one snippet croft cannot read no longer empties the whole set ──

/// A Python buffer holding `typed`, with a snippet set that mixes a plain
/// prefix and an array one; returns the first line after Tab.
fn expand_with_array_prefix_snippets(typed: &str) -> String {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("loop.py");
    std::fs::write(&f, "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.snippets = crate::snippets::SnippetSet::from_json(
        r#"{
            "Python main guard": { "prefix": "main", "body": "if __name__ == '__main__':", "scope": "python" },
            "For loop": { "prefix": ["for", "fori"], "body": ["for ${1:i} in range(${2:10}):", "    $0"], "scope": "python" }
        }"#,
    );
    app.editor.insert_str(typed);
    app.handle_editor_tab();
    app.editor.lines[0].clone()
}

/// Snippets the way `croft import-vscode` writes them from VS Code's
/// per-language files (#1641).
fn react_snippets() -> crate::snippets::SnippetSet {
    crate::snippets::SnippetSet::from_json(
        r#"{
          "Component": { "prefix": "rfc", "body": "function $1() {}", "scope": "javascriptreact" },
          "TS component": { "prefix": "tfc", "body": "const $1: FC = () => null", "scope": "typescriptreact" },
          "Log": { "prefix": "clg", "body": "console.log($1)", "scope": "javascript" },
          "Main": { "prefix": "ifm", "body": "if __name__ == '__main__':", "scope": "python" },
          "Key": { "prefix": "key", "body": "\"$1\": ", "scope": "jsonc" }
        }"#,
    )
}

/// Open `name` (empty) with the snippets above, type `prefix`, press Tab,
/// and return the line.
fn tab_after(name: &str, prefix: &str) -> String {
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join(name);
    std::fs::write(&p, "\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    app.snippets = react_snippets();
    app.editor.insert_str(prefix);
    app.handle_editor_tab();
    app.editor.lines[app.editor.cursor_row].clone()
}

/// #1641: a `javascriptreact` snippet expands in a `.jsx` file, and a
/// `jsonc` one in a `.jsonc` file, as in VS Code.
#[test]
fn a_javascriptreact_snippet_expands_in_a_jsx_file() {
    assert_eq!(tab_after("App.jsx", "rfc"), "function () {}");
    assert_eq!(tab_after("tsconfig.jsonc", "key"), "\"\": ");
}

/// Negative (#1641): `.tsx` keeps `typescriptreact`, a `javascript`
/// snippet keeps working in `.jsx` as it did, a `.js` file does not take
/// `javascriptreact` ones, and other languages' snippets stay out.
#[test]
fn jsx_snippet_scopes_leave_other_files_and_languages_alone() {
    assert_eq!(tab_after("App.tsx", "tfc"), "const : FC = () => null");
    assert_eq!(tab_after("App.jsx", "clg"), "console.log()");
    assert!(!tab_after("app.js", "rfc").contains("function"));
    assert!(!tab_after("App.jsx", "ifm").contains("__main__"));
}

#[test]
fn tab_expands_each_word_of_an_array_prefix() {
    assert_eq!(
        expand_with_array_prefix_snippets("fori"),
        "for i in range(10):"
    );
    assert_eq!(
        expand_with_array_prefix_snippets("for"),
        "for i in range(10):"
    );
    // The snippet beside it still expands too.
    assert_eq!(
        expand_with_array_prefix_snippets("main"),
        "if __name__ == '__main__':"
    );
}