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
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
//! Editor keys, vim mode, macros, multi-cursor and line commands, typing toggles,
//! copy, cut and paste routing and the clipboard, and reading dropped file paths out
//! of a paste.

use super::*;

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) enum VimOp {
    #[default]
    None,
    G,
    Y,
}

impl EditorVimChord {
    pub(super) fn reset(&mut self) {
        self.op = VimOp::None;
        self.count = 0;
    }
}

impl App {
    /// VS Code "Change All Occurrences" (Cmd/Ctrl+F2): select every textual
    /// match of the word under the cursor in the current file as multi-cursor
    /// carets so the next keystrokes edit them all at once.
    pub(super) fn start_change_all_occurrences(&mut self) {
        if self.editor.has_non_text_view() {
            return;
        }
        let n = self.editor.select_all_occurrences_of_word_at_cursor();
        if n == 0 {
            self.status = String::from("No symbol under cursor");
        } else {
            self.status = format!("Selected {n} occurrences (type to replace, Esc to cancel)");
        }
    }

    /// VS Code "Select All Occurrences of Find Match" (`Cmd+Shift+L`,
    /// #1558): a selection on every match of the selection, or of the word
    /// at the caret.
    pub(super) fn select_all_occurrences(&mut self) {
        if self.editor.has_non_text_view() {
            return;
        }
        let n = self.editor.select_all_occurrences();
        self.status = if n == 0 {
            String::from("Nothing to select: select text on one line, or put the caret on a word")
        } else {
            format!("Selected {n} occurrences (type to replace, Esc to cancel)")
        };
    }

    /// VS Code "Add Cursors to Line Ends" (`Shift+Alt+I`, #1558): a caret at
    /// the end of each selected line.
    pub(super) fn add_cursors_to_line_ends(&mut self) {
        if self.editor.has_non_text_view() {
            return;
        }
        let n = self.editor.add_cursors_to_line_ends();
        self.status = if n == 0 {
            String::from("Select the lines to put cursors at the ends of")
        } else {
            format!("{n} cursors at line ends")
        };
    }

    /// VS Code "Expand Line Selection" (`Cmd+L` / `Ctrl+L`, #1570): select
    /// the caret's whole line, and one more line on each further press.
    pub(super) fn expand_line_selection(&mut self) {
        if self.editor_is_text() {
            self.editor.expand_line_selection();
        }
    }

    /// VS Code "Add Selection to Next Find Match" (`Cmd+D`): select the word
    /// under the cursor, then grow the multi-cursor one occurrence per press.
    pub(super) fn start_select_next_occurrence(&mut self) {
        if self.editor.has_non_text_view() {
            return;
        }
        let n = self.editor.select_next_occurrence();
        if n == 0 {
            self.status = String::from("No symbol under cursor");
        } else if n > 1 {
            self.status = format!("Selected {n} occurrences (type to replace, Esc to cancel)");
        }
    }

    /// VS Code "Delete Line" (`Cmd+Shift+K`): delete the cursor's line, or
    /// every line a selection touches, yanking the removed text to the
    /// clipboard. Replaces the old `Cmd+d d` convenience, whose leader now
    /// belongs to Add Selection to Next Match.
    pub(super) fn delete_current_line(&mut self) {
        if self.editor.has_non_text_view() {
            return;
        }
        let yanked = self.editor.delete_caret_lines();
        let n = yanked.lines().count();
        let lines = if n == 1 { "line" } else { "lines" };
        self.status = if yanked.is_empty() {
            format!("Deleted {n} {lines}")
        } else {
            let landing = self.copy_where_pasted(&yanked);
            format!("Deleted {n} {lines}{}", landing.note())
        };
    }

    /// Kill from the caret to the end of its line, yanking the text to the
    /// clipboard (emacs `kill-line`). `Ctrl+K` in the editor on macOS and in
    /// vim mode; elsewhere `Ctrl+K` leads the `Cmd+K` chords (#843), and the
    /// palette's "Kill to End of Line" is the way here.
    pub(super) fn kill_to_end_of_line(&mut self) {
        if self.editor.has_non_text_view() {
            return;
        }
        let killed = self.editor.kill_to_eol();
        if !killed.is_empty() {
            let n = killed.chars().count();
            self.status = format!("Killed {n} chars{}", self.copy_where_pasted(&killed).note());
        }
    }

    /// Hand a paste to the pop-up that takes the keys, the way typing its
    /// characters would reach it: into the field of a pop-up that has one,
    /// at once and without the line breaks, and dropped by one that has
    /// none. True when a pop-up was open, so the paste never reaches the
    /// file, the shell or the panel the pop-up hides (#2665). The pop-ups
    /// are asked in the order `handle_key_inner` answers them, except that
    /// the input box and the four search pickers keep the order they had
    /// here. A paste is never replayed as keys: in a confirm, a typed `d`
    /// or `y` answers it.
    fn paste_into_popup(&mut self, s: &str) -> bool {
        let text: String = s.chars().filter(|c| !c.is_control()).collect();
        if self.pending_terminal_warning {
            return true;
        }
        if let Some(ui) = self.approval_ui.as_mut() {
            // The reason for refusing an edit, once `r` has opened it.
            if let Some(reason) = ui.reason.as_mut() {
                reason.push_str(&text);
            }
            return true;
        }
        if let Some(dialog) = self.connect_dialog.as_mut() {
            // A password, passphrase or code; ignored while none is asked.
            text.chars().for_each(|c| dialog.push_input_char(c));
            return true;
        }
        if self.shortcuts_modal.is_some() {
            return true;
        }
        if self.input_prompt.is_none()
            && let Some(ed) = self.settings_editor.as_mut()
        {
            let query = format!("{}{text}", ed.query);
            ed.set_query(query);
            return true;
        }
        if let Some(prompt) = self.input_prompt.as_mut() {
            text.chars().for_each(|c| prompt.push_char(c));
            return true;
        }
        if let Some(palette) = self.command_palette.as_mut() {
            text.chars().for_each(|c| palette.push_char(c));
            return true;
        }
        if let Some(picker) = self.go_to_symbol.as_mut() {
            text.chars().for_each(|c| picker.push_char(c));
            return true;
        }
        if let Some(picker) = self.workspace_symbols.as_mut() {
            text.chars().for_each(|c| picker.push_char(c));
            self.workspace_symbols_requery();
            return true;
        }
        if let Some(finder) = self.file_finder.as_mut() {
            text.chars().for_each(|c| finder.push_char(c));
            self.follow_quick_open_prefix();
            return true;
        }
        if self.process_picker.is_some() {
            return true;
        }
        if let Some(jump) = self.zoxide_jump.as_mut() {
            text.chars().for_each(|c| jump.push_char(c));
            self.refresh_zoxide_results();
            return true;
        }
        if let Some(history) = self.command_history_popup.as_mut() {
            text.chars().for_each(|c| history.push_char(c));
            self.refresh_command_history_results();
            return true;
        }
        if let Some(picker) = self.branch_picker.as_mut() {
            text.chars().for_each(|c| picker.push_char(c));
            return true;
        }
        if let Some(picker) = self.list_picker.as_mut() {
            text.chars().for_each(|c| picker.push_char(c));
            return true;
        }
        // The confirms answered before the single-line prompt.
        if self.pending_lossy_save.is_some()
            || self.pending_unsaved.is_some()
            || self.pending_replace_all.is_some()
            || self.pending_unsaved_scm.is_some()
            || self.pending_stash_drop.is_some()
            || self.pending_discard_all
            || self.pending_run_block.is_some()
        {
            return true;
        }
        if self.pending_terminal_paste.is_some() {
            // It holds the first paste, which this one neither replaces
            // nor slips past into the shell.
            self.status = String::from("Resolve the pending paste before pasting again");
            return true;
        }
        if self.pending_broadcast_enable {
            return true;
        }
        // New File, Rename and the other single-line prompts take it at the
        // caret, as the find bar does.
        if let Some(prompt) = self.prompt.as_mut() {
            prompt.edit(|t, at| crate::widgets::line_edit::insert_at(t, at, &text));
            return true;
        }
        // The confirms answered after it, then a right-click menu, which
        // takes every key while it is open and has no field (Codex).
        self.pending_local_open.is_some()
            || self.pending_discard.is_some()
            || self.pending_revert_hunk.is_some()
            || self.context_menu.is_some()
    }

    /// Flip native modal (vim) editing on or off. Driven by the global Cmd+E
    /// shortcut, so it can fire from any pane. Turning it off also dismisses
    /// any lingering `/` `?` search-match highlights, since the modal layer is
    /// the only place that clears them.
    pub(super) fn toggle_vim_mode(&mut self) {
        // The Vim modal layer is a bundled, toggleable extension: when disabled
        // in the Extensions panel, Cmd+E is inert (and any active session is
        // force-ended so a disable can't strand the editor in modal mode).
        if !self.is_extension_enabled("vim") {
            if self.vim.enabled {
                self.vim.toggle();
                self.end_vim_undo_groups();
            }
            self.status = String::from("Vim extension is disabled");
            return;
        }
        self.vim.toggle();
        // A change left open in Insert mode ends with the mode (#934).
        self.end_vim_undo_groups();
        if self.vim.enabled {
            self.status = String::from("vim mode on");
        } else {
            self.editor
                .set_search_highlight(None, crate::widgets::search::SearchOpts::default());
            self.status = String::from("vim mode off");
        }
        // Saved as the mode the next launch starts in (#1286). Under test
        // only into a config dir the test chose, never the developer's.
        self.vim_mode_pref = self.vim.enabled;
        if !cfg!(test) || self.config_dir != crate::paths::config_dir() {
            self.report_unsaved_setting(crate::prefs::save_vim_mode_in(
                &self.config_dir,
                self.vim.enabled,
            ));
        }
    }

    /// Follow the `vim_mode` pref (#1286) at launch and on a settings
    /// reload: Vim mode on when it is set and the `vim` extension is
    /// enabled. Only a change of the pref moves the live mode, so a reload
    /// for another setting leaves the mode, and Insert or Normal, as it is.
    pub(super) fn follow_vim_mode_pref(&mut self, want: bool) {
        if want == self.vim_mode_pref {
            return;
        }
        self.vim_mode_pref = want;
        let on = want && self.is_extension_enabled("vim");
        if on != self.vim.enabled {
            self.vim.toggle();
            self.end_vim_undo_groups();
            if !on {
                self.editor
                    .set_search_highlight(None, crate::widgets::search::SearchOpts::default());
            }
        }
    }

    /// Increment (`delta` 1) or decrement (`delta` -1) the number under the
    /// cursor, reporting in the status bar when there is nothing to bump so
    /// the keystroke never looks broken.
    pub(super) fn bump_number_under_cursor(&mut self, delta: i64) {
        if !self.editor_is_text() {
            return;
        }
        if !self.editor.bump_number(delta) {
            self.status = String::from("No number at or after the cursor on this line");
        }
    }

    pub(super) fn handle_editor_key(&mut self, key: KeyEvent) {
        // Inline find bar (Cmd+F / Ctrl+F) eats every key while open.
        if self.editor_find.is_some() {
            self.handle_editor_find_key(key);
            return;
        }
        // F7 / Shift+F7 in a buffer with merge conflicts: jump between the
        // blocks, the same chord the diff view uses for its hunks (VS Code's
        // "Go to Next/Previous Conflict"). Only claimed while conflicts
        // exist, so F7 keeps its normal meaning everywhere else.
        if matches!(key.code, KeyCode::F(7)) && !self.editor.conflicts().is_empty() {
            self.jump_conflict(key.modifiers.contains(KeyModifiers::SHIFT));
            return;
        }
        // F7 / Shift+F7 elsewhere: Go to Next / Previous Change over the
        // gutter's change bars (#1352), as the diff view walks its hunks.
        if matches!(key.code, KeyCode::F(7)) && self.editor.merge.is_none() {
            self.jump_editor_change(!key.modifiers.contains(KeyModifiers::SHIFT));
            return;
        }
        // Merge editor (#253): F7 hops the tracked Result regions (the
        // Result has no markers, so the arm above never claims it) and
        // Alt+Up/Down scrolls the source panes together. Every other key
        // falls through to the ordinary text path — the Result is a real
        // buffer.
        if self.editor.merge.is_some() {
            if matches!(key.code, KeyCode::F(7)) {
                self.merge_jump(key.modifiers.contains(KeyModifiers::SHIFT));
                return;
            }
            if key.modifiers.contains(KeyModifiers::ALT)
                && matches!(key.code, KeyCode::Up | KeyCode::Down)
            {
                let delta = if key.code == KeyCode::Up { -3 } else { 3 };
                if let Some(mv) = self.editor.merge.as_mut() {
                    mv.scroll_panes(delta);
                }
                return;
            }
        }
        if is_editor_find_key(key) {
            self.open_editor_find();
            return;
        }
        if is_editor_replace_key(key) {
            self.open_editor_replace();
            return;
        }
        // `.http`/`.rest` (#370): Cmd/Ctrl+Enter sends the request under
        // the caret, REST Client's own chord. Checked BEFORE the runnable
        // fence (#353), which claims the same chord: this arm is scoped to
        // request files, so the two compose — a `.http` file sends, and
        // every other file falls through to the fence path with its
        // meaning intact.
        if matches!(key.code, KeyCode::Enter)
            && key
                .modifiers
                .intersects(KeyModifiers::SUPER | KeyModifiers::CONTROL)
            && self
                .editor
                .path
                .as_deref()
                .is_some_and(crate::http_file::is_http_file)
        {
            self.send_http_request_under_caret();
            return;
        }
        // Runnable docs (#353): Cmd+Enter runs the fence under the caret.
        // Outside a runnable fence it falls through to Insert Line Below
        // (#1571).
        if is_run_fence_key(key) && self.focus == Pane::Editor && self.run_fence_at_cursor(false) {
            return;
        }
        // Markdown: Toggle Preview (Cmd/Ctrl+Shift+V, the VS Code default).
        if is_markdown_preview_key(key) {
            self.toggle_markdown_preview();
            return;
        }
        // While the rendered preview is up the buffer is not visible, so
        // navigation scrolls the preview and every other key is swallowed
        // (no invisible edits). Cmd+Shift+V above flips back to the source.
        if self.editor.markdown_preview.is_some() {
            // Copy Path / Copy Relative Path first: their chords are
            // Cmd+Opt+C and Cmd+Opt+Shift+C, which the looser copy-key
            // predicate below also matches. They are meaningful while a
            // preview is up (the file has a path either way), and this
            // block returns unconditionally, so they must be dispatched
            // here or they never run.
            if is_copy_path_key(key) {
                if let Some(path) = self.editor.path.clone() {
                    self.copy_path_to_clipboard(path);
                }
                return;
            }
            if is_copy_relative_path_key(key) {
                if let Some(path) = self.editor.path.clone() {
                    self.copy_relative_path_to_clipboard(path);
                }
                return;
            }
            // Close Tab (Cmd/Ctrl+W) for the same reason: the close-tab check
            // further down, above the diff / sheet / image guards, is never
            // reached from here, so a rendered Markdown, document or media
            // preview could not be closed from the keyboard (#2069).
            if is_close_tab_key(key) {
                self.request_close_tab(self.editor.active_index());
                return;
            }
            // Copy the rendered selection (#215): the preview swallows every
            // other key, so without this branch Cmd+C here never copies.
            if is_editor_copy_key(key) {
                self.copy_editor_selection();
                return;
            }
            if matches!(key.code, KeyCode::Esc)
                && let Some(md) = self.editor.markdown_preview.as_mut()
                && md.has_selection()
            {
                md.selection = None;
                md.dragging = false;
                return;
            }
            let page = self.editor.text_rows() as i32;
            match key.code {
                KeyCode::Up => {
                    self.editor.scroll_markdown_preview(-1);
                }
                KeyCode::Down => {
                    self.editor.scroll_markdown_preview(1);
                }
                KeyCode::PageUp => {
                    self.editor.scroll_markdown_preview(-page);
                }
                KeyCode::PageDown | KeyCode::Char(' ') => {
                    self.editor.scroll_markdown_preview(page);
                }
                KeyCode::Home => {
                    self.editor.scroll_markdown_preview(i16::MIN as i32);
                }
                // The render pass clamps to the wrapped height, so jumping
                // far past the end lands exactly on the last page.
                KeyCode::End => {
                    self.editor.scroll_markdown_preview(i16::MAX as i32);
                }
                _ => {}
            }
            return;
        }
        // Completion popup intercepts navigation / accept / dismiss keys
        // before normal editor handling. Any other key dismisses the popup
        // and falls through so the character lands in the buffer.
        if self.handle_completion_popup_key(key) {
            return;
        }
        // A snippet tab-stop session survives only plain typing, Backspace, and
        // Tab (which advances it). Any other key ends the session so Tab returns
        // to its normal indent role.
        if self.editor.snippet_active() && !snippet_key_continues(key) {
            self.editor.cancel_snippet();
        }
        // Esc closes the parameter-hints popup first (VS Code parity); a second
        // Esc then falls through to clear the selection / collapse cursors.
        if self.signature_help_popup.is_some() && matches!(key.code, KeyCode::Esc) {
            self.dismiss_signature_help();
            return;
        }
        // F4: focus the active file's next navigator comment box;
        // Shift+F4 ignores the nearest one.
        if matches!(key.code, KeyCode::F(4)) {
            if key.modifiers == KeyModifiers::SHIFT {
                self.ignore_focused_comment();
                return;
            }
            if key.modifiers.is_empty() {
                self.cycle_comment_box();
                return;
            }
        }
        if is_completion_trigger_key(key) {
            self.trigger_completion();
            return;
        }
        // Rename Symbol (F2) and Change All Occurrences (Cmd/Ctrl+F2) are only
        // meaningful on a text buffer, so they sit above the read-only diff /
        // sheet / image guards below. The sheet grid is editable and F2 is its
        // own "edit this cell" key (#1618), so there F2 falls through to it.
        if is_rename_symbol_key(key) && self.editor.sheet.is_none() {
            self.start_rename_symbol();
            return;
        }
        if is_change_all_occurrences_key(key) {
            self.start_change_all_occurrences();
            return;
        }
        if is_select_next_occurrence_key(key) {
            self.start_select_next_occurrence();
            return;
        }
        if is_select_all_occurrences_key(key) {
            self.select_all_occurrences();
            return;
        }
        if is_add_cursors_to_line_ends_key(key) {
            self.add_cursors_to_line_ends();
            return;
        }
        if is_expand_line_selection_key(key) {
            self.expand_line_selection();
            return;
        }
        if is_delete_line_key(key) {
            self.delete_current_line();
            return;
        }
        // VS Code "Reveal in Finder" (Cmd+Opt+R) for the active file. Works on
        // any tab backed by a real path (text, diff, sheet, image), so it sits
        // above the text-only guards. Local-macOS only, matching the Explorer
        // chord and the tab-menu entry; withheld on remote/headless sessions.
        if !self.is_remote && cfg!(target_os = "macos") && is_reveal_in_finder_key(key) {
            if let Some(path) = self.editor.path.clone() {
                self.reveal_in_finder(path);
            }
            return;
        }
        // VS Code "Copy Path" (Cmd+Opt+C): copy the active file's absolute path
        // to the clipboard. Works on any tab with a real path, local or remote;
        // a blank/untitled buffer is a no-op (the keystroke is still swallowed).
        if is_copy_path_key(key) {
            if let Some(path) = self.editor.path.clone() {
                self.copy_path_to_clipboard(path);
            }
            return;
        }
        // VS Code "Copy Relative Path" (Cmd+Opt+Shift+C): copy the active file's
        // path relative to the workspace root. Same path-or-no-op rule as Copy
        // Path; the keystroke is swallowed even on a blank/untitled buffer.
        if is_copy_relative_path_key(key) {
            if let Some(path) = self.editor.path.clone() {
                self.copy_relative_path_to_clipboard(path);
            }
            return;
        }
        // VS Code "Toggle Line Comment" (Cmd+/ / Ctrl+/), "Toggle Block
        // Comment" (Shift+Alt+A), and "View: Toggle Word Wrap" (Alt+Z). All
        // act on a text buffer, so they no-op on read-only diff / sheet /
        // image tabs (the keystroke is still swallowed). Each is also
        // reachable from the Command Palette, which guarantees parity on
        // terminals that don't deliver the Alt+letter chords.
        if is_toggle_line_comment_key(key) {
            // The palette's message too: a key that does nothing because the
            // language has no comment must say so (#1181); a blank line in
            // one that has does nothing quietly.
            if self.editor_is_text()
                && !self.editor.toggle_line_comment()
                && !self.editor.has_line_comment_syntax()
            {
                self.status = String::from("Toggle Line Comment: no comment for this language");
            }
            return;
        }
        if is_toggle_block_comment_key(key) {
            if self.editor_is_text() {
                self.editor.toggle_block_comment();
            }
            return;
        }
        if is_toggle_wrap_key(key) {
            if self.editor_is_text() {
                self.editor.toggle_wrap();
            }
            return;
        }
        // Alt+O: C/C++: Switch Header/Source (#1360), as VS Code's clangd
        // extension binds it. Other files keep the chord.
        if is_switch_header_source_key(key)
            && self
                .editor
                .path
                .as_deref()
                .is_some_and(crate::header_source::is_c_family)
        {
            self.switch_header_source();
            return;
        }
        // VS Code "Go to Bracket" (Cmd+Shift+\): jump the cursor to the
        // matching bracket. Also reachable from the Command Palette.
        if is_goto_bracket_key(key) {
            if self.editor_is_text() {
                self.editor.jump_to_matching_bracket();
            }
            return;
        }
        // VS Code "Select to Bracket" (Cmd+Opt+\): select the region between
        // the matching brackets, including the brackets.
        if is_select_to_bracket_key(key) {
            if self.editor_is_text() {
                self.editor.select_to_matching_bracket();
            }
            return;
        }
        // VS Code "Go Back" (Ctrl+-): the keyboard twin of the
        // Ctrl+Shift+click chord, so navigation history is reachable
        // without depending on the host terminal's mouse delivery (#31).
        if is_navigate_forward_key(key) {
            self.nav_forward();
            return;
        }
        if is_navigate_back_key(key) {
            self.nav_back();
            return;
        }
        // VS Code "Transpose Characters around the Cursor" (Ctrl+T).
        if is_transpose_key(key) {
            if self.editor_is_text() {
                self.editor.transpose_chars();
            }
            return;
        }
        // VS Code "Convert Indentation to Spaces" (Cmd+Opt+Shift+S).
        if is_indentation_to_spaces_key(key) {
            if self.editor_is_text() {
                self.editor.indentation_to_spaces();
                self.status = String::from("Converted indentation to spaces");
            }
            return;
        }
        // VS Code "Convert Indentation to Tabs" (Cmd+Opt+Shift+T).
        if is_indentation_to_tabs_key(key) {
            if self.editor_is_text() {
                self.editor.indentation_to_tabs();
                self.status = String::from("Converted indentation to tabs");
            }
            return;
        }
        // VS Code's `files.trimFinalNewlines`, as a command (Cmd+Opt+Shift+N).
        if is_trim_final_newlines_key(key) {
            if self.editor_is_text() && self.editor.trim_final_newlines() {
                self.status = String::from("Trimmed final newlines");
            }
            return;
        }
        // Bookmarks: toggle on the cursor's line, then walk them with
        // Cmd+Opt+. / Cmd+Opt+, (VS Code's Bookmarks extension, nvim marks).
        if is_toggle_bookmark_key(key) {
            self.toggle_bookmark();
            return;
        }
        if is_next_bookmark_key(key) {
            self.goto_bookmark(true);
            return;
        }
        if is_prev_bookmark_key(key) {
            self.goto_bookmark(false);
            return;
        }
        if is_clear_bookmarks_key(key) {
            self.clear_bookmarks();
            return;
        }
        // Formerly palette-only editor commands, now each on a chord so none
        // ships without an accelerator (croft tenet: everything has a shortcut).
        if is_join_lines_key(key) {
            if self.editor_is_text() {
                self.editor.join_lines();
            }
            return;
        }
        if is_transform_upper_key(key) {
            if self.editor_is_text() {
                self.editor
                    .transform_selection_case(crate::widgets::editor::CaseTransform::Upper);
            }
            return;
        }
        if is_transform_lower_key(key) {
            if self.editor_is_text() {
                self.editor
                    .transform_selection_case(crate::widgets::editor::CaseTransform::Lower);
            }
            return;
        }
        if is_sort_lines_asc_key(key) {
            if self.editor_is_text() {
                self.editor.sort_lines(true);
            }
            return;
        }
        if is_sort_lines_desc_key(key) {
            if self.editor_is_text() {
                self.editor.sort_lines(false);
            }
            return;
        }
        if is_trim_trailing_whitespace_key(key) {
            if self.editor_is_text() && self.editor.trim_trailing_whitespace() {
                self.status = String::from("Trimmed trailing whitespace");
            }
            return;
        }
        if is_increment_number_key(key) {
            self.bump_number_under_cursor(1);
            return;
        }
        if is_decrement_number_key(key) {
            self.bump_number_under_cursor(-1);
            return;
        }
        if is_emmet_expand_key(key) {
            self.expand_emmet_abbreviation();
            return;
        }
        // VS Code "Format Document" (Cmd+Opt+Shift+F): reformat the whole buffer
        // through the language server. No-op on read-only diff / sheet / image.
        if is_format_document_key(key) {
            if self.editor_is_text() {
                self.start_format_document();
            }
            return;
        }
        // VS Code "Quick Fix" (Cmd+. / Ctrl+.): code actions at the cursor.
        if is_quick_fix_key(key) {
            if self.editor_is_text() {
                self.start_code_action();
            }
            return;
        }
        // Rebase todo (#620): single-key actions on commit lines.
        if self.rebase_todo_key(key) {
            return;
        }
        // Inline suggestion (#607): Tab accepts, Esc dismisses, Ctrl+Right
        // and Ctrl+Down take a word or a line of it (#1625).
        if self.inline_suggestion_key(key) {
            return;
        }
        // Search Editor (#615): Enter or F12 on a result row opens the match;
        // anywhere else both keep their usual meaning.
        if (key.code == KeyCode::Enter && key.modifiers.is_empty() || is_go_to_definition_key(key))
            && self.open_search_editor_result()
        {
            return;
        }
        // Go to Definition (F12) / References (Shift+F12) / Type Definition
        // (Ctrl+F12) / Implementations (Cmd+F12) / Declaration (Ctrl+Shift+F12),
        // the VS Code F12-family bindings, also need a real text buffer. All are
        // no-ops on read-only diff / sheet / image tabs; the keystroke is still
        // swallowed so it never leaks into the buffer.
        if is_peek_definition_key(key) {
            if self.editor.diff.is_none()
                && self.editor.sheet.is_none()
                && self.editor.image.is_none()
            {
                self.peek_definition_at_cursor();
            }
            return;
        }
        if is_go_to_definition_key(key) {
            if self.editor.diff.is_none()
                && self.editor.sheet.is_none()
                && self.editor.image.is_none()
            {
                self.request_definition_at_cursor();
            }
            return;
        }
        if is_go_to_declaration_key(key) {
            if self.editor.diff.is_none()
                && self.editor.sheet.is_none()
                && self.editor.image.is_none()
            {
                self.request_declaration_at_cursor();
            }
            return;
        }
        if is_go_to_type_definition_key(key) {
            if self.editor.diff.is_none()
                && self.editor.sheet.is_none()
                && self.editor.image.is_none()
            {
                self.request_type_definition_at_cursor();
            }
            return;
        }
        if is_go_to_implementation_key(key) {
            if self.editor.diff.is_none()
                && self.editor.sheet.is_none()
                && self.editor.image.is_none()
            {
                self.request_implementation_at_cursor();
            }
            return;
        }
        if is_peek_references_key(key) {
            if self.editor.diff.is_none()
                && self.editor.sheet.is_none()
                && self.editor.image.is_none()
            {
                self.peek_references_at_cursor();
            }
            return;
        }
        if is_go_to_references_key(key) {
            if self.editor.diff.is_none()
                && self.editor.sheet.is_none()
                && self.editor.image.is_none()
            {
                self.request_references_at_cursor();
            }
            return;
        }
        // Column (box) selection from the keyboard (#1560): VS Code's
        // Cmd+Shift+Opt (Ctrl+Shift+Alt) arrows and PageUp/PageDown, and
        // plain Shift+arrows while Column Selection Mode is on. Ahead of the
        // multi-cursor collapse below, since the box is carets it keeps
        // growing, and of Add Cursor, which used to take the Up/Down chords
        // and leave one caret.
        if let Some((rows, cols)) = self.column_select_key(key) {
            self.editor.column_select(rows, cols);
            return;
        }
        // While multi-cursor mode is live, printable typing / backspace /
        // delete fan out to every caret and Esc collapses back to one cursor.
        // Any other key collapses the carets and falls through to normal
        // single-cursor handling (e.g. an arrow moves just the primary).
        if self.editor.has_multi_cursor() {
            match key.code {
                KeyCode::Esc => {
                    self.editor.collapse_carets();
                    self.status = String::from("Cursors collapsed");
                    return;
                }
                KeyCode::Backspace => {
                    self.editor.multi_backspace();
                    return;
                }
                KeyCode::Delete => {
                    self.editor.multi_delete_forward();
                    return;
                }
                KeyCode::Char(c)
                    if !key.modifiers.contains(KeyModifiers::CONTROL)
                        && !key.modifiers.contains(KeyModifiers::ALT)
                        && !key.modifiers.contains(KeyModifiers::SUPER) =>
                {
                    self.editor.multi_insert_char(c);
                    return;
                }
                _ => self.editor.collapse_carets(),
            }
        }
        // Close-tab (Cmd/Ctrl+W) applies to every tab type, so it sits above
        // the read-only diff / sheet / image guards below. Those guards each
        // short-circuit to a view-specific handler that has no close branch,
        // so without this hoist Cmd+W is silently swallowed on a diff, sheet,
        // or image tab and the tab can never be closed from the keyboard.
        if is_close_tab_key(key) {
            self.request_close_tab(self.editor.active_index());
            return;
        }
        if self.editor.diff.is_some() {
            self.handle_diff_key(key);
            return;
        }
        if self.editor.sheet.is_some() {
            self.handle_sheet_key(key);
            return;
        }
        if self.editor.hex.is_some() {
            self.handle_hex_key(key);
            return;
        }
        if self.editor.archive.is_some() {
            self.handle_archive_key(key);
            return;
        }
        if self.editor.pr_review.is_some() {
            self.handle_pr_review_key(key);
            return;
        }
        if self.editor.fleet.is_some() {
            self.handle_fleet_key(key);
            return;
        }
        if self.editor.sarif.is_some() {
            self.handle_sarif_key(key);
            self.refresh_sarif_preview();
            return;
        }
        if self.editor.log.is_some() && self.handle_log_key(key) {
            return;
        }
        // Image preview tabs are read-only. PDF tabs page with every
        // navigation key (arrows, PageUp/PageDown, Space, Home/End) and with
        // the wheel; everything else is swallowed.
        if self.editor.image.is_some() {
            match key.code {
                KeyCode::Right | KeyCode::PageDown | KeyCode::Down | KeyCode::Char(' ') => {
                    self.step_pdf_page(1);
                }
                KeyCode::Left | KeyCode::PageUp | KeyCode::Up => {
                    self.step_pdf_page(-1);
                }
                KeyCode::Home => self.jump_pdf_page(1),
                KeyCode::End => self.jump_pdf_page(u32::MAX),
                _ => {}
            }
            return;
        }
        // When modal editing is on it fully owns the editor pane and the
        // always-on `editor_vim_chord` convenience layer is bypassed. A
        // PassThrough means the key is not claimed by vim (Insert-mode typing,
        // or any Cmd/Ctrl shortcut in Normal mode) and falls through to the
        // editor's normal handling below.
        if self.vim.enabled {
            match self.vim.on_key(key) {
                crate::vim::VimKeyResult::Consumed(actions) => {
                    for action in actions {
                        self.apply_vim_action(action);
                    }
                    return;
                }
                crate::vim::VimKeyResult::PassThrough => {}
            }
        } else if self.handle_editor_vim_chord(key) {
            return;
        }
        if is_editor_line_home_key(key) {
            self.editor.clear_selection();
            self.editor.home_line();
            return;
        }
        if is_editor_line_end_key(key) {
            self.editor.clear_selection();
            self.editor.end_line();
            return;
        }
        if is_editor_kill_to_eol_key(key) {
            self.kill_to_end_of_line();
            return;
        }
        if is_editor_kill_to_bol_key(key) {
            let killed = self.editor.kill_to_bol();
            if !killed.is_empty() {
                let n = killed.chars().count();
                self.status = format!("Killed {n} chars{}", self.copy_where_pasted(&killed).note());
            }
            return;
        }
        // Insert Line Below (#1571): VS Code's `Cmd+Enter` (`Ctrl+Enter` off
        // macOS), with `Cmd+O` kept as an alias. A Markdown fence under the
        // caret ran above, so here it only opens a line.
        if is_editor_open_line_below_key(key) || is_run_fence_key(key) {
            self.editor.open_line_below();
            self.status = String::from("Opened line below");
            return;
        }
        if is_editor_open_line_above_key(key) {
            self.editor.open_line_above();
            self.status = String::from("Opened line above");
            return;
        }
        // Clipboard gestures take precedence over text input. They never
        // conflict with normal typing (Ctrl/Cmd + C/X/A) so the order is
        // safe even when the user is in the middle of editing.
        if is_editor_copy_key(key) {
            self.copy_editor_selection();
            return;
        }
        if is_editor_cut_key(key) {
            self.cut_editor_selection();
            return;
        }
        if is_editor_paste_key(key) {
            let text = self.clipboard_text();
            self.paste_clipboard_into_editor(text.as_deref());
            return;
        }
        if is_editor_select_all_key(key) {
            self.editor.select_all();
            self.status = format!(
                "Selected {} chars",
                self.editor.selection_text().chars().count()
            );
            return;
        }
        if is_editor_undo_key(key) {
            if self.editor.undo() {
                self.status = String::from("Undo");
            } else {
                self.status = String::from("Nothing to undo");
            }
            return;
        }
        if is_editor_redo_key(key) {
            if self.editor.redo() {
                self.status = String::from("Redo");
            } else {
                self.status = String::from("Nothing to redo");
            }
            return;
        }
        if let Some(idx) = jump_to_tab_index(key) {
            if self.editor.select(idx) {
                self.sync_open_file_poll_mtime();
                self.status = format!("Tab {}", idx + 1);
            }
            return;
        }
        if matches!(key.code, KeyCode::Esc) && self.editor.selection.is_some() {
            self.editor.clear_selection();
            return;
        }

        // Shift+<motion> extends selection in the motion's direction.
        let shift = key.modifiers.contains(KeyModifiers::SHIFT);
        let is_motion = matches!(
            key.code,
            KeyCode::Up
                | KeyCode::Down
                | KeyCode::Left
                | KeyCode::Right
                | KeyCode::Home
                | KeyCode::End
                | KeyCode::PageUp
                | KeyCode::PageDown
        );
        let alt = key.modifiers.contains(KeyModifiers::ALT);
        // The command modifier: Cmd (SUPER) on macOS, Ctrl on Linux / Termux.
        let cmd = key.modifiers.contains(KeyModifiers::SUPER)
            || key.modifiers.contains(KeyModifiers::CONTROL);
        // The word modifier for ←/→, Backspace and Delete: Option (Alt) on
        // macOS, Ctrl on Linux as in VS Code there (#909). Ctrl with Cmd
        // held is not it: Cmd with these keys is no word chord on macOS.
        let word = alt
            || key.modifiers.contains(KeyModifiers::CONTROL)
                && !key.modifiers.contains(KeyModifiers::SUPER);
        // VS Code "Add Cursor Above/Below" (Cmd+Opt+Up / Cmd+Opt+Down). Must
        // come before the plain-Alt move-line check so the cmd+alt combo is
        // routed here, not there.
        if cmd && alt && !shift && matches!(key.code, KeyCode::Up | KeyCode::Down) {
            match key.code {
                KeyCode::Up => self.editor.add_cursor_above(),
                KeyCode::Down => self.editor.add_cursor_below(),
                _ => unreachable!(),
            }
            return;
        }
        if shift && alt && matches!(key.code, KeyCode::Up | KeyCode::Down) {
            match key.code {
                KeyCode::Up => self.editor.duplicate_lines_up(),
                KeyCode::Down => self.editor.duplicate_lines_down(),
                _ => unreachable!(),
            }
            return;
        }
        // Expand / Shrink Selection (#254): Shift+Alt+Right/Left, VS Code's
        // smart-select chords. This deliberately claims what used to be
        // word-wise selection extension — the same collision VS Code
        // resolves the same way.
        if shift && alt && !cmd && matches!(key.code, KeyCode::Left | KeyCode::Right) {
            if key.code == KeyCode::Right {
                self.expand_selection();
            } else {
                self.shrink_selection();
            }
            return;
        }
        // VS Code "Move Line Up/Down" (Alt+Up / Alt+Down, no Shift, no Cmd).
        if alt && !shift && !cmd && matches!(key.code, KeyCode::Up | KeyCode::Down) {
            match key.code {
                KeyCode::Up => self.editor.move_lines_up(),
                KeyCode::Down => self.editor.move_lines_down(),
                _ => unreachable!(),
            }
            return;
        }
        if is_motion && shift {
            if self.editor.selection.is_none() {
                self.editor.start_selection_at_cursor();
            }
            match key.code {
                KeyCode::Up => self.editor.arrow_up(),
                KeyCode::Down => self.editor.arrow_down(),
                KeyCode::Left if word => self.editor.move_word_left(),
                KeyCode::Right if word => self.editor.move_word_right(),
                KeyCode::Left => self.editor.move_left(),
                KeyCode::Right => self.editor.move_right(),
                KeyCode::Home if cmd => self.editor.cursor_top(),
                KeyCode::End if cmd => self.editor.cursor_bottom(),
                KeyCode::Home => self.editor.home_key(),
                KeyCode::End => self.editor.end_key(),
                KeyCode::PageUp => self.editor.page_up_one_screen(),
                KeyCode::PageDown => self.editor.page_down_one_screen(),
                _ => {}
            }
            self.editor.extend_selection_to_cursor();
            self.editor.ensure_cursor_col_visible();
            return;
        }
        if is_motion {
            // Plain motion clears any prior selection (VS Code / Sublime
            // convention: arrows without Shift collapse the selection).
            self.editor.clear_selection();
        }

        match key.code {
            KeyCode::Up => self.editor.arrow_up(),
            KeyCode::Down => self.editor.arrow_down(),
            KeyCode::Left if word => self.editor.move_word_left(),
            KeyCode::Right if word => self.editor.move_word_right(),
            KeyCode::Left => self.editor.move_left(),
            KeyCode::Right => self.editor.move_right(),
            KeyCode::PageUp => self.editor.page_up_one_screen(),
            KeyCode::PageDown => self.editor.page_down_one_screen(),
            KeyCode::Home if cmd => self.editor.cursor_top(),
            KeyCode::End if cmd => self.editor.cursor_bottom(),
            KeyCode::Home => self.editor.home_key(),
            KeyCode::End => self.editor.end_key(),
            KeyCode::Backspace => {
                if word {
                    self.editor.delete_word_left();
                } else {
                    self.editor.backspace();
                }
                self.note_incomplete_completion_edit();
            }
            KeyCode::Delete if word => self.editor.delete_word_right(),
            KeyCode::Delete => self.editor.delete_forward(),
            // Insert flips between insert and overwrite (Replace) typing.
            KeyCode::Insert if !shift && !cmd && !alt && !word => self.toggle_overwrite_mode(),
            KeyCode::Enter => self.editor.insert_newline(),
            // Tab advances a live snippet, else expands a snippet whose prefix
            // was just typed, else indents (whole block for a multi-line
            // selection, otherwise to the next tab stop).
            KeyCode::Tab => self.handle_editor_tab(),
            // Shift+Tab arrives as BackTab. Outdent the current line, or every
            // line a selection touches, mirroring VS Code's Shift+Tab.
            KeyCode::BackTab => self.editor.dedent_lines(),
            KeyCode::Char(c)
                if !key.modifiers.contains(KeyModifiers::CONTROL)
                    && !key.modifiers.contains(KeyModifiers::ALT)
                    && !key.modifiers.contains(KeyModifiers::SUPER) =>
            {
                self.type_char_in_editor(c);
                // With an incomplete list pending but none of it on screen,
                // typing on still re-asks (#1529).
                self.note_incomplete_completion_edit();
                // The server's trigger characters, and with quick
                // suggestions a word begun, open the list (#929).
                self.note_completion_typed(c);
                // Parameter hints: `(` / `,` open or advance a call. Closing
                // (typing `)`, moving away, deleting) is handled by the tick's
                // re-query, which also covers nested calls.
                if is_signature_help_trigger(c) {
                    self.trigger_signature_help();
                }
            }
            _ => {}
        }
        // Home, End, typing, Backspace, Delete and Enter move the caret
        // sideways too; only ←/→ pulled the view along, so End on a wide
        // line or typing past the edge left the caret off-screen (#1215).
        self.editor.ensure_cursor_col_visible();
    }

    /// Vim-style chord layer for the editor: `cmd+gg` jumps to top, `cmd+G`
    /// jumps to bottom, `cmd+yy` yanks a line. Counts go between the chord
    /// start and the completion key (`cmd+g 12 g` jumps to line 12), and
    /// Enter completes a `cmd+g` holding one, so VS Code's Go to Line
    /// (`ctrl+g 12 Enter`) lands there too (#902). There is no `cmd+dd`:
    /// `cmd+d` is Add Selection to Next Match, and Delete Line moved to
    /// `cmd+shift+k`.
    /// Returns true when the key was consumed; false means the caller
    /// should continue with normal editor handling.
    pub(super) fn handle_editor_vim_chord(&mut self, key: KeyEvent) -> bool {
        if is_vim_goto_bottom(key) {
            let count = self.editor_vim_chord.count;
            self.editor_vim_chord.reset();
            if count > 0 {
                self.editor.goto_line(count);
                self.status = format!("Line {count}");
            } else {
                self.editor.goto_bottom();
                self.status = String::from("Bottom of file");
            }
            return true;
        }

        let count_pending = self.editor_vim_chord.count > 0;
        let op_pending = self.editor_vim_chord.op != VimOp::None;

        if (op_pending || count_pending)
            && let Some(d) = chord_digit_value(key)
        {
            self.editor_vim_chord.count = self
                .editor_vim_chord
                .count
                .saturating_mul(10)
                .saturating_add(d);
            let op = match self.editor_vim_chord.op {
                VimOp::G => 'g',
                VimOp::Y => 'y',
                VimOp::None => ' ',
            };
            self.status = chord_status_text(op, self.editor_vim_chord.count);
            return true;
        }

        if !op_pending {
            if is_vim_chord_g(key) {
                self.editor_vim_chord.op = VimOp::G;
                self.status = chord_status_text('g', self.editor_vim_chord.count);
                return true;
            }
            if is_vim_chord_y(key) {
                self.editor_vim_chord.op = VimOp::Y;
                self.status = chord_status_text('y', self.editor_vim_chord.count);
                return true;
            }
            if !count_pending {
                if let Some(d) = cmd_only_digit_value(key) {
                    self.editor_vim_chord.count = d;
                    self.status = chord_status_text(' ', self.editor_vim_chord.count);
                    return true;
                }
                return false;
            }
            return self.cancel_editor_vim_chord(key);
        }

        let completes = match self.editor_vim_chord.op {
            VimOp::G => {
                is_plain_letter(key, 'g')
                    || is_vim_chord_g(key)
                    || (count_pending && key.code == KeyCode::Enter && key.modifiers.is_empty())
            }
            VimOp::Y => is_plain_letter(key, 'y') || is_vim_chord_y(key),
            VimOp::None => false,
        };

        if completes {
            let count = self.editor_vim_chord.count;
            match self.editor_vim_chord.op {
                VimOp::G => {
                    if count > 0 {
                        self.editor.goto_line(count);
                        self.status = format!("Line {count}");
                    } else {
                        self.editor.goto_top();
                        self.status = String::from("Top of file");
                    }
                }
                VimOp::Y => {
                    let n = count.max(1);
                    let yanked = self.editor.yank_lines(n);
                    let lines = if n == 1 { "line" } else { "lines" };
                    self.status = if yanked.is_empty() {
                        format!("Yanked {n} {lines}")
                    } else {
                        let landing = self.copy_where_pasted(&yanked);
                        format!("Yanked {n} {lines}{}", landing.note())
                    };
                }
                VimOp::None => {}
            }
            self.editor_vim_chord.reset();
            return true;
        }

        self.cancel_editor_vim_chord(key)
    }

    /// Drop the pending chord on a key that completes none, returning whether
    /// that key is consumed. It keeps its normal meaning only when nothing but
    /// the leader was typed: after a count the digits were swallowed, so the
    /// last key alone would edit the buffer with a fragment of what was typed
    /// (`cmd+g 25 Tab` indenting the line). Esc only ever cancels (#902).
    pub(super) fn cancel_editor_vim_chord(&mut self, key: KeyEvent) -> bool {
        let consumed = self.editor_vim_chord.count > 0 || key.code == KeyCode::Esc;
        self.editor_vim_chord.reset();
        self.status = String::from("Chord cancelled");
        consumed
    }

    /// End the vim change's undo group (#934): on the active editor, which
    /// also starts the next edit's own step, and on whichever other tab or
    /// editor group the change was entered on.
    pub(super) fn end_vim_undo_groups(&mut self) {
        self.editor.end_undo_group();
        for group in self.editor_layout.all_groups_mut(&mut self.editor) {
            group.end_open_undo_groups();
        }
    }

    /// Apply one resolved vim intent to the editor. The vim state machine has
    /// already advanced its own mode; this only mutates the buffer/cursor.
    pub(super) fn apply_vim_action(&mut self, action: crate::vim::VimAction) {
        use crate::vim::{Op, Target, VimAction};
        // A change runs from the command that enters Insert to the next vim
        // command, the `Esc` that leaves it: the operator's delete, the line
        // `o` opens and the typed text undo as one step, as in Vim (#934).
        self.end_vim_undo_groups();
        if matches!(
            action,
            VimAction::Insert(_)
                | VimAction::Operate { op: Op::Change, .. }
                | VimAction::VisualOperate(Op::Change)
        ) {
            self.editor.begin_undo_group();
        }
        match action {
            VimAction::Move(motion, count) => {
                self.vim_apply_motion(motion, count);
                self.vim_sync_visual_selection();
            }
            VimAction::Operate { op, target, count } => match target {
                Target::Lines => self.vim_operate_lines(op, self.editor.cursor_row, count),
                Target::Object(obj) => self.vim_operate_textobject(op, obj),
                Target::Motion(m) => self.vim_operate_motion(op, m, count),
            },
            VimAction::DeleteChar(count) => self.vim_delete_chars(count),
            VimAction::Insert(at) => self.vim_enter_insert(at),
            VimAction::Paste(at, count) => self.vim_paste(at, count),
            VimAction::Undo => {
                self.status = if self.editor.undo() {
                    String::from("Undo")
                } else {
                    String::from("Nothing to undo")
                };
                // The step an operator opened holds the selection it acted
                // on; Normal mode shows none, and `x` must not delete it.
                self.editor.clear_selection();
            }
            VimAction::Redo => {
                self.status = if self.editor.redo() {
                    String::from("Redo")
                } else {
                    String::from("Nothing to redo")
                };
                self.editor.clear_selection();
            }
            VimAction::EnterVisual { line } => {
                self.editor.break_undo_coalescing();
                self.vim_visual_line = line;
                self.vim
                    .set_visual_anchor(self.editor.cursor_row, self.editor.cursor_col);
                self.editor.start_selection_at_cursor();
                self.status = String::from(if line {
                    "-- VISUAL LINE --"
                } else {
                    "-- VISUAL --"
                });
            }
            VimAction::ExitVisual => {
                self.editor.clear_selection();
                self.vim_visual_line = false;
                self.status.clear();
            }
            VimAction::VisualOperate(op) => self.vim_visual_operate(op),
            VimAction::ExitInsert => {
                if self.editor.cursor_col > 0 {
                    self.editor.cursor_col -= 1;
                }
                self.status.clear();
            }
            VimAction::RunEx(cmd) => self.vim_run_ex(&cmd),
            VimAction::Search(dir, term) => self.vim_search(dir, &term),
            VimAction::ClearPending => {
                self.editor.clear_selection();
                self.vim_visual_line = false;
            }
            // `q{a-z}` starts, a bare `q` stops. The vim machine reports the
            // gesture; the recording itself lives on App so a macro recorded
            // in vim mode replays from the palette and vice versa (#255).
            // Recording control is inert during replay. `macro_replaying`
            // gates capture, not dispatch, so without this a replayed `q`
            // would reach here and leave the user silently recording after
            // the replay returned — the class of command the issue's
            // exclusion list exists for.
            VimAction::MacroRecord(_) | VimAction::MacroReplay(..) if self.macro_replaying => {}
            VimAction::MacroRecord(register) => match register {
                // A register letter STARTS; a bare `q` stops. The app owns
                // the recording state, so vim never has to track it.
                Some(r) if self.macro_recording.is_none() => self.start_macro_recording(Some(r)),
                _ => self.stop_macro_recording(),
            },
            VimAction::MacroReplay(register, count) => match register {
                Some(r) => self.replay_macro_register(r, count),
                None => self.replay_last_macro(count),
            },
            VimAction::Unsupported(what) => {
                self.status = format!("{what} is not supported in vim mode");
            }
        }
    }

    pub(super) fn vim_line_len(&self, row: usize) -> usize {
        self.editor
            .lines
            .get(row)
            .map(|l| l.chars().count())
            .unwrap_or(0)
    }

    pub(super) fn vim_first_non_blank(&self, row: usize) -> usize {
        self.editor
            .lines
            .get(row)
            .map(|l| l.chars().take_while(|c| c.is_whitespace()).count())
            .unwrap_or(0)
    }

    pub(super) fn vim_apply_motion(&mut self, motion: crate::vim::Motion, count: usize) {
        use crate::vim::Motion;
        let n = count.max(1);
        match motion {
            Motion::Left => {
                self.editor.cursor_col = self.editor.cursor_col.saturating_sub(n);
            }
            Motion::Right => {
                let len = self.vim_line_len(self.editor.cursor_row);
                self.editor.cursor_col = (self.editor.cursor_col + n).min(len);
            }
            Motion::Up => {
                for _ in 0..n {
                    self.editor.move_up();
                }
            }
            Motion::Down => {
                for _ in 0..n {
                    self.editor.move_down();
                }
            }
            Motion::WordForward => {
                for _ in 0..n {
                    self.vim_word_forward();
                }
            }
            Motion::WordBackward => {
                for _ in 0..n {
                    self.vim_word_backward();
                }
            }
            Motion::WordEnd => {
                for _ in 0..n {
                    self.vim_word_end();
                }
            }
            Motion::LineStart => self.editor.cursor_col = 0,
            Motion::FirstNonBlank => {
                self.editor.cursor_col = self.vim_first_non_blank(self.editor.cursor_row);
            }
            Motion::LineEnd => {
                self.editor.cursor_col = self.vim_line_len(self.editor.cursor_row);
            }
            Motion::FileStart => self.editor.goto_top(),
            Motion::FileEnd => self.editor.goto_bottom(),
            Motion::GotoLine(line) => self.editor.goto_line(line),
            Motion::Find(kind, ch) => {
                self.vim_last_find = Some((kind, ch));
                self.vim_find_char(kind, ch, n);
            }
            Motion::RepeatFind => {
                if let Some((kind, ch)) = self.vim_last_find {
                    self.vim_find_char(kind, ch, n);
                }
            }
            Motion::RepeatFindRev => {
                if let Some((kind, ch)) = self.vim_last_find {
                    self.vim_find_char(reverse_find(kind), ch, n);
                }
            }
        }
        self.editor.ensure_cursor_col_visible();
    }

    pub(super) fn vim_find_char(&mut self, kind: crate::vim::FindKind, ch: char, count: usize) {
        use crate::vim::FindKind;
        let row = self.editor.cursor_row;
        let Some(line) = self.editor.lines.get(row) else {
            return;
        };
        let chars: Vec<char> = line.chars().collect();
        let mut col = self.editor.cursor_col;
        for _ in 0..count.max(1) {
            match kind {
                FindKind::CharForward => match (col + 1..chars.len()).find(|&i| chars[i] == ch) {
                    Some(idx) => col = idx,
                    None => return,
                },
                FindKind::TillForward => match (col + 1..chars.len()).find(|&i| chars[i] == ch) {
                    Some(idx) if idx > 0 => col = idx - 1,
                    _ => return,
                },
                FindKind::CharBackward => match (0..col).rev().find(|&i| chars[i] == ch) {
                    Some(idx) => col = idx,
                    None => return,
                },
                FindKind::TillBackward => match (0..col).rev().find(|&i| chars[i] == ch) {
                    Some(idx) => col = idx + 1,
                    None => return,
                },
            }
        }
        self.editor.cursor_col = col;
    }

    /// Character class for vim word motions: 0 = blank (or past line end),
    /// 1 = keyword (alphanumeric/underscore), 2 = punctuation. A `w`/`b`/`e`
    /// word is a maximal run of one non-blank class.
    pub(super) fn vim_class_at(&self, row: usize, col: usize) -> u8 {
        match self.editor.lines.get(row).and_then(|l| l.chars().nth(col)) {
            None => 0,
            Some(c) if c.is_whitespace() => 0,
            Some(c) if c.is_alphanumeric() || c == '_' => 1,
            Some(_) => 2,
        }
    }

    pub(super) fn vim_next_pos(&self, row: usize, col: usize) -> Option<(usize, usize)> {
        if col < self.vim_line_len(row) {
            Some((row, col + 1))
        } else if row + 1 < self.editor.lines.len() {
            Some((row + 1, 0))
        } else {
            None
        }
    }

    pub(super) fn vim_prev_pos(&self, row: usize, col: usize) -> Option<(usize, usize)> {
        if col > 0 {
            Some((row, col - 1))
        } else if row > 0 {
            Some((row - 1, self.vim_line_len(row - 1)))
        } else {
            None
        }
    }

    pub(super) fn vim_word_forward(&mut self) {
        let mut row = self.editor.cursor_row;
        let mut col = self.editor.cursor_col;
        let start = self.vim_class_at(row, col);
        if start != 0 {
            while self.vim_class_at(row, col) == start {
                match self.vim_next_pos(row, col) {
                    Some((r, c)) => {
                        row = r;
                        col = c;
                    }
                    None => {
                        self.editor.cursor_row = row;
                        self.editor.cursor_col = col;
                        return;
                    }
                }
            }
        }
        while self.vim_class_at(row, col) == 0 {
            match self.vim_next_pos(row, col) {
                Some((r, c)) => {
                    row = r;
                    col = c;
                }
                None => break,
            }
        }
        self.editor.cursor_row = row;
        self.editor.cursor_col = col;
    }

    pub(super) fn vim_word_backward(&mut self) {
        let mut row = self.editor.cursor_row;
        let mut col = self.editor.cursor_col;
        let Some((r, c)) = self.vim_prev_pos(row, col) else {
            return;
        };
        row = r;
        col = c;
        while self.vim_class_at(row, col) == 0 {
            match self.vim_prev_pos(row, col) {
                Some((r, c)) => {
                    row = r;
                    col = c;
                }
                None => {
                    self.editor.cursor_row = row;
                    self.editor.cursor_col = col;
                    return;
                }
            }
        }
        let class = self.vim_class_at(row, col);
        while let Some((pr, pc)) = self.vim_prev_pos(row, col) {
            if self.vim_class_at(pr, pc) != class {
                break;
            }
            row = pr;
            col = pc;
        }
        self.editor.cursor_row = row;
        self.editor.cursor_col = col;
    }

    pub(super) fn vim_word_end(&mut self) {
        let mut row = self.editor.cursor_row;
        let mut col = self.editor.cursor_col;
        let Some((r, c)) = self.vim_next_pos(row, col) else {
            return;
        };
        row = r;
        col = c;
        while self.vim_class_at(row, col) == 0 {
            match self.vim_next_pos(row, col) {
                Some((r, c)) => {
                    row = r;
                    col = c;
                }
                None => {
                    self.editor.cursor_row = row;
                    self.editor.cursor_col = col;
                    return;
                }
            }
        }
        let class = self.vim_class_at(row, col);
        while let Some((nr, nc)) = self.vim_next_pos(row, col) {
            if self.vim_class_at(nr, nc) != class {
                break;
            }
            row = nr;
            col = nc;
        }
        self.editor.cursor_row = row;
        self.editor.cursor_col = col;
    }

    /// Where `{count}cw` from a non-blank ends: `e` `count` times, except
    /// that on a word's last char the first `e` stays put, so `cw` there
    /// changes that char rather than running to the next word's end.
    pub(super) fn vim_change_word_end(&mut self, count: usize) {
        let (row, col) = (self.editor.cursor_row, self.editor.cursor_col);
        let at_word_end = self.vim_class_at(row, col + 1) != self.vim_class_at(row, col);
        for _ in usize::from(at_word_end)..count.max(1) {
            self.vim_word_end();
        }
    }

    pub(super) fn vim_operate_lines(&mut self, op: crate::vim::Op, start_row: usize, count: usize) {
        use crate::vim::Op;
        // A symbol tab's operator stays inside its symbol (#369): `dgg`
        // from its second line reaches its first line, not the file's.
        let (lo, hi) = self
            .editor
            .symbol_clip()
            .unwrap_or((0, self.editor.lines.len().max(1)));
        let first = start_row.clamp(lo, hi - 1);
        let end = (start_row + count.max(1)).clamp(first + 1, hi);
        self.editor.cursor_row = first;
        let n = end - first;
        match op {
            Op::Delete => {
                let text = self.editor.delete_lines(n);
                let landing = self.copy_where_pasted(&text);
                self.status = format!("Deleted {n} line(s){}", landing.note());
            }
            Op::Yank => {
                let text = self.editor.yank_lines(n);
                let landing = self.copy_where_pasted(&text);
                self.status = format!("Yanked {n} line(s){}", landing.note());
            }
            Op::Change => {
                let text = self.editor.delete_lines(n);
                self.copy_where_pasted(&text);
                self.editor.open_line_above();
                self.vim.enter_insert_mode();
                self.status = String::from("-- INSERT --");
            }
        }
    }

    pub(super) fn vim_operate_motion(
        &mut self,
        op: crate::vim::Op,
        motion: crate::vim::Motion,
        count: usize,
    ) {
        if vim_motion_is_linewise(motion) {
            let (first, last) = self.vim_line_range_for_motion(motion, count);
            self.vim_operate_lines(op, first, last + 1 - first);
            return;
        }
        let start = (self.editor.cursor_row, self.editor.cursor_col);
        // `cw` on a word changes up to its end and keeps the blank after it
        // (Vim's `:help cw`, #934); on a blank it is `dw`'s span.
        let change_word = op == crate::vim::Op::Change
            && motion == crate::vim::Motion::WordForward
            && self.vim_class_at(start.0, start.1) != 0;
        if change_word {
            self.vim_change_word_end(count);
        } else {
            self.vim_apply_motion(motion, count);
        }
        let end = (self.editor.cursor_row, self.editor.cursor_col);
        let (lo, hi) = if start <= end {
            (start, end)
        } else {
            (end, start)
        };
        // Forward-inclusive motions (f/t/e) cover the char they land on.
        let head = if start <= end && (change_word || vim_motion_is_forward_inclusive(motion)) {
            let len = self.vim_line_len(hi.0);
            (hi.0, (hi.1 + 1).min(len))
        } else {
            hi
        };
        self.editor.selection = Some(crate::widgets::editor::EditorSelection { anchor: lo, head });
        self.vim_apply_operator_to_selection(op, lo);
    }

    pub(super) fn vim_operate_textobject(
        &mut self,
        op: crate::vim::Op,
        obj: crate::vim::TextObject,
    ) {
        use crate::vim::TextObject;
        let row = self.editor.cursor_row;
        let Some((start, mut end)) = self.editor.word_at(row, self.editor.cursor_col) else {
            return;
        };
        if obj == TextObject::AWord
            && let Some(line) = self.editor.lines.get(row)
        {
            let chars: Vec<char> = line.chars().collect();
            while end < chars.len() && chars[end].is_whitespace() {
                end += 1;
            }
        }
        self.editor.selection = Some(crate::widgets::editor::EditorSelection {
            anchor: (row, start),
            head: (row, end),
        });
        self.vim_apply_operator_to_selection(op, (row, start));
    }

    /// Delete / yank / change whatever the editor selection currently spans,
    /// leaving the cursor at `start` and entering Insert mode for a change.
    pub(super) fn vim_apply_operator_to_selection(
        &mut self,
        op: crate::vim::Op,
        start: (usize, usize),
    ) {
        use crate::vim::Op;
        // A motion can leave a symbol tab's lines (`db` at its first
        // column); the operator covers only the part inside them (#369).
        let start = self.clamp_to_symbol_clip(start);
        if let Some(sel) = self.editor.selection {
            self.editor.selection = Some(crate::widgets::editor::EditorSelection {
                anchor: self.clamp_to_symbol_clip(sel.anchor),
                head: self.clamp_to_symbol_clip(sel.head),
            });
        }
        let text = self.editor.selection_text();
        self.copy_where_pasted(&text);
        match op {
            Op::Yank => {
                self.editor.clear_selection();
                self.editor.cursor_row = start.0;
                self.editor.cursor_col = start.1;
            }
            Op::Delete => {
                self.editor.delete_selection();
            }
            Op::Change => {
                self.editor.delete_selection();
                self.vim.enter_insert_mode();
                self.status = String::from("-- INSERT --");
            }
        }
    }

    /// `pos` pulled inside a symbol tab's lines: above them to the first
    /// line's start, below them to the last line's end. Unchanged on an
    /// ordinary tab.
    pub(super) fn clamp_to_symbol_clip(&self, pos: (usize, usize)) -> (usize, usize) {
        match self.editor.symbol_clip() {
            Some((first, _)) if pos.0 < first => (first, 0),
            Some((_, end)) if pos.0 >= end => (end - 1, self.vim_line_len(end - 1)),
            _ => pos,
        }
    }

    pub(super) fn vim_line_range_for_motion(
        &self,
        motion: crate::vim::Motion,
        count: usize,
    ) -> (usize, usize) {
        use crate::vim::Motion;
        let row = self.editor.cursor_row;
        let last = self.editor.lines.len().saturating_sub(1);
        let n = count.max(1);
        match motion {
            Motion::Down => (row, (row + n).min(last)),
            Motion::Up => (row.saturating_sub(n), row),
            Motion::FileStart => (0, row),
            Motion::FileEnd => (row, last),
            Motion::GotoLine(line) => {
                let target = line.saturating_sub(1).min(last);
                if target >= row {
                    (row, target)
                } else {
                    (target, row)
                }
            }
            _ => (row, row),
        }
    }

    pub(super) fn vim_delete_chars(&mut self, count: usize) {
        let row = self.editor.cursor_row;
        let Some(line) = self.editor.lines.get(row) else {
            return;
        };
        let chars: Vec<char> = line.chars().collect();
        let col = self.editor.cursor_col;
        let end = (col + count.max(1)).min(chars.len());
        if col < end {
            let deleted: String = chars[col..end].iter().collect();
            self.copy_where_pasted(&deleted);
            for _ in col..end {
                self.editor.delete_forward();
            }
        }
    }

    pub(super) fn vim_enter_insert(&mut self, at: crate::vim::InsertAt) {
        use crate::vim::InsertAt;
        let row = self.editor.cursor_row;
        match at {
            InsertAt::Cursor => {}
            InsertAt::After => {
                let len = self.vim_line_len(row);
                if self.editor.cursor_col < len {
                    self.editor.cursor_col += 1;
                }
            }
            InsertAt::LineStart => self.editor.cursor_col = self.vim_first_non_blank(row),
            InsertAt::LineEnd => self.editor.cursor_col = self.vim_line_len(row),
            InsertAt::Below => self.editor.open_line_below(),
            InsertAt::Above => self.editor.open_line_above(),
        }
        self.status = String::from("-- INSERT --");
    }

    pub(super) fn vim_paste(&mut self, at: crate::vim::PasteAt, count: usize) {
        use crate::vim::PasteAt;
        let Some(text) = self.clipboard_text() else {
            self.status = String::from("Nothing to paste: the clipboard can't be read");
            return;
        };
        if text.is_empty() {
            self.status = String::from("Nothing to paste: the clipboard is empty");
            return;
        }
        let n = count.max(1);
        if let Some(body) = text.strip_suffix('\n') {
            // Linewise paste: the yank ended on a newline, so it lands on
            // fresh lines rather than inside the current one.
            let block = std::iter::repeat_n(body, n).collect::<Vec<_>>().join("\n");
            match at {
                PasteAt::After => {
                    self.editor.cursor_col = self.vim_line_len(self.editor.cursor_row);
                    self.editor.insert_str(&format!("\n{block}"));
                }
                PasteAt::Before => {
                    self.editor.cursor_col = 0;
                    self.editor.insert_str(&format!("{block}\n"));
                }
            }
        } else {
            let block = text.repeat(n);
            if at == PasteAt::After {
                let len = self.vim_line_len(self.editor.cursor_row);
                if self.editor.cursor_col < len {
                    self.editor.cursor_col += 1;
                }
            }
            self.editor.insert_str(&block);
        }
        self.status = String::from("Pasted");
    }

    pub(super) fn vim_visual_operate(&mut self, op: crate::vim::Op) {
        use crate::vim::Op;
        let Some(sel) = self.editor.selection else {
            return;
        };
        if self.vim_visual_line {
            let ((sr, _), (er, _)) = sel.normalised();
            self.vim_operate_lines(op, sr, er + 1 - sr);
            self.vim_visual_line = false;
            return;
        }
        // Charwise visual is inclusive of the cell under the cursor, so extend
        // the high end one char before operating.
        let ((sr, sc), (er, ec)) = sel.normalised();
        let len = self.vim_line_len(er);
        self.editor.selection = Some(crate::widgets::editor::EditorSelection {
            anchor: (sr, sc),
            head: (er, (ec + 1).min(len)),
        });
        self.vim_apply_operator_to_selection(op, (sr, sc));
        self.vim_visual_line = false;
        if !matches!(op, Op::Change) {
            self.status.clear();
        }
    }

    pub(super) fn vim_run_ex(&mut self, cmd: &str) {
        let cmd = cmd.trim();
        if let Ok(line) = cmd.parse::<usize>() {
            self.editor.goto_line(line);
            return;
        }
        match cmd {
            "w" | "write" => self.save(),
            "q" | "quit" => self.request_close_tab(self.editor.active_index()),
            // vim's `!` is the answer to "discard the changes?" given up
            // front, so these two never ask (#862).
            "q!" => self.close_tab_now(self.editor.active_index()),
            "qa!" => {
                self.clear_hot_exit();
                self.quit = true;
            }
            "wq" | "x" | "wq!" => {
                self.save();
                // A save that did not land (a disk conflict, a format still
                // running) leaves the tab dirty, and the close asks.
                self.request_close_tab(self.editor.active_index());
            }
            "qa" | "quitall" => self.guard_unsaved(UnsavedExit::Quit),
            other => self.status = format!("Unknown command: {other}"),
        }
    }

    pub(super) fn vim_search(&mut self, dir: crate::vim::SearchDir, term: &str) {
        self.editor.set_search_highlight(
            Some(term.to_string()),
            crate::widgets::search::SearchOpts::default(),
        );
        match self.vim_find_match(dir, term) {
            Some((row, col)) => {
                self.editor.cursor_row = row;
                self.editor.cursor_col = col;
                self.editor.ensure_cursor_col_visible();
                // Record the hit the cursor jumped to so the renderer paints it
                // in the distinct active colour (orange) while the remaining
                // matches keep the regular yellow. Literal search, so the match
                // is exactly `term` long in characters.
                self.editor.active_search_match = Some((row, col, term.chars().count()));
                self.status = match dir {
                    crate::vim::SearchDir::Forward => format!("/{term}"),
                    crate::vim::SearchDir::Backward => format!("?{term}"),
                };
            }
            None => {
                self.editor.active_search_match = None;
                self.status = format!("Pattern not found: {term}");
            }
        }
    }

    pub(super) fn vim_find_match(
        &self,
        dir: crate::vim::SearchDir,
        term: &str,
    ) -> Option<(usize, usize)> {
        use crate::vim::SearchDir;
        let lines = &self.editor.lines;
        if term.is_empty() || lines.is_empty() {
            return None;
        }
        let (cr, cc) = (self.editor.cursor_row, self.editor.cursor_col);
        let total = lines.len();
        match dir {
            SearchDir::Forward => {
                for off in 0..=total {
                    let row = (cr + off) % total;
                    let from = if off == 0 { cc + 1 } else { 0 };
                    if let Some(col) = find_char_index(&lines[row], term, from) {
                        return Some((row, col));
                    }
                }
                None
            }
            SearchDir::Backward => {
                for off in 0..=total {
                    let row = (cr + total - off) % total;
                    let limit = if off == 0 { cc } else { usize::MAX };
                    if let Some(col) = rfind_char_index(&lines[row], term, limit) {
                        return Some((row, col));
                    }
                }
                None
            }
        }
    }

    pub(super) fn vim_sync_visual_selection(&mut self) {
        if !matches!(
            self.vim.mode(),
            crate::vim::VimMode::Visual | crate::vim::VimMode::VisualLine
        ) {
            return;
        }
        if let Some(anchor) = self.vim.visual_anchor() {
            self.editor.selection = Some(crate::widgets::editor::EditorSelection {
                anchor,
                head: (self.editor.cursor_row, self.editor.cursor_col),
            });
        }
    }
}

impl App {
    /// Copy the terminal pane's current selection to the user's clipboard.
    /// Selection stays visible so the user can verify what was copied.
    ///
    /// A copy that finds NOTHING now says so (#538). Inside a program that has
    /// ASKED for mouse tracking — Claude Code and most full-screen TUIs, but
    /// not a program that never requested it — a plain drag is the child's
    /// gesture and croft deliberately holds no selection of its own (#474), so
    /// the old silent return left the user pressing copy with nothing
    /// happening and no way to learn that Shift+drag selects there. The hint
    /// is keyed on `mouse_reporting`, so a pane whose child is not tracking is
    /// told to drag, which is what works there.
    pub(super) fn copy_terminal_selection(&mut self) {
        if !self.terminal().selection().is_some_and(|s| s.has_area()) {
            self.status = String::from(if self.terminal().mouse_reporting() {
                "Nothing selected: Shift+drag selects inside a program that tracks the mouse"
            } else {
                "Nothing selected: drag to select first"
            });
            return;
        }
        let text = self.terminal_text_for_copy(self.terminal().selection_text());
        if text.is_empty() {
            // A real selection, but over blank cells: saying "nothing
            // selected" here would describe the wrong thing to fix.
            self.status = String::from("Selection has no text to copy");
            return;
        }
        self.deliver_copied_text(&text);
    }

    /// Put copied text where the user can actually paste it.
    ///
    /// "The clipboard" is not always this machine's. On a relay session croft
    /// runs on a remote box while the user types at another machine, and it is
    /// THAT clipboard a paste comes from — so the text goes home over the drop
    /// relay, the same road `request_remote_clipboard` uses to fetch it for a
    /// paste, travelled in the other direction (#538). Writing the remote
    /// box's clipboard instead put the text somewhere nothing could reach, and
    /// an SSH session usually has no clipboard tool to write to at all.
    ///
    /// Everywhere else it is this machine's clipboard, with the OSC 52
    /// fallback [`Self::copy_where_pasted`] keeps for a host terminal that
    /// honours it. That fallback is reported HONESTLY: whether the sequence is
    /// acted on is the host terminal's choice, not something croft can see, so
    /// claiming a copy landed would be a claim croft cannot make.
    pub(super) fn deliver_copied_text(&mut self, text: &str) {
        let n = text.chars().count();
        self.status = self.copy_where_pasted(text).status(&format!("{n} chars"));
    }

    /// The copy `deliver_copied_text` makes, without the status line, for a
    /// caller that words its own. Every copy croft makes goes this way, so a
    /// copy command cannot skip the relay by mistake: terminal copies did
    /// (#1667), and so did the editor's, vim's, Copy Path, Copy Commit Hash
    /// and the rest (#2070), all writing the remote box's clipboard on a
    /// relay session, where pasting at home found the old text.
    ///
    /// Off a relay session, the order of attempts:
    ///   1. **This machine's clipboard** — `clipboard::write_string` posts
    ///      directly to `NSPasteboard.generalPasteboard` on macOS (with
    ///      `pbcopy` as a fall-back inside the same helper), the only path
    ///      that survives every iTerm2 configuration seen in the wild. OSC 52
    ///      is, empirically, silently dropped by iTerm2 in some setups even
    ///      with `AllowClipboardAccess` enabled, and writing escape bytes to
    ///      the alt-screen stdout always risks racing the next frame.
    ///   2. **OSC 52** — only if that write failed (a Linux box with no
    ///      clipboard tool, where the only hand-shake with the user's own
    ///      terminal is escape bytes through the SSH PTY). Best-effort, and
    ///      the landing says so.
    ///
    /// On a relay session the local machine's clipboard comes first, over
    /// the relay. When it has no clipboard to write (a Linux box with no
    /// clipboard tool), its pump says so and `drain_relay_copies` sends the
    /// OSC 52 sequence from here instead, which the user's terminal gets
    /// over the SSH session as it did before the copy went home.
    pub(super) fn copy_where_pasted(&mut self, text: &str) -> CopyLanding {
        crate::clipboard::remember_copy(text);
        if self.is_relay_session
            && let Some(request_id) = self.push_clipboard_via_relay(text)
        {
            self.pending_relay_copies.push(PendingRelayCopy {
                request_id,
                text: text.to_owned(),
                started_at: std::time::Instant::now(),
            });
            CopyLanding::Local
        } else if crate::clipboard::write_string(text) {
            CopyLanding::Clipboard
        } else {
            crate::clipboard::send_osc52(text);
            CopyLanding::Osc52
        }
    }

    /// Follow up the relay copies whose answer is due. The pump answers only
    /// a copy it could not put on the local clipboard, with `.err` in the
    /// request's inbox directory; that copy goes by OSC 52 instead, the
    /// fallback a copy off a relay session gets. Silence means it landed,
    /// so a copy with no answer by [`RELAY_COPY_ANSWER_WAIT`] is let go:
    /// that also covers a local croft too old to answer at all.
    pub fn drain_relay_copies(&mut self) -> bool {
        if self.pending_relay_copies.is_empty() {
            return false;
        }
        let Some(inbox) = self.relay_inbox_path() else {
            self.pending_relay_copies.clear();
            return false;
        };
        let mut changed = false;
        for copy in std::mem::take(&mut self.pending_relay_copies) {
            let request_dir = inbox.join(&copy.request_id);
            if request_dir.join(".err").exists() {
                let _ = std::fs::remove_dir_all(&request_dir);
                crate::clipboard::send_osc52(&copy.text);
                let n = copy.text.chars().count();
                self.status = format!(
                    "The local machine has no clipboard to write: sent {n} chars via OSC 52 (the host terminal decides)"
                );
                changed = true;
            } else if copy.started_at.elapsed() < RELAY_COPY_ANSWER_WAIT {
                self.pending_relay_copies.push(copy);
            }
        }
        changed
    }

    /// Push copied text to the LOCAL machine's clipboard over the drop relay.
    /// Returns the request's id when it was queued.
    ///
    /// The payload goes in a file in the relay INBOX rather than into the
    /// request line: a request is one TAB-SEPARATED LINE, while copied text
    /// carries newlines and tabs of its own and can be megabytes of
    /// scrollback. The line names only the request id — the pump derives
    /// `<inbox>/<id>.txt` from the inbox it already owns, so no path from
    /// this side is ever handed to a remote shell.
    ///
    /// An oversized copy is REFUSED here rather than truncated there. The pump
    /// caps what it will read into the local machine's memory and drops
    /// anything past it, and a selection that pastes back half-formed is worse
    /// than falling through to the ordinary clipboard route and saying so.
    pub(super) fn push_clipboard_via_relay(&mut self, text: &str) -> Option<String> {
        if text.len() > crate::remote::MAX_COPY_PAYLOAD_BYTES {
            return None;
        }
        let (Some(log_path), Some(inbox)) = (self.relay_log_path(), self.relay_inbox_path()) else {
            return None;
        };
        self.ensure_relay_dir();
        let request_id = Self::relay_request_id("copy");
        if std::fs::write(inbox.join(format!("{request_id}.txt")), text).is_err() {
            return None;
        }
        append_to_relay_log(&log_path, &format!("copy\t{request_id}\n"))
            .is_ok()
            .then_some(request_id)
    }

    /// Paste the host clipboard into the terminal: the chord (Cmd+V /
    /// Ctrl+Shift+V) and the pane menu's "Paste" both land here, so
    /// bracketed paste, broadcast fan-out and the remote-clipboard fallback
    /// behave identically whichever one the user reached for.
    ///
    /// The messages name the ACTION rather than the chord: the menu route has
    /// no Cmd+V in it, and a status line quoting a key the user never pressed
    /// reads as a bug report about the wrong thing.
    pub(super) fn paste_clipboard_into_terminal(&mut self) {
        let text = crate::clipboard::read_string();
        if text.is_none() && self.drop_relay_active() {
            self.request_remote_clipboard();
            return;
        }
        // Without a relay, what croft last copied, as for any other paste
        // inside croft (#933).
        match text.or_else(crate::clipboard::last_copy) {
            Some(text) if !text.is_empty() => {
                self.paste_terminal_input(text.as_bytes());
            }
            Some(_) => {
                self.status = String::from("Paste: clipboard is empty");
            }
            None => {
                self.status =
                    String::from("Paste: clipboard read failed (no pbpaste / NSPasteboard)");
            }
        }
    }

    pub(super) fn copy_editor_selection(&mut self) {
        // The rendered preview hides the source buffer, so its selection
        // is the only one the user can see (#215).
        if let Some(md) = self.editor.markdown_preview.as_ref() {
            let text = md.selection_text();
            if !text.is_empty() {
                self.deliver_copied_text(&text);
            }
            return;
        }
        // A rendered log likewise hides its own text behind a stub buffer,
        // and the return is unconditional: falling through when there is no
        // selection would run the editor's copy over that stub and put its
        // placeholder content on the clipboard, which is worse than copying
        // nothing.
        if self.editor.log.is_some() {
            self.copy_log_selection();
            return;
        }
        if let Some(diff) = self.editor.diff.as_ref() {
            if let Some(text) = diff.selection_text()
                && !text.is_empty()
            {
                self.deliver_copied_text(&text);
            }
            return;
        }
        let Some(sel) = self.editor.selection else {
            return;
        };
        if !sel.has_area() {
            return;
        }
        let text = self.editor.selection_text();
        if text.is_empty() {
            return;
        }
        self.deliver_copied_text(&text);
    }

    /// Whether the active editor view shows a selection for Copy to take,
    /// read as [`Self::copy_editor_selection`] reads it: a rendered preview's
    /// or log's own selection, a diff's, else the buffer's in a text view.
    pub(super) fn editor_view_has_selection(&self) -> bool {
        if let Some(md) = self.editor.markdown_preview.as_ref() {
            return !md.selection_text().is_empty();
        }
        if let Some(log) = self.editor.log.as_ref() {
            return log.has_selection();
        }
        if let Some(diff) = self.editor.diff.as_ref() {
            return diff.selection_text().is_some_and(|t| !t.is_empty());
        }
        self.editor_is_text() && self.editor.selection.is_some_and(|s| s.has_area())
    }

    pub(super) fn cut_editor_selection(&mut self) {
        let Some(sel) = self.editor.selection else {
            return;
        };
        if !sel.has_area() {
            return;
        }
        let text = self.editor.selection_text();
        if text.is_empty() {
            self.editor.clear_selection();
            return;
        }
        let n = text.chars().count();
        let landing = self.copy_where_pasted(&text);
        self.editor.delete_selection();
        self.status = match landing {
            CopyLanding::Clipboard => format!("Cut {n} chars to clipboard"),
            _ => format!("Cut {n} chars{}", landing.note()),
        };
    }

    pub(super) fn paste_clipboard_into_search(&mut self, text: Option<&str>) {
        let Some(s) = text else {
            self.status = String::from("Cmd+V: clipboard read failed");
            return;
        };
        if s.is_empty() {
            self.status = String::from("Cmd+V: clipboard is empty");
            return;
        }
        self.paste_str_into_search(s);
        self.status = format!(
            "Cmd+V: pasted into {} field",
            search_field_name(self.search.field)
        );
    }

    /// Paste `s` at the caret of the focused Search field, whichever it is,
    /// for the clipboard key and the bracketed-paste event alike.
    pub(super) fn paste_str_into_search(&mut self, s: &str) {
        self.search.insert_str(s);
        // Replace text doesn't change which files match, so only re-run the
        // scan when the paste landed in a search-affecting field.
        if self.search.field != crate::widgets::search::SearchField::Replace {
            self.submit_search_query();
        }
    }

    pub(super) fn paste_clipboard_into_editor(&mut self, text: Option<&str>) {
        let Some(s) = text else {
            self.status = String::from("Cmd+V: clipboard read failed");
            return;
        };
        if s.is_empty() {
            self.status = String::from("Cmd+V: clipboard is empty");
            return;
        }
        self.editor.paste_str(s, self.paste_reindent);
        self.status = format!("Pasted {} chars", s.chars().count());
    }

    /// What a paste inside croft inserts: the host clipboard, or what croft
    /// itself last copied when the host clipboard can't be read (#933), as
    /// on a Linux host with no clipboard tool, where copies go out only by
    /// OSC 52.
    ///
    /// On a relay session croft's last copy comes FIRST. Every copy there
    /// goes home to the clipboard of the machine the user types at and
    /// leaves this box's alone (#2070), so this box's clipboard holds
    /// nothing copied in croft: reading it first made a Cut then Paste, or
    /// vim's `d` then `p`, put back whatever was on it before.
    pub(super) fn clipboard_text(&self) -> Option<String> {
        if self.is_relay_session {
            return crate::clipboard::last_copy().or_else(self.clipboard_reader);
        }
        (self.clipboard_reader)().or_else(crate::clipboard::last_copy)
    }

    /// A terminal paste. While a macro records, a paste into the editor is a
    /// step of it, on the same terms `handle_key` records a key: not while
    /// replaying, and only when the editor had focus before and after and
    /// the text went into it (#1464). Before, the replay silently left the pasted text out.
    pub(super) fn handle_paste(&mut self, s: &str) {
        if self.screencast.is_on() {
            self.screencast.pasted(std::time::Instant::now());
        }
        let capture =
            self.macro_recording.is_some() && !self.macro_replaying && self.focus == Pane::Editor;
        let into_editor = self.handle_paste_inner(s);
        #[cfg(test)]
        self.assert_one_view_per_tab();
        if self.macro_recording.is_none() || self.macro_replaying {
            return;
        }
        // A paste the palette, a prompt or the find bar took never reached
        // the document, so replaying it there would insert stray text.
        if capture && into_editor && self.focus == Pane::Editor {
            if let Some(rec) = self.macro_recording.as_mut() {
                rec.recorded.push_paste(s);
            }
        } else if !s.is_empty() {
            // Logged as skipped keys are, by size only: a paste into a
            // terminal can be a password.
            crate::output::push(
                "Macros",
                crate::output::OutputLevel::Info,
                &format!(
                    "skipped a paste of {} chars: recording captures the editor pane only",
                    s.chars().count()
                ),
            );
        }
    }

    /// Route a paste to whatever owns it; true only when it went into the
    /// editor's text, the one place a recording macro can replay it.
    pub(super) fn handle_paste_inner(&mut self, s: &str) -> bool {
        // Pop-ups own a paste entirely while open: it lands in the pop-up's
        // own field, never in the editor, tree or terminal behind it. Without
        // this, hitting Cmd+V right after Cmd+P pastes into whatever pane was
        // last focused instead of into the finder query, which makes the
        // "open + paste a filename" path that the VS Code Quick Open is meant
        // to support unusable.
        if self.paste_into_popup(s) {
            return false;
        }
        // The in-file find bar is a pane-scoped widget, not a modal: it only
        // owns the paste while the editor itself is focused. Without the focus
        // guard, an open find bar would swallow a paste meant for the terminal
        // (or tree) the user has since clicked into — the keystroke path is
        // already focus-gated via `match self.focus`, so paste must match it.
        if self.focus == Pane::Editor && self.editor_find.is_some() {
            // Pasted at the caret (#1729), like typing: the bar is an input
            // line, and a middle-of-query paste must not jump to the end.
            let text = s.to_string();
            self.editor_find_edit_at_caret(|t, c| {
                crate::widgets::editor_find::insert_at(t, c, &text)
            });
            return false;
        }
        // Finder drag-and-drop into croft arrives via the host terminal as
        // a bracketed paste containing absolute filesystem path(s). The
        // drop in iTerm2 does NOT shift mouse focus, so we cannot require
        // `self.focus == Pane::Tree` for the gesture: the user can have
        // last clicked into the editor or the embedded terminal and still
        // expect the drop on the sidebar to import.
        //
        //   * Remote view: any path-shaped paste is an scp upload. There
        //     is no other reasonable thing the user could want, since the
        //     visible UI is a host list.
        //   * Explorer view: a path-shaped paste is an import only when
        //     focus is on the tree, otherwise we keep the current
        //     behaviour (typing a path string into the focused editor or
        //     terminal command line) because that is a legitimate use.
        // iTerm2's inline-image drag artefact ALWAYS short-circuits the
        // paste pipeline: a stray click-and-microdrag on an OSC-1337 cell
        // (activity-bar icon, welcome wordmark, no-repo / run-debug / SSH
        // hero) makes iTerm2 write the decoded PNG to $TMPDIR/iTerm2.<rand>.png
        // and re-inject the path as a bracketed paste. parse_dropped_paths
        // already filters those paths out of the import list, but without
        // an early-return here the fallthrough would still paste the raw
        // path string into the editor body (the user reported this as
        // "Pasted 67 chars" appearing in a freshly-opened CLAUDE.local.md
        // tab while they were trying to resize the sidebar near the
        // Explorer icon). Detect the artefact at the payload level and
        // silently drop the entire paste — no text, no import, no status.
        if parsed_drop_tokens(s)
            .iter()
            .any(|p| p.is_absolute() && is_iterm2_inline_image_drop(p))
        {
            return false;
        }
        let dropped = parse_dropped_paths(s);
        if !dropped.is_empty() {
            match self.sidebar_view {
                SidebarView::Remote if self.focus == Pane::Tree => {
                    self.import_paths_into_remote(&dropped);
                    return false;
                }
                SidebarView::Explorer if self.focus == Pane::Tree => {
                    self.import_paths_into_explorer(&dropped);
                    return false;
                }
                _ => {}
            }
        }
        // Remote-launched croft case: the path the user dragged from
        // their local Finder doesn't exist on this remote box, so the
        // strict parser above returned nothing. If the drop-relay env
        // is plumbed (set by the local-croft parent over the SSH
        // session) and the paste shape is path-like, request a reverse
        // pull through the relay.
        //
        // Two triggers gate the relay pull. Tree focus is the explicit one,
        // matching the strict branch above. The second, `is_pure_path_payload`,
        // recovers a genuine Finder drag: a drop arrives as a bracketed paste
        // and does NOT move keyboard focus to the tree, so a focus-only gate
        // silently dropped every drag where the user had last clicked the
        // terminal or editor. A real drop is nothing but absolute-path tokens,
        // whereas the text pastes the focus guard protects — a shell command or
        // code snippet that merely contains a `/...` token — always carry a
        // non-path token, so they still fall through to a normal paste rather
        // than being hijacked into a relay pull with no local file to fetch
        // (the regression seen on remote sessions opened from Termux).
        if self.drop_relay_active()
            && self.sidebar_view == SidebarView::Explorer
            && (self.focus == Pane::Tree || is_pure_path_payload(s))
        {
            let foreign = parse_foreign_dropped_paths(s);
            if !foreign.is_empty() {
                self.request_remote_pulls(&foreign);
                return false;
            }
        }
        if self.sidebar_view == SidebarView::Search && self.focus == Pane::Tree {
            self.paste_str_into_search(s);
            self.status = format!("Pasted {} chars", s.chars().count());
            return false;
        }
        // Source Control commit message box: bracketed paste must
        // populate it the same way Cmd+V via the key path does
        // (`handle_source_control_key` -> `source_control.insert_str`).
        // Without this branch, in the production setup where iTerm2
        // emits Cmd+V as a bracketed paste rather than a key event,
        // the payload silently vanishes when the user has the SC
        // sidebar focused.
        if self.sidebar_view == SidebarView::SourceControl
            && self.focus != Pane::Editor
            && self.focus != Pane::Terminal
        {
            self.source_control.insert_str(s);
            self.status = format!("Pasted {} chars", s.chars().count());
            return false;
        }
        match self.focus {
            Pane::Editor => {
                self.editor.paste_str(s, self.paste_reindent);
                self.status = format!("Pasted {} chars", s.chars().count());
                return true;
            }
            Pane::Terminal => {
                if self.terminal_find.is_some() {
                    // At the caret, like the clipboard key (#1729).
                    self.terminal_find_edit_at_caret(|t, at| {
                        crate::widgets::line_edit::insert_at(t, at, s)
                    });
                } else {
                    self.paste_terminal_input(s.as_bytes());
                }
            }
            Pane::Tree => {}
        }
        false
    }

    /// Ask the local-croft drop pump to fetch the user's macOS clipboard
    /// and stage it on this remote box. The drained pull resolves to a
    /// `paste_input` call on the embedded terminal — see `drain_remote_pulls`.
    pub(super) fn request_remote_clipboard(&mut self) {
        let Some(log_path) = self.relay_log_path() else {
            self.status = String::from("Cmd+V: drop relay vanished");
            return;
        };
        self.ensure_relay_dir();
        let request_id = Self::relay_request_id("clip");
        let mut line = String::from("clipboard\t");
        line.push_str(&request_id);
        line.push('\n');
        match append_to_relay_log(&log_path, &line) {
            Ok(()) => {
                self.pending_remote_pulls.push(PendingRemotePull {
                    request_id,
                    src_display: String::from("clipboard"),
                    basename: String::from("clipboard.txt"),
                    dest_dir: PathBuf::new(),
                    started_at: std::time::Instant::now(),
                    kind: RemotePullKind::Clipboard,
                });
                self.status = String::from("Cmd+V: fetching local Mac clipboard via croft relay");
            }
            Err(e) => {
                self.status = format!("Cmd+V: relay write failed: {e}");
            }
        }
    }

    /// Capture one key into the live recording. Recording control keys are
    /// excluded by the callers that own them (vim's `q`, the palette
    /// commands), so a macro can never contain the gesture that ends it.
    pub(super) fn record_macro_key(&mut self, key: crossterm::event::KeyEvent) {
        if let Some(rec) = self.macro_recording.as_mut() {
            rec.recorded.push_key(key);
        }
    }

    /// Hold back a recorded key that opened or went into the Command Palette
    /// (#952) until the palette closes: it then joins the macro with the rest
    /// of that palette session, so a palette command replays whole. The
    /// session that runs Macro: Start/Stop Recording never gets here with
    /// its Enter, because stopping drops the recording and what it held.
    /// One the palette was opened for without a key (a click) is dropped:
    /// replayed without the chord, its query would be typed into the file.
    /// So is one whose command took focus out of the editor, such as
    /// Terminal: Focus Terminal: the click that brings it back is not
    /// recorded, so a replay would type the keys after it into the shell.
    pub(super) fn hold_palette_macro_key(
        &mut self,
        key: crossterm::event::KeyEvent,
        palette_before: bool,
    ) {
        let open_now = self.command_palette.is_some();
        let in_editor = self.focus == Pane::Editor;
        let Some(rec) = self.macro_recording.as_mut() else {
            return;
        };
        if !palette_before {
            // The key that opened the palette starts a session that
            // replays; whatever an earlier one held was never closed by a
            // key, so it has nothing to replay.
            rec.palette_keys.clear();
            rec.palette_keys.push(key);
        } else if !rec.palette_keys.is_empty() {
            rec.palette_keys.push(key);
        } else {
            crate::output::push(
                "Macros",
                crate::output::OutputLevel::Info,
                &format!("skipped {key:?}: the palette was not opened from the keyboard"),
            );
        }
        if open_now {
            return;
        }
        let held = std::mem::take(&mut rec.palette_keys);
        if in_editor {
            for k in held {
                rec.recorded.push_key(k);
            }
        } else if !held.is_empty() {
            crate::output::push(
                "Macros",
                crate::output::OutputLevel::Info,
                "skipped a palette command that left the editor: recording captures the editor pane only",
            );
        }
    }

    /// Drop what a palette session held for the macro once the palette has
    /// closed without a key, as a click outside it or on a row does (#952):
    /// a session that is never closed from the keyboard has nothing that
    /// replays, and a later session must not pick its keys up.
    pub(super) fn drop_unkeyed_palette_macro_keys(&mut self) {
        if self.command_palette.is_none()
            && let Some(rec) = self.macro_recording.as_mut()
        {
            rec.palette_keys.clear();
        }
    }

    /// Start recording into `register` (vim `q{a-z}`) or into the unnamed
    /// last-recording slot (the palette command). Starting while already
    /// recording stops instead, so one gesture toggles.
    pub(super) fn start_macro_recording(&mut self, register: Option<char>) {
        if self.macro_recording.is_some() {
            self.stop_macro_recording();
            return;
        }
        self.macro_recording = Some(crate::macros::Recording {
            register,
            recorded: crate::macros::Macro::default(),
            palette_keys: Vec::new(),
        });
        // One source of truth: vim's `q` branches on this, and a copy the
        // machine kept for itself drifted whenever the palette was used.
        self.vim.set_recording(true);
        self.status = match register {
            Some(r) => format!("Recording macro into @{r}"),
            None => String::from("Recording macro"),
        };
    }

    /// Finish the live recording: it becomes the last macro either way, and
    /// a named register is also persisted. An empty recording is discarded
    /// rather than replacing a useful macro with a no-op.
    pub(super) fn stop_macro_recording(&mut self) {
        let Some(rec) = self.macro_recording.take() else {
            return;
        };
        self.vim.set_recording(false);
        if rec.recorded.is_empty() {
            self.status = String::from("Macro discarded (nothing recorded)");
            return;
        }
        let len = rec.recorded.len();
        if let Some(r) = rec.register {
            let name = r.to_string();
            self.macro_registers
                .insert(name.clone(), rec.recorded.clone());
            if let Err(e) =
                crate::macros::save_register(&self.macros_path, &name, rec.recorded.clone())
            {
                crate::output::push("Macros", crate::output::OutputLevel::Warn, &e);
            }
            // Written by croft itself: nothing for the config watch to reload.
            self.config_watch.note(&self.macros_path.clone());
            self.status = format!("Recorded {len} keys into @{r}");
        } else {
            self.status = format!("Recorded {len} keys");
        }
        self.macro_last = Some(rec.recorded);
    }

    /// Replay `mac` `count` times by feeding its keys back through
    /// `handle_key`. Guarded three ways: a re-entrancy flag (a macro cannot
    /// invoke itself), a total-key budget (a pathological count cannot spin
    /// the UI), and an abort on the first key that errors, which leaves the
    /// buffer at the abort point with earlier iterations intact.
    pub(super) fn replay_macro(&mut self, mac: crate::macros::Macro, count: usize) {
        const MAX_REPLAY_KEYS: usize = 100_000;
        if self.macro_replaying {
            self.status = String::from("Macro is already replaying");
            return;
        }
        if mac.is_empty() {
            self.status = String::from("Macro is empty");
            return;
        }
        let count = count.max(1);
        // Budget the steps actually fed, not the recorded step count:
        // `replay_steps` drops steps this build cannot replay, so `len()` is
        // an upper bound rather than the real total.
        let keys = mac.replay_steps();
        if keys.is_empty() {
            // Every step was one this build cannot replay (a macro from a
            // newer croft). Say so rather than reporting a successful run
            // of nothing.
            self.status = String::from("Macro has no steps this version can replay");
            return;
        }
        // A paste is one step but inserts all of its text, so its characters
        // count against the budget like typed ones.
        let per_run: usize = keys
            .iter()
            .map(|step| match step {
                crate::macros::Replay::Key(_) => 1,
                crate::macros::Replay::Paste(text) => text.chars().count().max(1),
            })
            .sum();
        let total = per_run.saturating_mul(count);
        if total > MAX_REPLAY_KEYS {
            self.status =
                format!("Macro would run {total} keys (limit {MAX_REPLAY_KEYS}) — refused");
            return;
        }
        self.macro_replaying = true;
        let mut done = 0usize;
        let mut aborted = None;
        'outer: for iteration in 0..count {
            // Break coalescing so a new iteration's opening keystrokes never
            // merge into the previous iteration's typing run. This bounds
            // iterations apart; it does NOT make one iteration one undo step
            // — `push_undo` coalesces only a typing run, so a macro
            // holding a delete plus an insert still undoes in two. Wrapping
            // the iteration in `Editor::begin_undo_group` would not do it
            // either: every vim command the macro runs ends that group (#934).
            self.editor.break_undo_coalescing();
            for step in &keys {
                match step {
                    crate::macros::Replay::Key(k) => {
                        if let Err(e) = self.handle_key(*k) {
                            aborted = Some((iteration + 1, e.to_string()));
                            break 'outer;
                        }
                    }
                    // Pasted, not typed, as it was recorded (#1464).
                    crate::macros::Replay::Paste(text) => self.handle_paste(text),
                }
            }
            done = iteration + 1;
        }
        self.macro_replaying = false;
        self.status = match aborted {
            Some((at, e)) => format!("Macro aborted on iteration {at}: {e}"),
            None if done == 1 => String::from("Macro replayed"),
            None => format!("Macro replayed {done}×"),
        };
    }

    /// Replay the last recording (palette "Macro: Replay Last", vim `@@`).
    pub(super) fn replay_last_macro(&mut self, count: usize) {
        match self.macro_last.clone() {
            Some(m) => self.replay_macro(m, count),
            None => self.status = String::from("No macro recorded yet"),
        }
    }

    /// Replay a named register (vim `@{a-z}`).
    pub(super) fn replay_macro_register(&mut self, register: char, count: usize) {
        match self.macro_registers.get(&register.to_string()).cloned() {
            Some(m) => {
                self.macro_last = Some(m.clone());
                self.replay_macro(m, count);
            }
            None => self.status = format!("Register @{register} is empty"),
        }
    }

    /// The `(rows, cols)` a column-select key moves the box head (#1560):
    /// Cmd/Ctrl+Shift+Alt with an arrow moves one row or column and with
    /// PageUp/PageDown one screen; while Column Selection Mode is on, plain
    /// Shift does the same. `None` for every other key.
    pub(super) fn column_select_key(&self, key: KeyEvent) -> Option<(isize, isize)> {
        let m = key.modifiers;
        let shift = m.contains(KeyModifiers::SHIFT);
        let alt = m.contains(KeyModifiers::ALT);
        let cmd = m.contains(KeyModifiers::SUPER) || m.contains(KeyModifiers::CONTROL);
        let chord = cmd && shift && alt;
        let mode = self.editor.column_selection_mode && shift && !cmd && !alt;
        if !chord && !mode {
            return None;
        }
        let page = self.editor.column_select_page();
        Some(match key.code {
            KeyCode::Up => (-1, 0),
            KeyCode::Down => (1, 0),
            KeyCode::Left => (0, -1),
            KeyCode::Right => (0, 1),
            KeyCode::PageUp => (-page, 0),
            KeyCode::PageDown => (page, 0),
            _ => return None,
        })
    }

    /// View: Toggle Column Selection Mode (#1560): while on, Shift+arrows
    /// grow a column selection.
    pub(super) fn toggle_column_selection_mode(&mut self) {
        self.editor.column_selection_mode = !self.editor.column_selection_mode;
        self.status = format!(
            "Column Selection Mode {}",
            if self.editor.column_selection_mode {
                "on"
            } else {
                "off"
            }
        );
    }

    /// Type `c` into the active editor in the app's typing mode. The mode is
    /// copied first: a tab switched to in the same input batch has not had
    /// its `overwrite` flag synced by the draw yet.
    pub(super) fn type_char_in_editor(&mut self, c: char) {
        self.editor.overwrite = self.overwrite_mode;
        self.editor.insert_char(c);
    }

    /// Flip Insert/Overwrite typing (the Insert key).
    pub(super) fn toggle_overwrite_mode(&mut self) {
        self.overwrite_mode = !self.overwrite_mode;
        self.editor.overwrite = self.overwrite_mode;
        // Text typed before and after the switch undo as separate steps.
        self.editor.break_undo_coalescing();
        self.status = format!(
            "{} mode",
            if self.overwrite_mode {
                "Overwrite"
            } else {
                "Insert"
            }
        );
    }

    /// Make the terminal's caret match the typing mode: a block while the
    /// editor has focus in overwrite mode, the steady bar croft runs with
    /// otherwise. Emitted only when the wanted shape changes.
    pub(super) fn sync_caret_style(&mut self) {
        let want_block = self.overwrite_mode && self.focus == Pane::Editor;
        if want_block == self.caret_block_sent {
            return;
        }
        self.caret_block_sent = want_block;
        let style = if want_block {
            crossterm::cursor::SetCursorStyle::SteadyBlock
        } else {
            crossterm::cursor::SetCursorStyle::SteadyBar
        };
        let mut out = stdout();
        let _ = crossterm::execute!(out, style);
    }

    /// Step the gutter's line numbers through on, relative, interval and
    /// off (#1576), on every editor, and save the choice.
    pub(super) fn cycle_line_numbers(&mut self) {
        self.line_numbers = self.line_numbers.next();
        self.apply_view_prefs();
        self.status = format!("Line Numbers: {}", self.line_numbers.pref_id());
        if !cfg!(test) {
            self.report_unsaved_setting(crate::prefs::save_line_numbers(
                self.line_numbers.pref_id(),
            ));
        }
    }

    /// Give every open editor, in every split group, the current line
    /// number mode (#1576). A split beside the active one is on screen
    /// too, and nothing else resyncs it until focus next moves.
    pub(super) fn toggle_render_whitespace(&mut self) {
        self.whitespace_mode = self.whitespace_mode.next();
        self.apply_view_prefs();
        self.status = format!("Render Whitespace: {}", self.whitespace_mode.label());
        if !cfg!(test) {
            self.report_unsaved_setting(crate::prefs::save_render_whitespace(
                self.whitespace_mode.pref_id(),
            ));
        }
    }

    pub(super) fn toggle_bracket_colors(&mut self) {
        self.bracket_colors_enabled = !self.bracket_colors_enabled;
        self.apply_view_prefs();
        self.status = format!(
            "Bracket Pair Colorization: {}",
            if self.bracket_colors_enabled {
                "on"
            } else {
                "off"
            }
        );
        if !cfg!(test) {
            self.report_unsaved_setting(crate::prefs::save_bracket_colors(
                self.bracket_colors_enabled,
            ));
        }
    }

    pub(super) fn toggle_indent_guides(&mut self) {
        self.indent_guides_enabled = !self.indent_guides_enabled;
        self.apply_view_prefs();
        self.status = format!(
            "Indent Guides: {}",
            if self.indent_guides_enabled {
                "on"
            } else {
                "off"
            }
        );
        if !cfg!(test) {
            self.report_unsaved_setting(crate::prefs::save_indent_guides(
                self.indent_guides_enabled,
            ));
        }
    }

    pub(super) fn toggle_auto_close_pairs(&mut self) {
        self.auto_close_pairs = !self.auto_close_pairs;
        self.editor.auto_close_pairs = self.auto_close_pairs;
        self.status = format!(
            "Auto Closing Pairs: {}",
            if self.auto_close_pairs { "on" } else { "off" }
        );
        if !cfg!(test) {
            self.report_unsaved_setting(crate::prefs::save_auto_close_pairs(self.auto_close_pairs));
        }
    }

    /// VS Code's `editor.formatOnType` toggle (#254), persisted like the
    /// other editor preferences.
    pub(super) fn toggle_format_on_type(&mut self) {
        self.format_on_type = !self.format_on_type;
        self.status = if self.format_on_type {
            String::from("Format on Type: on")
        } else {
            String::from("Format on Type: off")
        };
        if !cfg!(test) {
            self.report_unsaved_setting(crate::prefs::save_format_on_type(self.format_on_type));
        }
    }

    /// Flip `editor.formatOnSave`, persist it, and report the new state.
    /// Persistence is skipped under test so the suite never writes the
    /// developer's `~/.config/croft/config.json` (mirrors the layout prefs).
    pub(super) fn toggle_format_on_save(&mut self) {
        self.format_on_save = !self.format_on_save;
        self.status = if self.format_on_save {
            String::from("Format on Save: on")
        } else {
            String::from("Format on Save: off")
        };
        if !cfg!(test) {
            self.report_unsaved_setting(crate::prefs::save_format_on_save(self.format_on_save));
        }
    }
}

/// Read the system clipboard. Used by the search input when Cmd+V arrives as
/// a key event rather than bracketed paste content.
pub(super) fn read_system_clipboard() -> Option<String> {
    crate::clipboard::read_string()
}

/// VS Code "Copy Relative Path" text: `path` relative to the workspace `root`,
/// or the absolute `path` when it lives outside the root (never a `../` walk).
/// Pure so the relativization is unit-tested without touching the clipboard.
pub(super) fn relative_clipboard_text(path: &Path, root: &Path) -> String {
    path.strip_prefix(root)
        .unwrap_or(path)
        .display()
        .to_string()
}

/// How long a relay copy waits for the pump to say the local machine had no
/// clipboard to write. The pump gives up reading a payload after 15 s, and
/// claims and answers each take one more SSH round trip.
pub(super) const RELAY_COPY_ANSWER_WAIT: std::time::Duration = std::time::Duration::from_secs(60);

/// A copy sent home over the relay, kept until the pump's answer is due so
/// it can still go by OSC 52 if the local machine had no clipboard.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct PendingRelayCopy {
    pub(super) request_id: String,
    pub(super) text: String,
    pub(super) started_at: std::time::Instant,
}

/// Where `App::copy_where_pasted` put a copy.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum CopyLanding {
    /// Queued home over the drop relay, to the machine the user types at.
    /// The relay sends no word back on whether that clipboard took it, so
    /// the status says it was sent, not that it landed.
    Local,
    /// This machine's clipboard.
    Clipboard,
    /// Only an OSC 52 sequence, which the host terminal may ignore.
    Osc52,
}

impl CopyLanding {
    /// What to add to a status line that already says the text was taken
    /// (`Deleted 3 lines`, `Cut 5 chars`) when it did not simply land on
    /// this machine's clipboard: nothing for that, where it went otherwise.
    pub(super) fn note(self) -> &'static str {
        match self {
            CopyLanding::Local => "; sent to the local clipboard",
            CopyLanding::Clipboard => "",
            CopyLanding::Osc52 => "; copied via OSC 52 (the host terminal decides)",
        }
    }

    /// The status line for copying `what`, saying honestly where it went.
    pub(super) fn status(self, what: &str) -> String {
        match self {
            CopyLanding::Local => format!("Sent {what} to the local clipboard"),
            CopyLanding::Clipboard => format!("Copied {what} to clipboard"),
            CopyLanding::Osc52 => format!("Copied {what} via OSC 52 (the host terminal decides)"),
        }
    }
}

pub(super) fn chord_status_text(op: char, count: usize) -> String {
    if count > 0 {
        format!("Pending: {op} (count {count})")
    } else {
        format!("Pending: {op}")
    }
}

pub(super) fn is_vim_chord_letter(key: KeyEvent, letter: char) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if c != letter {
        return false;
    }
    if key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::SUPER) || key.modifiers.contains(KeyModifiers::CONTROL)
}

pub(super) fn is_vim_chord_g(key: KeyEvent) -> bool {
    is_vim_chord_letter(key, 'g')
}

pub(super) fn is_vim_chord_y(key: KeyEvent) -> bool {
    is_vim_chord_letter(key, 'y')
}

/// `Cmd+Shift+G` / `Ctrl+Shift+G`: the bottom of the file, or the line a
/// pending count names. Opt is rejected: `Cmd+Opt+Shift+G` is Debug: Switch
/// Session, which leaves the caret alone when no session runs (#2647).
pub(super) fn is_vim_goto_bottom(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'g') {
        return false;
    }
    if !key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::SUPER) || key.modifiers.contains(KeyModifiers::CONTROL)
}

pub(super) fn chord_digit_value(key: KeyEvent) -> Option<usize> {
    let KeyCode::Char(c) = key.code else {
        return None;
    };
    let d = c.to_digit(10)? as usize;
    if key.modifiers.contains(KeyModifiers::ALT) || key.modifiers.contains(KeyModifiers::SHIFT) {
        return None;
    }
    Some(d)
}

pub(super) fn cmd_only_digit_value(key: KeyEvent) -> Option<usize> {
    let d = chord_digit_value(key)?;
    if !key.modifiers.contains(KeyModifiers::SUPER) {
        return None;
    }
    Some(d)
}

pub(super) fn reverse_find(kind: crate::vim::FindKind) -> crate::vim::FindKind {
    use crate::vim::FindKind;
    match kind {
        FindKind::CharForward => FindKind::CharBackward,
        FindKind::CharBackward => FindKind::CharForward,
        FindKind::TillForward => FindKind::TillBackward,
        FindKind::TillBackward => FindKind::TillForward,
    }
}

/// Vertical / whole-file motions operate linewise under an operator (`dj`,
/// `dG`), unlike the charwise horizontal and word motions.
pub(super) fn vim_motion_is_linewise(motion: crate::vim::Motion) -> bool {
    use crate::vim::Motion;
    matches!(
        motion,
        Motion::Up | Motion::Down | Motion::FileStart | Motion::FileEnd | Motion::GotoLine(_)
    )
}

/// `f`/`t`/`e` land on a char that the operator should include, so the
/// deletion range needs to extend one past the landing column.
pub(super) fn vim_motion_is_forward_inclusive(motion: crate::vim::Motion) -> bool {
    use crate::vim::{FindKind, Motion};
    matches!(
        motion,
        Motion::WordEnd
            | Motion::Find(FindKind::CharForward, _)
            | Motion::Find(FindKind::TillForward, _)
    )
}

/// First char index `>= from` where `term` begins in `line`, comparing by
/// char (not byte) so the result indexes the editor's char-based cursor.
pub(super) fn find_char_index(line: &str, term: &str, from: usize) -> Option<usize> {
    let chars: Vec<char> = line.chars().collect();
    let needle: Vec<char> = term.chars().collect();
    let tlen = needle.len();
    if tlen == 0 || chars.len() < tlen {
        return None;
    }
    (from..=chars.len() - tlen).find(|&i| chars[i..i + tlen] == needle[..])
}

/// Last char index `< limit` where `term` begins in `line`.
pub(super) fn rfind_char_index(line: &str, term: &str, limit: usize) -> Option<usize> {
    let chars: Vec<char> = line.chars().collect();
    let needle: Vec<char> = term.chars().collect();
    let tlen = needle.len();
    if tlen == 0 || chars.len() < tlen {
        return None;
    }
    let upper = limit.min(chars.len() - tlen + 1);
    (0..upper).rev().find(|&i| chars[i..i + tlen] == needle[..])
}

pub(super) fn is_plain_letter(key: KeyEvent, letter: char) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if c != letter {
        return false;
    }
    !(key.modifiers.contains(KeyModifiers::CONTROL)
        || key.modifiers.contains(KeyModifiers::SUPER)
        || key.modifiers.contains(KeyModifiers::ALT))
}