kimun-notes 0.18.0

A terminal-based notes application
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
//! Built-in vim emulation: a modal input interpreter over a `TextArea`.
//! Pure over `&mut TextArea` — no component state, no async (adr/0012).

use super::snapshot::EditorMode;
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui_textarea::{CursorMove, TextArea};

/// Screen-level actions the host performs on the engine's behalf (adr/0012).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VimHostAction {
    OpenPalette,                  // `:`
    OpenSearch { forward: bool }, // `/` (true) `?` (false)
    SearchNext,                   // `n`
    SearchPrev,                   // `N`
}

/// What a key did, so the host can bump the right revision counters.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VimKeyOutcome {
    /// Buffer text changed — host calls `bump_content()`.
    TextMutated,
    /// Only the cursor/selection moved — host refreshes view, not content.
    CursorOnly,
    /// Nothing happened (unmapped key in Normal mode).
    NoOp,
    /// Insert mode: defer to the existing `handle_textarea_key` path.
    PassThrough,
    /// The host must perform a screen-level action.
    Host(VimHostAction),
}

// ── Reified command model (adr/0011) ────────────────────────────────────────

/// A cursor motion. Operators consume a motion to form a range.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Motion {
    Left,
    Right,
    Up,
    Down,
    WordForward,
    WordBack,
    WordEnd,
    WordForwardBig,            // W — WORD: any non-blank run
    WordBackBig,               // B
    WordEndBig,                // E
    WordEndBack { big: bool }, // ge / gE
    LineStart,
    FirstNonBlank,
    LastNonBlank, // g_
    LineEnd,
    FileStart,
    FileEnd,
    GotoLine(usize), // 5gg / 5G (1-based)
    ParagraphForward,
    ParagraphBack,
    MatchingPair,                                     // %
    FindChar { ch: char, till: bool, forward: bool }, // f/F/t/T
}

/// An operator awaiting a motion or text object.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Operator {
    Delete,
    Change,
    Yank,
    Indent,
    Outdent,
    Lowercase,  // gu
    Uppercase,  // gU
    ToggleCase, // g~
}

/// How a motion forms an operator range (vim `:h exclusive`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SpanKind {
    /// Half-open `[start, end)` char range.
    Exclusive,
    /// Includes the char at `end` (`[start, end]`).
    Inclusive,
    /// Whole lines from `start.row` through `end.row`.
    Linewise,
}

/// A text object (`iw`, `a"`, …).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextObject {
    Word {
        around: bool,
    },
    Pair {
        open: char,
        close: char,
        around: bool,
    },
    Quote {
        ch: char,
        around: bool,
    },
}

/// Where an insert-entry command places the cursor before entering Insert.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InsertEntry {
    Here,      // i
    After,     // a
    LineStart, // I
    LineEnd,   // A
    OpenBelow, // o
    OpenAbove, // O
}

/// The fully-parsed unit of work (adr/0011). `apply` is the only door that
/// mutates the buffer; dot-repeat (and future macros) replay these values
/// through that same door, so first press and replay cannot diverge.
#[derive(Debug, Clone)]
pub enum Command {
    Move(Motion, usize),
    OperateMotion(Operator, Motion, usize),      // e.g. 2dw
    OperateLine(Operator, usize),                // dd / cc / yy with count
    OperateObject(Operator, TextObject),         // diw, ci"
    OperateToLineEnd(Operator),                  // D / C / Y
    IndentLines { outdent: bool, count: usize }, // >> / <<
    DeleteChar { forward: bool, count: usize },  // x / X
    ReplaceChar(char),                           // r<ch>
    SubstituteChar(usize),                       // s
    SubstituteLine,                              // S
    JoinLines { count: usize, spaced: bool },    // J (spaced) / gJ (raw)
    ToggleCase(usize),                           // ~
    Paste { after: bool, count: usize },         // p / P
    Undo(usize),                                 // u
    Redo(usize),                                 // Ctrl-r
    EnterInsert(InsertEntry),                    // i a I A o O
    EnterReplace,                                // R — overwrite until Esc
    EnterVisual { line: bool },                  // v / V
    Repeat,                                      // .
}

/// One key of the g-command grammar (the key AFTER a pending `g`). Produced
/// by `g_key_for`, consumed by both the Normal parser and the Visual handler.
enum GKey {
    /// `gg` — file start, or line N when a count is pending.
    GotoLine,
    /// `ge` / `gE` / `g_` — plain motions.
    Motion(Motion),
    /// `gu` / `gU` / `g~` — case operators.
    CaseOp(Operator),
    /// `gJ` — join without space handling.
    Join,
}

/// What one Normal-mode key parsed into. Parsing never touches the buffer;
/// `Cmd` is the only variant that leads to mutation — via `apply`.
enum Parsed {
    /// Accumulated pending state; wait for more keys.
    Pending,
    Cmd(Command),
    Host(VimHostAction),
    /// Esc — pending state cleared, host-side selection cleanup applies.
    Cancel,
    /// Unmapped key.
    Nothing,
}

// ── Pending-state helper types ───────────────────────────────────────────────

#[derive(Debug, Clone, Copy)]
struct PendingFind {
    operator: Option<Operator>,
    till: bool,
    forward: bool,
}

/// A one-key continuation: the parser saw a prefix and waits for exactly one
/// more key. One field holds them all, so every ceremony site (clear,
/// space_leads, the footer hint) checks a single state instead of a drifting
/// list of flags — and a future `q`/`"`/`m` prefix is one new variant.
#[derive(Debug, Clone, Copy)]
enum Awaiting {
    /// `g` — the g-command grammar (`g_key_for`).
    G,
    /// `r` — the replacement char.
    ReplaceChar,
    /// `f`/`F`/`t`/`T` — the find target (the operator was captured at entry).
    Find(PendingFind),
    /// `i`/`a` after an operator (or in charwise Visual) — the object key.
    ObjectScope { around: bool },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RegisterKind {
    Charwise,
    Linewise,
}

/// One register's value — content and kind live together so they cannot
/// desync (adr/0011: the register is internal vim state, kept separate from
/// the textarea's yank buffer and the OS clipboard).
#[derive(Debug, Clone)]
struct RegisterValue {
    text: String,
    kind: RegisterKind,
}

/// The engine-owned register file. Only the unnamed register exists today;
/// named registers (v2) add a map alongside without touching operator code.
#[derive(Debug, Default)]
struct Registers {
    unnamed: Option<RegisterValue>,
}

impl Registers {
    /// Vim rule: every yank AND every delete/change fills the unnamed
    /// register. Empty text never overwrites it (a no-op delete keeps the
    /// previous content, matching vim).
    fn fill(&mut self, text: String, kind: RegisterKind) {
        if text.is_empty() {
            return;
        }
        self.unnamed = Some(RegisterValue { text, kind });
    }

    fn read(&self) -> Option<&RegisterValue> {
        self.unnamed.as_ref()
    }
}

#[derive(Debug, Clone)]
struct Change {
    command: Command,
    inserted: Option<String>,
}

#[derive(Debug, Clone)]
struct InsertCapture {
    command: Command,
    start: (usize, usize),
}

// ── VimEngine ────────────────────────────────────────────────────────────────

/// Modal vim state layered over the textarea buffer.
#[derive(Debug)]
pub struct VimEngine {
    mode: EditorMode,
    // pending-state + dot-repeat fields
    pending_count: Option<usize>,
    /// Count typed BEFORE the operator (`2` in `2d3w`); multiplied with the
    /// motion count at completion (vim: `2d3w` deletes 6 words).
    pending_op_count: Option<usize>,
    pending_operator: Option<Operator>,
    /// The one-key continuation the parser is waiting on (g-prefix, find
    /// target, replace char, object key) — mutually exclusive by type.
    awaiting: Option<Awaiting>,
    last_find: Option<(char, bool, bool)>, // (ch, till, forward) for ; and ,
    registers: Registers,
    /// The last mutating command + captured insert delta, for `.` (adr/0011).
    last_change: Option<Change>,
    /// While in Insert via a vim command, the text typed is accumulated here
    /// (resulting delta) so `.` can replay it.
    insert_capture: Option<InsertCapture>,
    /// Replace mode's restore stack: what each overwritten position held
    /// (`None` = the char was appended past EOL). Backspace pops it.
    replace_stack: Vec<Option<char>>,
}

impl Default for VimEngine {
    fn default() -> Self {
        Self {
            mode: EditorMode::Normal,
            pending_count: None,
            pending_op_count: None,
            pending_operator: None,
            awaiting: None,
            last_find: None,
            registers: Registers::default(),
            last_change: None,
            insert_capture: None,
            replace_stack: Vec::new(),
        }
    }
}

impl VimEngine {
    pub fn mode(&self) -> &EditorMode {
        &self.mode
    }

    /// Footer label for the current mode (e.g. "NORMAL").
    pub fn mode_label(&self) -> String {
        self.mode.label().to_string()
    }

    /// The in-progress command sequence, for the footer hint (e.g. "2d", "f").
    /// Returns `None` when nothing is pending (no display needed).
    pub fn pending_hint(&self) -> Option<String> {
        // Fast path: nothing pending — skip all allocation (common idle-frame case).
        if self.pending_count.is_none()
            && self.pending_op_count.is_none()
            && self.pending_operator.is_none()
            && self.awaiting.is_none()
        {
            return None;
        }
        let mut s = String::new();
        if let Some(n) = self.pending_op_count {
            s.push_str(&n.to_string());
        }
        if let Some(op) = self.pending_operator {
            s.push_str(match op {
                Operator::Delete => "d",
                Operator::Change => "c",
                Operator::Yank => "y",
                Operator::Indent => ">",
                Operator::Outdent => "<",
                Operator::Lowercase => "gu",
                Operator::Uppercase => "gU",
                Operator::ToggleCase => "g~",
            });
        }
        if let Some(n) = self.pending_count {
            s.push_str(&n.to_string());
        }
        match self.awaiting {
            Some(Awaiting::G) => s.push('g'),
            Some(Awaiting::ReplaceChar) => s.push('r'),
            Some(Awaiting::Find(pf)) => s.push(match (pf.till, pf.forward) {
                (false, true) => 'f',
                (false, false) => 'F',
                (true, true) => 't',
                (true, false) => 'T',
            }),
            Some(Awaiting::ObjectScope { around }) => s.push(if around { 'a' } else { 'i' }),
            None => {}
        }
        if s.is_empty() { None } else { Some(s) }
    }

    pub fn reset_to_normal(&mut self) {
        self.mode = EditorMode::Normal;
        self.clear_pending();
        // A capture from an interrupted Insert (e.g. note switch mid-`cw`)
        // must not survive: execute() skips dot-recording while one is live,
        // which would silently disable `.` for every later change.
        self.insert_capture = None;
    }

    /// Reconcile mode after a host-driven selection change (mouse). A live
    /// selection means Visual; losing the selection in Visual returns to Normal.
    pub fn sync_mouse_selection(&mut self, has_selection: bool) {
        match (has_selection, &self.mode) {
            (true, EditorMode::Normal) => self.mode = EditorMode::Visual,
            (false, EditorMode::Visual) | (false, EditorMode::VisualLine) => {
                self.mode = EditorMode::Normal
            }
            _ => {}
        }
    }

    /// True when a bare Space should start the leader: Normal mode, nothing
    /// pending (so `d<Space>`, `f<Space>`, counts etc. still take Space as an
    /// argument/motion, not the leader).
    pub fn space_leads(&self) -> bool {
        self.mode == EditorMode::Normal
            && self.pending_count.is_none()
            && self.pending_op_count.is_none()
            && self.pending_operator.is_none()
            && self.awaiting.is_none()
    }

    /// Interpret one key. In Insert mode everything except `Esc` is
    /// `PassThrough` (the host runs the existing direct textarea path).
    /// In Visual/VisualLine mode, motions extend the selection; operators
    /// act on the live selection. In Normal mode, motions move the cursor
    /// and the insert-entry keys switch to Insert mode.
    pub fn handle_key(&mut self, key: &KeyEvent, ta: &mut TextArea<'static>) -> VimKeyOutcome {
        match self.mode {
            EditorMode::Insert => self.handle_insert(key, ta),
            EditorMode::Replace => self.handle_replace(key, ta),
            EditorMode::Visual | EditorMode::VisualLine => self.handle_visual(key, ta),
            _ => self.handle_normal(key, ta),
        }
    }

    // ── Visual + Visual-line mode handler ────────────────────────────────────

    fn handle_visual(&mut self, key: &KeyEvent, ta: &mut TextArea<'static>) -> VimKeyOutcome {
        // One-key continuations consume the next key first: the find target
        // (`vf,` extends through the ','), and the object key after `i`/`a`
        // (`vi(` re-aims the selection at the object). The g continuation is
        // resolved below where the full key context is available.
        match self.awaiting {
            Some(Awaiting::Find(pf)) => {
                self.awaiting = None;
                if let KeyCode::Char(ch) = key.code {
                    self.last_find = Some((ch, pf.till, pf.forward));
                    let cnt = self.take_count();
                    let motion = Motion::FindChar {
                        ch,
                        till: pf.till,
                        forward: pf.forward,
                    };
                    self.apply_motion(motion, cnt, ta);
                    return VimKeyOutcome::CursorOnly;
                }
                self.clear_pending();
                return VimKeyOutcome::NoOp;
            }
            Some(Awaiting::ObjectScope { around }) => {
                self.awaiting = None;
                if let KeyCode::Char(ch) = key.code
                    && let Some(obj) = Self::object_for_char(ch, around)
                {
                    Self::select_object_visual(obj, ta);
                    self.clear_pending();
                    return VimKeyOutcome::CursorOnly;
                }
                self.clear_pending();
                return VimKeyOutcome::NoOp;
            }
            _ => {}
        }

        // Esc: cancel selection and return to Normal.
        if key.code == KeyCode::Esc {
            ta.cancel_selection();
            self.mode = EditorMode::Normal;
            self.clear_pending();
            return VimKeyOutcome::CursorOnly;
        }

        // Arrow keys: extend the selection.
        let plain = key.modifiers == KeyModifiers::NONE || key.modifiers == KeyModifiers::SHIFT;
        let KeyCode::Char(c) = key.code else {
            match key.code {
                KeyCode::Left => {
                    ta.move_cursor(CursorMove::Back);
                    return VimKeyOutcome::CursorOnly;
                }
                KeyCode::Right => {
                    ta.move_cursor(CursorMove::Forward);
                    return VimKeyOutcome::CursorOnly;
                }
                KeyCode::Up => {
                    ta.move_cursor(CursorMove::Up);
                    return VimKeyOutcome::CursorOnly;
                }
                KeyCode::Down => {
                    ta.move_cursor(CursorMove::Down);
                    return VimKeyOutcome::CursorOnly;
                }
                _ => return VimKeyOutcome::NoOp,
            }
        };
        if !plain {
            return VimKeyOutcome::NoOp;
        }

        // Count accumulation.
        if self.accumulate_count(c) {
            return VimKeyOutcome::NoOp;
        }

        // Operators act on the EXISTING live selection (already started by v/V).
        // In VisualLine mode: use linewise deletion (preserves newlines correctly).
        // In Visual mode: use charwise cut on the current selection.
        let op = match c {
            'd' | 'x' => Some(Operator::Delete),
            'c' | 's' => Some(Operator::Change),
            'y' => Some(Operator::Yank),
            // vim visual case ops. `~` stays on the auto-surround
            // PassThrough path below (kimün wraps the selection instead).
            'u' => Some(Operator::Lowercase),
            'U' => Some(Operator::Uppercase),
            _ => None,
        };
        if let Some(op) = op {
            return self.visual_operate(op, ta);
        }

        // 'p'/'P': replace the current visual selection with the register.
        // The register is engine-owned, so the cut below cannot clobber it.
        if c == 'p' || c == 'P' {
            let Some(reg) = self.registers.read().cloned() else {
                ta.cancel_selection();
                self.mode = EditorMode::Normal;
                return VimKeyOutcome::CursorOnly;
            };
            let text = reg.text;
            if self.mode == EditorMode::VisualLine {
                // VisualLine: delete the selected whole lines, then paste the
                // saved content. The delete fills the register with the deleted
                // lines — vim swap behavior — while `text` keeps the original.
                let (start_row, end_row) = if let Some(((sr, _), (er, _))) = ta.selection_range() {
                    (sr, er)
                } else {
                    let (r, _) = super::cursor_tuple(ta);
                    (r, r)
                };
                ta.cancel_selection();
                ta.move_cursor(CursorMove::Jump(start_row as u16, 0));
                let count = end_row - start_row + 1;
                self.apply_operator_linewise(Operator::Delete, count, None, ta);
                let body = text.strip_suffix('\n').unwrap_or(&text);
                ta.move_cursor(CursorMove::Head);
                ta.insert_str(body);
                ta.insert_newline();
                ta.move_cursor(CursorMove::Up);
            } else {
                // Charwise: make an inclusive selection, delete it, and fill
                // the register with the deleted text (vim swap: the replaced
                // selection enters the register), then insert the saved `text`.
                if let Some((start, end)) = ta.selection_range() {
                    ta.cancel_selection();
                    Self::select_range(ta, start, end, true);
                }
                ta.cut(); // cursor lands at the deletion gap
                self.fill_from_textarea(ta, RegisterKind::Charwise);
                // Record where the paste starts so we can leave the cursor there
                // (vim visual-p leaves cursor at the start of the pasted text).
                let paste_start = super::cursor_tuple(ta);
                ta.insert_str(&text); // insert the SAVED content, not the yank buffer
                ta.move_cursor(CursorMove::Jump(paste_start.0 as u16, paste_start.1 as u16));
            }
            self.mode = EditorMode::Normal;
            self.clear_pending();
            return VimKeyOutcome::TextMutated;
        }

        // 'o': swap cursor and anchor (vim: move to the other end of the
        // selection so it can be extended from there).
        if c == 'o' {
            if let Some((start, end)) = ta.selection_range() {
                let cur = super::cursor_tuple(ta);
                let other = if cur == end { start } else { end };
                ta.cancel_selection();
                ta.move_cursor(CursorMove::Jump(cur.0 as u16, cur.1 as u16));
                ta.start_selection();
                ta.move_cursor(CursorMove::Jump(other.0 as u16, other.1 as u16));
            }
            return VimKeyOutcome::CursorOnly;
        }

        // Visual `>`/`<` — indent/outdent the selected line range.
        if c == '>' || c == '<' {
            let outdent = c == '<';
            let line_count = if let Some(((sr, _), (er, _))) = ta.selection_range() {
                er.saturating_sub(sr) + 1
            } else {
                1
            };
            // Cancel selection; jump to first selected row; then indent.
            let start_row = if let Some(((sr, _), _)) = ta.selection_range() {
                sr
            } else {
                super::cursor_tuple(ta).0
            };
            ta.cancel_selection();
            ta.move_cursor(CursorMove::Jump(start_row as u16, 0));
            self.indent_lines(outdent, line_count, ta);
            self.mode = EditorMode::Normal;
            self.clear_pending();
            return VimKeyOutcome::TextMutated;
        }

        // Pair chars: set Normal and return PassThrough so the host's existing
        // auto-surround path wraps the selection. Skipped while a `g` is
        // pending — `g~` (case toggle) must reach the g-block below.
        if !matches!(self.awaiting, Some(Awaiting::G))
            && matches!(
                c,
                '(' | '[' | '{' | '<' | '"' | '\'' | '`' | '*' | '_' | '~'
            )
        {
            self.mode = EditorMode::Normal;
            return VimKeyOutcome::PassThrough;
        }

        // g prefix — the same shared g-command grammar as Normal mode,
        // dispatched against the selection. Case ops run on the selection
        // (bare `~` belongs to auto-surround in kimün, so g~ is the visual
        // toggle-case key); gJ joins the selected lines raw.
        if c == 'g' && !matches!(self.awaiting, Some(Awaiting::G)) {
            self.awaiting = Some(Awaiting::G);
            return VimKeyOutcome::NoOp;
        }
        if matches!(self.awaiting, Some(Awaiting::G)) {
            self.awaiting = None;
            return match Self::g_key_for(c) {
                Some(GKey::GotoLine) => {
                    let m = match self.pending_count.take() {
                        Some(n) => Motion::GotoLine(n),
                        None => Motion::FileStart,
                    };
                    self.apply_motion(m, 1, ta);
                    self.clear_pending();
                    VimKeyOutcome::CursorOnly
                }
                Some(GKey::Motion(m)) => {
                    let cnt = self.take_count();
                    self.apply_motion(m, cnt, ta);
                    self.clear_pending();
                    VimKeyOutcome::CursorOnly
                }
                Some(GKey::CaseOp(op)) => self.visual_operate(op, ta),
                Some(GKey::Join) => self.visual_join(false, ta),
                None => {
                    self.clear_pending();
                    VimKeyOutcome::NoOp
                }
            };
        }

        // J: join the selected lines with vim's space handling.
        if c == 'J' {
            return self.visual_join(true, ta);
        }

        // f/F/t/T: pend a selection-extending find.
        if let Some((till, forward)) = Self::find_spec_for(c) {
            self.awaiting = Some(Awaiting::Find(PendingFind {
                operator: None,
                till,
                forward,
            }));
            return VimKeyOutcome::NoOp;
        }

        // ; and , repeat the last find, extending the selection.
        if c == ';' || c == ',' {
            if let Some(motion) = self.repeat_find_motion(c) {
                let cnt = self.take_count();
                self.apply_motion(motion, cnt, ta);
            }
            self.clear_pending();
            return VimKeyOutcome::CursorOnly;
        }

        // i/a: text-object selection (charwise Visual only — `vi(`, `va"`).
        if (c == 'i' || c == 'a') && self.mode == EditorMode::Visual {
            self.awaiting = Some(Awaiting::ObjectScope { around: c == 'a' });
            return VimKeyOutcome::NoOp;
        }

        // Motions extend the selection. 5G extends to line 5 (count = line
        // number, matching the Normal-mode parser); the count is only
        // consumed for 'G' — every other motion keeps it as a repeat.
        if let Some(m) = Self::motion_for_char(c) {
            let m = if c == 'G' {
                match self.pending_count.take() {
                    Some(n) => Motion::GotoLine(n),
                    None => m,
                }
            } else {
                m
            };
            let count = self.take_count();
            self.apply_motion(m, count, ta);
            self.clear_pending();
            return VimKeyOutcome::CursorOnly;
        }

        self.clear_pending();
        VimKeyOutcome::NoOp
    }

    /// Visual `J` / `gJ`: join all selected lines into one (vim), then
    /// return to Normal mode.
    fn visual_join(&mut self, spaced: bool, ta: &mut TextArea<'static>) -> VimKeyOutcome {
        let (start_row, end_row) = if let Some(((sr, _), (er, _))) = ta.selection_range() {
            (sr, er)
        } else {
            let (r, _) = super::cursor_tuple(ta);
            (r, r)
        };
        ta.cancel_selection();
        ta.move_cursor(CursorMove::Jump(start_row as u16, 0));
        let joins = end_row.saturating_sub(start_row).max(1);
        for _ in 0..joins {
            Self::join_line(ta, spaced);
        }
        self.mode = EditorMode::Normal;
        self.clear_pending();
        VimKeyOutcome::TextMutated
    }

    /// Apply `op` to the live visual selection (charwise or linewise) and
    /// leave Visual mode. Shared by the visual operator keys (d/x/c/s/y/u/U)
    /// and `g~`.
    fn visual_operate(&mut self, op: Operator, ta: &mut TextArea<'static>) -> VimKeyOutcome {
        if self.mode == EditorMode::VisualLine {
            // VisualLine: operate on whole selected lines, preserving newlines.
            let (start_row, end_row) = if let Some(((sr, _), (er, _))) = ta.selection_range() {
                (sr, er)
            } else {
                let (r, _) = super::cursor_tuple(ta);
                (r, r)
            };
            // Cancel the current selection so apply_operator_linewise can
            // re-anchor from the correct start row.
            ta.cancel_selection();
            ta.move_cursor(CursorMove::Jump(start_row as u16, 0));
            let count = end_row - start_row + 1;
            self.apply_operator_linewise(op, count, None, ta);
        } else {
            // Charwise Visual: vim selection is inclusive of the char under
            // the cursor — re-select through select_range's inclusive end.
            let range = ta.selection_range();
            if let Some((start, end)) = range {
                ta.cancel_selection();
                Self::select_range(ta, start, end, true);
            }
            if op == Operator::Change {
                // Honest dot-repeat: `.` after a visual change replays a
                // same-sized change from the cursor (vim semantics) —
                // chars on one row, whole lines across rows.
                let capture_cmd = match range {
                    Some(((sr, sc), (er, ec))) if sr == er => Command::OperateMotion(
                        Operator::Change,
                        Motion::Right,
                        ec.saturating_sub(sc) + 1,
                    ),
                    Some(((sr, _), (er, _))) => {
                        Command::OperateLine(Operator::Change, er.saturating_sub(sr) + 1)
                    }
                    None => Command::OperateMotion(Operator::Change, Motion::Right, 1),
                };
                ta.cut();
                self.fill_from_textarea(ta, RegisterKind::Charwise);
                self.finish_insert_entry(&capture_cmd, None, ta);
            } else {
                self.apply_operator_on_selection(op, ta);
            }
        }
        // Change paths own the Insert transition (via the insert capture);
        // everything else returns to Normal here — one writer per transition.
        if op != Operator::Change {
            self.mode = EditorMode::Normal;
        }
        self.clear_pending();
        Self::outcome_for(op)
    }

    /// Re-aim the charwise visual selection at the text object under the
    /// cursor. The selection end is left ON the object's last char (visual
    /// selections are inclusive; the operator's inclusive `+1` restores the
    /// half-open range `object_range` computed).
    fn select_object_visual(obj: TextObject, ta: &mut TextArea<'static>) {
        let Some((row, start, end)) = Self::object_range_at_cursor(ta, obj) else {
            return;
        };
        if start >= end {
            // Empty object (vi( on "()"): collapsing to one char would make
            // the operator's inclusive +1 grab the closing delimiter. No-op.
            return;
        }
        ta.cancel_selection();
        // Leave the selection end ON the object's last char (visual
        // selections are inclusive; the operator's +1 restores [start, end)).
        Self::select_range(ta, (row, start), (row, end - 1), false);
    }

    // ── Insert + Replace mode handlers ───────────────────────────────────────

    fn handle_insert(&mut self, key: &KeyEvent, ta: &mut TextArea<'static>) -> VimKeyOutcome {
        if key.code == KeyCode::Esc {
            return self.exit_to_normal(ta);
        }
        VimKeyOutcome::PassThrough
    }

    /// Replace (overwrite) mode — vim `R`. Keys are handled by the engine,
    /// never passed to the host textarea path: R is raw overwrite, with no
    /// auto-surround / smart-Enter underneath.
    fn handle_replace(&mut self, key: &KeyEvent, ta: &mut TextArea<'static>) -> VimKeyOutcome {
        // A live selection (mouse drag) would make the textarea's delete/
        // insert calls wipe it wholesale on the next keypress — drop it.
        if ta.selection_range().is_some() {
            ta.cancel_selection();
        }
        let plain = key.modifiers == KeyModifiers::NONE || key.modifiers == KeyModifiers::SHIFT;
        match key.code {
            KeyCode::Esc => self.exit_to_normal(ta),
            KeyCode::Enter => {
                ta.insert_newline();
                // The newline starts a fresh replace extent.
                self.replace_stack.clear();
                VimKeyOutcome::TextMutated
            }
            KeyCode::Backspace => {
                // vim's replace stack: Backspace restores what the position
                // held before it was overwritten; an appended char (None) is
                // simply removed. Past the extent it's a plain step back.
                if super::cursor_tuple(ta).1 > 0 {
                    ta.move_cursor(CursorMove::Back);
                    match self.replace_stack.pop() {
                        Some(Some(orig)) => {
                            ta.delete_next_char();
                            ta.insert_char(orig);
                            ta.move_cursor(CursorMove::Back);
                            return VimKeyOutcome::TextMutated;
                        }
                        Some(None) => {
                            ta.delete_next_char();
                            return VimKeyOutcome::TextMutated;
                        }
                        None => {}
                    }
                }
                VimKeyOutcome::CursorOnly
            }
            KeyCode::Left | KeyCode::Right | KeyCode::Up | KeyCode::Down => {
                // vim allows movement in Replace mode and resets the replace
                // extent — restart the dot capture and the restore stack.
                ta.move_cursor(match key.code {
                    KeyCode::Left => CursorMove::Back,
                    KeyCode::Right => CursorMove::Forward,
                    KeyCode::Up => CursorMove::Up,
                    _ => CursorMove::Down,
                });
                let here = super::cursor_tuple(ta);
                if let Some(cap) = self.insert_capture.as_mut() {
                    cap.start = here;
                }
                self.replace_stack.clear();
                VimKeyOutcome::CursorOnly
            }
            KeyCode::Char(c) if plain => {
                // Record what this position held (None = appended past EOL)
                // so Backspace can restore it.
                let (row, col) = super::cursor_tuple(ta);
                let orig = ta.lines().get(row).and_then(|l| l.chars().nth(col));
                self.replace_stack.push(orig);
                Self::overwrite_char(ta, c);
                VimKeyOutcome::TextMutated
            }
            _ => VimKeyOutcome::NoOp,
        }
    }

    /// Overwrite the char under the cursor (plain insert at EOL — vim R
    /// appends once the line runs out), cursor left after the written char.
    fn overwrite_char(ta: &mut TextArea<'static>, ch: char) {
        if ch == '\n' {
            ta.insert_newline();
            return;
        }
        let (row, col) = super::cursor_tuple(ta);
        let len = ta.lines().get(row).map(|l| l.chars().count()).unwrap_or(0);
        if col < len {
            ta.delete_next_char();
        }
        ta.insert_char(ch);
    }

    /// Esc out of Insert/Replace mode: finalize the dot capture and step the
    /// cursor back (vim).
    fn exit_to_normal(&mut self, ta: &mut TextArea<'static>) -> VimKeyOutcome {
        self.mode = EditorMode::Normal;
        self.replace_stack.clear();
        // A stray selection (mouse drag mid-Insert/Replace) must not survive
        // into Normal mode, where motions would silently extend it.
        ta.cancel_selection();
        // Compute the typed text once at Esc, slicing from the start cursor
        // recorded when Insert/Replace began to the current cursor.
        if let Some(cap) = self.insert_capture.take() {
            let end = super::cursor_tuple(ta);
            let inserted = Self::text_between(ta.lines(), cap.start, end);
            if !inserted.is_empty() || Self::records_when_empty(&cap.command) {
                self.last_change = Some(Change {
                    command: cap.command,
                    inserted: Some(inserted),
                });
            }
        }
        if super::cursor_tuple(ta).1 > 0 {
            ta.move_cursor(CursorMove::Back);
        }
        VimKeyOutcome::CursorOnly
    }

    // ── Normal mode: keys → parse → Command → execute/apply (adr/0011) ───────

    fn handle_normal(&mut self, key: &KeyEvent, ta: &mut TextArea<'static>) -> VimKeyOutcome {
        match self.parse_normal(key) {
            Parsed::Pending | Parsed::Nothing => VimKeyOutcome::NoOp,
            Parsed::Cancel => {
                // Esc also cancels any stray textarea selection left live in
                // Normal mode (e.g. the auto-surround PassThrough path).
                ta.cancel_selection();
                VimKeyOutcome::CursorOnly
            }
            Parsed::Host(action) => {
                self.clear_pending();
                VimKeyOutcome::Host(action)
            }
            Parsed::Cmd(cmd) => self.execute(cmd, ta),
        }
    }

    /// Parse one Normal-mode key into a `Parsed` value. Pure pending-state
    /// accumulation — never touches the buffer (adr/0011).
    fn parse_normal(&mut self, key: &KeyEvent) -> Parsed {
        // One-key continuations (g-prefix, find target, replace char, object
        // key) consume the next key before anything else.
        if let Some(aw) = self.awaiting.take() {
            return self.parse_awaiting(aw, key);
        }

        // Esc cancels any pending sequence (operator, counts).
        if key.code == KeyCode::Esc {
            self.clear_pending();
            return Parsed::Cancel;
        }

        // Ctrl-r → redo (before the plain filter so it isn't stripped).
        if key.code == KeyCode::Char('r') && key.modifiers.contains(KeyModifiers::CONTROL) {
            return Parsed::Cmd(Command::Redo(self.take_total_count()));
        }

        let plain = key.modifiers == KeyModifiers::NONE || key.modifiers == KeyModifiers::SHIFT;
        match key.code {
            KeyCode::Char(c) if plain => self.parse_normal_char(c),
            KeyCode::Left => Parsed::Cmd(Command::Move(Motion::Left, 1)),
            KeyCode::Right => Parsed::Cmd(Command::Move(Motion::Right, 1)),
            KeyCode::Up => Parsed::Cmd(Command::Move(Motion::Up, 1)),
            KeyCode::Down => Parsed::Cmd(Command::Move(Motion::Down, 1)),
            _ => Parsed::Nothing,
        }
    }

    /// Consume the single key a continuation was waiting for. Non-char keys
    /// cancel the whole pending sequence (vim); Esc additionally clears any
    /// stray selection via the `Cancel` path.
    fn parse_awaiting(&mut self, aw: Awaiting, key: &KeyEvent) -> Parsed {
        let KeyCode::Char(c) = key.code else {
            self.clear_pending();
            return if key.code == KeyCode::Esc {
                Parsed::Cancel
            } else {
                Parsed::Nothing
            };
        };
        match aw {
            Awaiting::ReplaceChar => Parsed::Cmd(Command::ReplaceChar(c)),
            Awaiting::Find(pf) => {
                self.last_find = Some((c, pf.till, pf.forward));
                let motion = Motion::FindChar {
                    ch: c,
                    till: pf.till,
                    forward: pf.forward,
                };
                match pf.operator {
                    Some(op) => {
                        Parsed::Cmd(Command::OperateMotion(op, motion, self.take_total_count()))
                    }
                    None => Parsed::Cmd(Command::Move(motion, self.take_count())),
                }
            }
            Awaiting::G => self.parse_g_key(c),
            Awaiting::ObjectScope { around } => {
                if let Some(obj) = Self::object_for_char(c, around)
                    && let Some(op) = self.pending_operator.take()
                {
                    self.clear_pending();
                    return Parsed::Cmd(Command::OperateObject(op, obj));
                }
                self.clear_pending();
                Parsed::Nothing
            }
        }
    }

    /// The key after a pending `g`, dispatched through the shared g-command
    /// grammar (`g_key_for`).
    fn parse_g_key(&mut self, c: char) -> Parsed {
        match Self::g_key_for(c) {
            Some(GKey::GotoLine) => {
                // A count is a line number (5gg → line 5), wherever it was
                // typed relative to a pending operator (d5gg / 5dgg).
                let target = self
                    .pending_count
                    .take()
                    .or_else(|| self.pending_op_count.take());
                let m = match target {
                    Some(n) => Motion::GotoLine(n),
                    None => Motion::FileStart,
                };
                match self.pending_operator.take() {
                    Some(op) => Parsed::Cmd(Command::OperateMotion(op, m, 1)),
                    None => Parsed::Cmd(Command::Move(m, 1)),
                }
            }
            Some(GKey::Motion(m)) => match self.pending_operator.take() {
                Some(op) => Parsed::Cmd(Command::OperateMotion(op, m, self.take_total_count())),
                None => Parsed::Cmd(Command::Move(m, self.take_count())),
            },
            Some(GKey::CaseOp(op)) => {
                // gugu / gUgU / g~g~: the doubled g-form runs linewise.
                if self.pending_operator == Some(op) {
                    self.pending_operator = None;
                    return Parsed::Cmd(Command::OperateLine(op, self.take_total_count()));
                }
                self.pending_operator = Some(op);
                self.pending_op_count = self.pending_count.take();
                Parsed::Pending
            }
            Some(GKey::Join) => Parsed::Cmd(Command::JoinLines {
                count: self.take_count().max(2) - 1,
                spaced: false,
            }),
            None => {
                // Unmapped g-sequence aborts the whole pending state (vim).
                self.clear_pending();
                Parsed::Nothing
            }
        }
    }

    // ── parse_normal_char: pure Normal-mode key parser ───────────────────────

    /// Parse one plain Normal-mode char. Pure pending-state accumulation —
    /// commands come out as values; nothing here touches the buffer.
    fn parse_normal_char(&mut self, c: char) -> Parsed {
        // Count digits accumulate first.
        if self.accumulate_count(c) {
            return Parsed::Pending;
        }

        // g prefix — the next key resolves through the g-command grammar.
        if c == 'g' {
            self.awaiting = Some(Awaiting::G);
            return Parsed::Pending;
        }

        // guu / gUU / g~~: the doubled-key form runs the case op linewise.
        if let Some(op) = self.pending_operator {
            let doubles = matches!(
                (op, c),
                (Operator::Lowercase, 'u')
                    | (Operator::Uppercase, 'U')
                    | (Operator::ToggleCase, '~')
            );
            if doubles {
                self.pending_operator = None;
                return Parsed::Cmd(Command::OperateLine(op, self.take_total_count()));
            }
        }

        // Operator entry (d/c/y set pending; doubled → linewise).
        let op_for_char = match c {
            'd' => Some(Operator::Delete),
            'c' => Some(Operator::Change),
            'y' => Some(Operator::Yank),
            _ => None,
        };
        if let Some(op) = op_for_char {
            if self.pending_operator == Some(op) {
                return Parsed::Cmd(Command::OperateLine(op, self.take_total_count()));
            }
            if self.pending_operator.is_some() {
                // A different operator while one is pending aborts (vim).
                self.clear_pending();
                return Parsed::Nothing;
            }
            self.pending_operator = Some(op);
            // A count typed so far scopes to the operator; the motion gets
            // its own accumulator (vim multiplies the two).
            self.pending_op_count = self.pending_count.take();
            return Parsed::Pending;
        }
        // D / C / Y → operator to line end.
        if let Some(op) = match c {
            'D' => Some(Operator::Delete),
            'C' => Some(Operator::Change),
            'Y' => Some(Operator::Yank),
            _ => None,
        } {
            if self.pending_operator.is_some() {
                self.clear_pending();
                return Parsed::Nothing; // dD etc. abort (vim)
            }
            return Parsed::Cmd(Command::OperateToLineEnd(op));
        }

        // >>/<< indent/outdent: first key sets the pending operator; the
        // doubled key completes linewise. A motion after the first key (e.g.
        // `>j`) instead forms a range via the motion dispatch below.
        if c == '>' || c == '<' {
            let outdent = c == '<';
            if (outdent && self.pending_operator == Some(Operator::Outdent))
                || (!outdent && self.pending_operator == Some(Operator::Indent))
            {
                self.pending_operator = None;
                return Parsed::Cmd(Command::IndentLines {
                    outdent,
                    count: self.take_total_count(),
                });
            }
            if self.pending_operator.is_some() {
                self.clear_pending();
                return Parsed::Nothing; // d> etc. abort (vim)
            }
            self.pending_operator = Some(if outdent {
                Operator::Outdent
            } else {
                Operator::Indent
            });
            self.pending_op_count = self.pending_count.take();
            return Parsed::Pending;
        }

        // Paste.
        if c == 'p' || c == 'P' {
            if self.pending_operator.is_some() {
                self.clear_pending();
                return Parsed::Nothing; // dp etc. abort (vim)
            }
            return Parsed::Cmd(Command::Paste {
                after: c == 'p',
                count: self.take_count(),
            });
        }

        // f/F/t/T — await the find target (captures the operator so `df,` works).
        if let Some((till, forward)) = Self::find_spec_for(c) {
            self.awaiting = Some(Awaiting::Find(PendingFind {
                operator: self.pending_operator.take(),
                till,
                forward,
            }));
            return Parsed::Pending;
        }

        // ; and , — repeat last find (same / opposite direction); with a
        // pending operator (`d;`) forms a range like any motion.
        if c == ';' || c == ',' {
            if let Some(motion) = self.repeat_find_motion(c) {
                return match self.pending_operator.take() {
                    Some(op) => {
                        Parsed::Cmd(Command::OperateMotion(op, motion, self.take_total_count()))
                    }
                    None => Parsed::Cmd(Command::Move(motion, self.take_count())),
                };
            }
            self.clear_pending();
            return Parsed::Nothing;
        }

        // Text objects — `i`/`a` with an operator pending awaits the object
        // key (so `di`/`ci`/`yi` never enter Insert; the object char is
        // consumed by parse_awaiting, not the motion dispatch).
        if self.pending_operator.is_some() && (c == 'i' || c == 'a') {
            self.awaiting = Some(Awaiting::ObjectScope { around: c == 'a' });
            return Parsed::Pending;
        }

        // Motion dispatch (count-aware; with a pending operator, forms a range).
        if let Some(m) = Self::motion_for_char(c) {
            // 5G goes to line 5 — the count is a line number, not a repeat.
            if c == 'G' {
                let target = self
                    .pending_count
                    .take()
                    .or_else(|| self.pending_op_count.take());
                let m = match target {
                    Some(n) => Motion::GotoLine(n),
                    None => m,
                };
                return match self.pending_operator.take() {
                    Some(op) => Parsed::Cmd(Command::OperateMotion(op, m, 1)),
                    None => Parsed::Cmd(Command::Move(m, 1)),
                };
            }
            return match self.pending_operator.take() {
                Some(op) => Parsed::Cmd(Command::OperateMotion(op, m, self.take_total_count())),
                None => Parsed::Cmd(Command::Move(m, self.take_count())),
            };
        }

        // A pending operator followed by a key that forms no motion, object,
        // find, or doubled form aborts the whole sequence (vim beeps and
        // cancels) — `gUu` must not run Undo, `dx` must not delete a char.
        if self.pending_operator.is_some() {
            self.clear_pending();
            return Parsed::Nothing;
        }

        // Single-key edits, dot, visual entry, host actions, insert entry.
        // NOTE: i/a only reach here when NO operator is pending — operator +
        // i/a is the text-object path above.
        let cmd = match c {
            'x' => Command::DeleteChar {
                forward: true,
                count: self.take_count(),
            },
            'X' => Command::DeleteChar {
                forward: false,
                count: self.take_count(),
            },
            'r' => {
                self.awaiting = Some(Awaiting::ReplaceChar);
                return Parsed::Pending;
            }
            's' => Command::SubstituteChar(self.take_count()),
            'S' => Command::SubstituteLine,
            'R' => Command::EnterReplace,
            'J' => Command::JoinLines {
                count: self.take_count().max(2) - 1,
                spaced: true,
            },
            '~' => Command::ToggleCase(self.take_count()),
            'u' => Command::Undo(self.take_count()),
            '.' => Command::Repeat,
            'v' => Command::EnterVisual { line: false },
            'V' => Command::EnterVisual { line: true },
            'i' => Command::EnterInsert(InsertEntry::Here),
            'a' => Command::EnterInsert(InsertEntry::After),
            'I' => Command::EnterInsert(InsertEntry::LineStart),
            'A' => Command::EnterInsert(InsertEntry::LineEnd),
            'o' => Command::EnterInsert(InsertEntry::OpenBelow),
            'O' => Command::EnterInsert(InsertEntry::OpenAbove),
            // Host actions — `:` `/` `?` `n` `N` (adr/0012). `?` backward-first
            // is deferred; `/` and `?` both open the find bar for v1.
            ':' => return Parsed::Host(VimHostAction::OpenPalette),
            '/' => return Parsed::Host(VimHostAction::OpenSearch { forward: true }),
            '?' => return Parsed::Host(VimHostAction::OpenSearch { forward: false }),
            'n' => return Parsed::Host(VimHostAction::SearchNext),
            'N' => return Parsed::Host(VimHostAction::SearchPrev),
            _ => {
                self.clear_pending();
                return Parsed::Nothing;
            }
        };
        Parsed::Cmd(cmd)
    }

    /// Run a freshly-parsed command through the one mutation door, recording
    /// it for `.` when it is a repeatable change. Change-family commands
    /// defer recording to Esc (the insert capture owns it).
    fn execute(&mut self, cmd: Command, ta: &mut TextArea<'static>) -> VimKeyOutcome {
        let outcome = self.apply(&cmd, None, ta);
        if outcome != VimKeyOutcome::NoOp && Self::repeatable(&cmd) && self.insert_capture.is_none()
        {
            self.record(cmd);
        }
        self.clear_pending();
        outcome
    }

    /// Whether `.` repeats this command. Motions, undo/redo, yanks, mode
    /// changes and `.` itself are not changes (vim semantics).
    fn repeatable(cmd: &Command) -> bool {
        match cmd {
            Command::Move(..)
            | Command::Undo(_)
            | Command::Redo(_)
            | Command::EnterVisual { .. }
            | Command::Repeat => false,
            Command::OperateMotion(op, ..)
            | Command::OperateLine(op, _)
            | Command::OperateObject(op, _)
            | Command::OperateToLineEnd(op) => *op != Operator::Yank,
            // Exhaustive on purpose — a new Command variant must decide its
            // dot-repeat policy here, not inherit a silent default.
            Command::IndentLines { .. }
            | Command::DeleteChar { .. }
            | Command::ReplaceChar(_)
            | Command::SubstituteChar(_)
            | Command::SubstituteLine
            | Command::JoinLines { .. }
            | Command::ToggleCase(_)
            | Command::Paste { .. }
            | Command::EnterInsert(_)
            | Command::EnterReplace => true,
        }
    }

    /// Whether Esc with NOTHING typed still records the command for `.`.
    /// Plain insert entries (i/a/I/A, R) don't — an aborted insert is not a
    /// change in vim. o/O do (the opened line IS the change), and the
    /// Change family does (the cut already happened before Insert began).
    /// Exhaustive on purpose, like `repeatable` — a new command must decide.
    fn records_when_empty(cmd: &Command) -> bool {
        match cmd {
            Command::EnterInsert(
                InsertEntry::Here
                | InsertEntry::After
                | InsertEntry::LineStart
                | InsertEntry::LineEnd,
            )
            | Command::EnterReplace => false,
            Command::EnterInsert(InsertEntry::OpenBelow | InsertEntry::OpenAbove)
            | Command::Move(..)
            | Command::OperateMotion(..)
            | Command::OperateLine(..)
            | Command::OperateObject(..)
            | Command::OperateToLineEnd(_)
            | Command::IndentLines { .. }
            | Command::DeleteChar { .. }
            | Command::ReplaceChar(_)
            | Command::SubstituteChar(_)
            | Command::SubstituteLine
            | Command::JoinLines { .. }
            | Command::ToggleCase(_)
            | Command::Paste { .. }
            | Command::Undo(_)
            | Command::Redo(_)
            | Command::EnterVisual { .. }
            | Command::Repeat => true,
        }
    }

    /// The only door that mutates the buffer for Normal-mode commands.
    /// `inserted` is the captured Insert-mode delta when replaying a
    /// Change-family command (dot-repeat); `None` on a first press, which
    /// enters Insert mode and starts capturing instead.
    fn apply(
        &mut self,
        cmd: &Command,
        inserted: Option<&str>,
        ta: &mut TextArea<'static>,
    ) -> VimKeyOutcome {
        match *cmd {
            Command::Move(m, n) => {
                self.apply_motion(m, n, ta);
                VimKeyOutcome::CursorOnly
            }
            Command::OperateMotion(op, m, n) => {
                if self.apply_operator_motion(op, m, n, inserted, ta) {
                    Self::outcome_for(op)
                } else {
                    VimKeyOutcome::NoOp
                }
            }
            Command::OperateLine(op, n) => {
                self.apply_operator_linewise(op, n, inserted, ta);
                Self::outcome_for(op)
            }
            Command::OperateObject(op, obj) => {
                if self.apply_operator_object(op, obj, inserted, ta) {
                    Self::outcome_for(op)
                } else {
                    VimKeyOutcome::NoOp
                }
            }
            Command::OperateToLineEnd(op) => {
                self.apply_operator_to_line_end(op, inserted, ta);
                Self::outcome_for(op)
            }
            Command::IndentLines { outdent, count } => {
                self.indent_lines(outdent, count, ta);
                VimKeyOutcome::TextMutated
            }
            Command::DeleteChar { forward, count } => {
                if self.delete_chars(forward, count, ta) {
                    VimKeyOutcome::TextMutated
                } else {
                    VimKeyOutcome::NoOp
                }
            }
            Command::ReplaceChar(c) => self.replace_char(c, ta),
            Command::SubstituteChar(n) => {
                // vim `s` enters Insert even on an empty line; the delete's
                // success only matters for the outcome's mutation signal.
                let deleted = self.delete_chars(true, n, ta);
                self.finish_insert_entry(cmd, inserted, ta);
                if deleted || inserted.is_some() {
                    VimKeyOutcome::TextMutated
                } else {
                    VimKeyOutcome::CursorOnly
                }
            }
            Command::SubstituteLine => {
                // Linewise register fill (vim: S puts the whole line in the
                // unnamed register, linewise), computed before the cut.
                let (row, _) = super::cursor_tuple(ta);
                if let Some(text) = ta.lines().get(row).map(|l| format!("{l}\n")) {
                    self.registers.fill(text, RegisterKind::Linewise);
                }
                ta.move_cursor(CursorMove::Head);
                ta.start_selection();
                ta.move_cursor(CursorMove::End);
                ta.cut();
                self.finish_insert_entry(cmd, inserted, ta);
                VimKeyOutcome::TextMutated
            }
            Command::JoinLines { count, spaced } => {
                for _ in 0..count.max(1) {
                    Self::join_line(ta, spaced);
                }
                VimKeyOutcome::TextMutated
            }
            Command::ToggleCase(n) => {
                for _ in 0..n {
                    Self::toggle_case_at_cursor(ta);
                }
                VimKeyOutcome::TextMutated
            }
            Command::Paste { after, count } => {
                if self.paste(after, count, ta) {
                    VimKeyOutcome::TextMutated
                } else {
                    VimKeyOutcome::NoOp
                }
            }
            Command::Undo(n) => {
                for _ in 0..n {
                    ta.undo();
                }
                VimKeyOutcome::TextMutated
            }
            Command::Redo(n) => {
                for _ in 0..n {
                    ta.redo();
                }
                VimKeyOutcome::TextMutated
            }
            Command::EnterInsert(entry) => self.apply_enter_insert(entry, cmd, inserted, ta),
            Command::EnterReplace => match inserted {
                Some(text) => {
                    for ch in text.chars() {
                        Self::overwrite_char(ta, ch);
                    }
                    self.mode = EditorMode::Normal;
                    if super::cursor_tuple(ta).1 > 0 {
                        ta.move_cursor(CursorMove::Back);
                    }
                    VimKeyOutcome::TextMutated
                }
                None => {
                    self.enter_insert_capture(cmd.clone(), ta);
                    self.mode = EditorMode::Replace; // the capture helper sets Insert
                    self.replace_stack.clear();
                    VimKeyOutcome::CursorOnly
                }
            },
            Command::EnterVisual { line } => {
                if line {
                    ta.move_cursor(CursorMove::Head);
                    ta.start_selection();
                    ta.move_cursor(CursorMove::End);
                    self.mode = EditorMode::VisualLine;
                } else {
                    ta.start_selection();
                    self.mode = EditorMode::Visual;
                }
                VimKeyOutcome::CursorOnly
            }
            Command::Repeat => match self.last_change.clone() {
                Some(change) => self.apply(&change.command, change.inserted.as_deref(), ta),
                None => VimKeyOutcome::NoOp,
            },
        }
    }

    /// Shared tail of every command that ends in Insert mode: on a first
    /// press, enter Insert and start capturing the typed delta; on replay,
    /// insert the captured text directly and stay in Normal.
    fn finish_insert_entry(
        &mut self,
        cmd: &Command,
        inserted: Option<&str>,
        ta: &mut TextArea<'static>,
    ) {
        match inserted {
            Some(text) => {
                ta.insert_str(text);
                self.mode = EditorMode::Normal;
            }
            None => self.enter_insert_capture(cmd.clone(), ta),
        }
    }

    fn apply_enter_insert(
        &mut self,
        entry: InsertEntry,
        cmd: &Command,
        inserted: Option<&str>,
        ta: &mut TextArea<'static>,
    ) -> VimKeyOutcome {
        let opened_line = match entry {
            InsertEntry::Here => false,
            InsertEntry::After => {
                ta.move_cursor(CursorMove::Forward);
                false
            }
            InsertEntry::LineStart => {
                // vim I: insert before the FIRST NON-BLANK char, not col 0.
                Self::first_non_blank(ta);
                false
            }
            InsertEntry::LineEnd => {
                ta.move_cursor(CursorMove::End);
                false
            }
            InsertEntry::OpenBelow => {
                ta.move_cursor(CursorMove::End);
                ta.insert_newline();
                true
            }
            InsertEntry::OpenAbove => {
                ta.move_cursor(CursorMove::Head);
                ta.insert_newline();
                ta.move_cursor(CursorMove::Up);
                true
            }
        };
        match inserted {
            Some(text) => {
                ta.insert_str(text);
                self.mode = EditorMode::Normal;
                if super::cursor_tuple(ta).1 > 0 {
                    ta.move_cursor(CursorMove::Back);
                }
                VimKeyOutcome::TextMutated
            }
            None => {
                self.enter_insert_capture(cmd.clone(), ta);
                if opened_line {
                    VimKeyOutcome::TextMutated
                } else {
                    VimKeyOutcome::CursorOnly
                }
            }
        }
    }

    /// Map a Normal/Visual motion key to its Motion. Shared by normal_char and handle_visual.
    fn motion_for_char(c: char) -> Option<Motion> {
        match c {
            'h' => Some(Motion::Left),
            'l' => Some(Motion::Right),
            'k' => Some(Motion::Up),
            'j' => Some(Motion::Down),
            'w' => Some(Motion::WordForward),
            'W' => Some(Motion::WordForwardBig),
            'b' => Some(Motion::WordBack),
            'B' => Some(Motion::WordBackBig),
            'e' => Some(Motion::WordEnd),
            'E' => Some(Motion::WordEndBig),
            '0' => Some(Motion::LineStart),
            '^' => Some(Motion::FirstNonBlank),
            '$' => Some(Motion::LineEnd),
            'G' => Some(Motion::FileEnd),
            '{' => Some(Motion::ParagraphBack),
            '}' => Some(Motion::ParagraphForward),
            '%' => Some(Motion::MatchingPair),
            _ => None,
        }
    }

    /// The g-command grammar: what one key after a pending `g` means. Both
    /// the Normal parser and the Visual handler consume this single table
    /// (dispatching per mode), so a new g-command is added exactly once.
    fn g_key_for(c: char) -> Option<GKey> {
        match c {
            'g' => Some(GKey::GotoLine), // gg — file start, or line N with a count
            'e' => Some(GKey::Motion(Motion::WordEndBack { big: false })),
            'E' => Some(GKey::Motion(Motion::WordEndBack { big: true })),
            '_' => Some(GKey::Motion(Motion::LastNonBlank)),
            'u' => Some(GKey::CaseOp(Operator::Lowercase)),
            'U' => Some(GKey::CaseOp(Operator::Uppercase)),
            '~' => Some(GKey::CaseOp(Operator::ToggleCase)),
            'J' => Some(GKey::Join),
            _ => None,
        }
    }

    /// Map a find key to its `(till, forward)` spec. Shared by the Normal
    /// parser and the Visual handler.
    fn find_spec_for(c: char) -> Option<(bool, bool)> {
        match c {
            'f' => Some((false, true)),
            'F' => Some((false, false)),
            't' => Some((true, true)),
            'T' => Some((true, false)),
            _ => None,
        }
    }

    /// The motion `;` / `,` repeats: the last find, same or reversed
    /// direction. Shared by the Normal parser and the Visual handler.
    fn repeat_find_motion(&self, c: char) -> Option<Motion> {
        let (ch, till, fwd) = self.last_find?;
        let forward = if c == ';' { fwd } else { !fwd };
        Some(Motion::FindChar { ch, till, forward })
    }

    // ── count accumulation helpers ───────────────────────────────────────────

    fn take_count(&mut self) -> usize {
        self.pending_count.take().unwrap_or(1)
    }

    /// Operator-scoped count × motion-scoped count (vim: `2d3w` = 6 words).
    fn take_total_count(&mut self) -> usize {
        let op_n = self.pending_op_count.take().unwrap_or(1);
        op_n * self.pending_count.take().unwrap_or(1)
    }

    fn clear_pending(&mut self) {
        self.pending_count = None;
        self.pending_op_count = None;
        self.pending_operator = None;
        self.awaiting = None;
    }

    /// Returns true if `c` was consumed as a count digit.
    fn accumulate_count(&mut self, c: char) -> bool {
        if c.is_ascii_digit() {
            // bare '0' with no pending count is the LineStart motion, not a digit
            if c == '0' && self.pending_count.is_none() {
                return false;
            }
            let d = c as usize - '0' as usize;
            self.pending_count = Some(self.pending_count.unwrap_or(0) * 10 + d);
            return true;
        }
        false
    }

    // ── Motion resolution ────────────────────────────────────────────────────

    /// Where `motion` (× count) would land, as a position value — no net
    /// cursor mutation (the cursor is restored before returning).
    fn resolve_motion(
        &self,
        motion: Motion,
        count: usize,
        ta: &mut TextArea<'static>,
    ) -> (usize, usize) {
        let saved = super::cursor_tuple(ta);
        self.apply_motion(motion, count, ta);
        let target = super::cursor_tuple(ta);
        ta.move_cursor(CursorMove::Jump(saved.0 as u16, saved.1 as u16));
        target
    }

    /// Vim's motion classification: how a motion forms an operator range.
    /// (`:h exclusive` — every vim motion is exclusive, inclusive, or
    /// linewise when consumed by an operator.)
    fn kind_of(motion: Motion) -> SpanKind {
        match motion {
            Motion::Up
            | Motion::Down
            | Motion::FileStart
            | Motion::FileEnd
            | Motion::GotoLine(_) => SpanKind::Linewise,
            Motion::WordEnd
            | Motion::WordEndBig
            | Motion::WordEndBack { .. }
            | Motion::MatchingPair => SpanKind::Inclusive,
            // d$ / dg_ delete through the char they land on (vim: inclusive).
            Motion::LineEnd | Motion::LastNonBlank => SpanKind::Inclusive,
            // f/t are inclusive; F/T (backward) are exclusive.
            Motion::FindChar { forward: true, .. } => SpanKind::Inclusive,
            _ => SpanKind::Exclusive,
        }
    }

    /// Select `[start, end]` (inclusive) or `[start, end)` on the textarea.
    /// The single home of the vim-inclusive → ratatui-half-open `+1`
    /// conversion, clamped to the end line's length.
    fn select_range(
        ta: &mut TextArea<'static>,
        start: (usize, usize),
        end: (usize, usize),
        inclusive: bool,
    ) {
        let (er, ec) = end;
        let end_col = if inclusive {
            let len = ta.lines().get(er).map(|l| l.chars().count()).unwrap_or(ec);
            (ec + 1).min(len)
        } else {
            ec
        };
        ta.move_cursor(CursorMove::Jump(start.0 as u16, start.1 as u16));
        ta.start_selection();
        ta.move_cursor(CursorMove::Jump(er as u16, end_col as u16));
    }

    fn apply_motion(&self, motion: Motion, count: usize, ta: &mut TextArea<'static>) {
        // Count-finds are atomic in vim: `2fx` with one 'x' fails the WHOLE
        // motion (cursor stays put) — never "as far as possible". Handled
        // outside the per-count loop, which can't express that.
        if let Motion::FindChar { ch, till, forward } = motion {
            Self::find_char_count(ta, ch, till, forward, count);
            return;
        }
        for _ in 0..count.max(1) {
            match motion {
                Motion::Left => ta.move_cursor(CursorMove::Back),
                Motion::Right => ta.move_cursor(CursorMove::Forward),
                Motion::Up => ta.move_cursor(CursorMove::Up),
                Motion::Down => ta.move_cursor(CursorMove::Down),
                Motion::WordForward => ta.move_cursor(CursorMove::WordForward),
                Motion::WordBack => ta.move_cursor(CursorMove::WordBack),
                Motion::WordEnd => ta.move_cursor(CursorMove::WordEnd),
                Motion::WordForwardBig => {
                    let (r, c) = Self::word_forward_big(ta.lines(), super::cursor_tuple(ta));
                    ta.move_cursor(CursorMove::Jump(r as u16, c as u16));
                }
                Motion::WordBackBig => {
                    let (r, c) = Self::word_back_big(ta.lines(), super::cursor_tuple(ta));
                    ta.move_cursor(CursorMove::Jump(r as u16, c as u16));
                }
                Motion::WordEndBig => {
                    if let Some((r, c)) = Self::word_end_big(ta.lines(), super::cursor_tuple(ta)) {
                        ta.move_cursor(CursorMove::Jump(r as u16, c as u16));
                    }
                }
                Motion::WordEndBack { big } => {
                    if let Some((r, c)) =
                        Self::word_end_back(ta.lines(), super::cursor_tuple(ta), big)
                    {
                        ta.move_cursor(CursorMove::Jump(r as u16, c as u16));
                    }
                }
                Motion::LineStart => ta.move_cursor(CursorMove::Head),
                Motion::FirstNonBlank => Self::first_non_blank(ta),
                Motion::LastNonBlank => Self::last_non_blank(ta),
                Motion::LineEnd => ta.move_cursor(CursorMove::End),
                Motion::FileStart => ta.move_cursor(CursorMove::Top),
                Motion::FileEnd => ta.move_cursor(CursorMove::Bottom),
                Motion::GotoLine(n) => {
                    let last = ta.lines().len().saturating_sub(1);
                    let row = n.saturating_sub(1).min(last);
                    ta.move_cursor(CursorMove::Jump(row as u16, 0));
                }
                Motion::ParagraphForward => ta.move_cursor(CursorMove::ParagraphForward),
                Motion::ParagraphBack => ta.move_cursor(CursorMove::ParagraphBack),
                Motion::MatchingPair => Self::match_pair(ta),
                Motion::FindChar { .. } => unreachable!("handled atomically above"),
            }
        }
    }

    fn first_non_blank(ta: &mut TextArea<'static>) {
        let (row, _) = super::cursor_tuple(ta);
        if let Some(line) = ta.lines().get(row) {
            let n = line.chars().take_while(|c| c.is_whitespace()).count();
            ta.move_cursor(CursorMove::Jump(row as u16, n as u16));
        }
    }

    /// `g_` — last non-blank char of the line (no-op on a blank line, vim).
    fn last_non_blank(ta: &mut TextArea<'static>) {
        let (row, _) = super::cursor_tuple(ta);
        let idx = ta.lines().get(row).and_then(|line| {
            line.chars()
                .enumerate()
                .filter(|(_, c)| !c.is_whitespace())
                .map(|(i, _)| i)
                .last()
        });
        if let Some(idx) = idx {
            ta.move_cursor(CursorMove::Jump(row as u16, idx as u16));
        }
    }

    /// Char class for small-word motions: blank / word (alnum + `_`) / punct.
    fn char_class(c: char) -> u8 {
        if c.is_whitespace() {
            0
        } else if c.is_alphanumeric() || c == '_' {
            1
        } else {
            2
        }
    }

    /// `W` — the start of the next WORD (any non-blank run) after `pos`.
    /// Crosses lines; an empty line is itself a WORD stop (vim). Pure over
    /// the line slice — the caller jumps the cursor.
    fn word_forward_big(lines: &[String], pos: (usize, usize)) -> (usize, usize) {
        let (mut row, mut col) = pos;
        let last = lines.len().saturating_sub(1);
        let mut chars: Vec<char> = lines[row].chars().collect();
        // Skip the rest of the current WORD.
        while col < chars.len() && !chars[col].is_whitespace() {
            col += 1;
        }
        // Skip blanks to the next WORD start.
        loop {
            if col >= chars.len() {
                if row == last {
                    break; // EOF: rest at line end
                }
                row += 1;
                chars = lines[row].chars().collect();
                col = 0;
                if chars.is_empty() {
                    break;
                }
                continue;
            }
            if chars[col].is_whitespace() {
                col += 1;
            } else {
                break;
            }
        }
        (row, col)
    }

    /// `B` — the start of the current/previous WORD before `pos`. Pure.
    fn word_back_big(lines: &[String], pos: (usize, usize)) -> (usize, usize) {
        let (mut row, mut col) = pos;
        let mut chars: Vec<char> = lines[row].chars().collect();
        // Walk backward to the previous non-blank char, crossing lines; an
        // empty line is itself a stop (vim).
        loop {
            if col == 0 {
                if row == 0 {
                    return pos; // nothing before — motion fails in place
                }
                row -= 1;
                chars = lines[row].chars().collect();
                if chars.is_empty() {
                    return (row, 0);
                }
                col = chars.len() - 1;
            } else {
                col -= 1;
            }
            if !chars[col].is_whitespace() {
                break;
            }
        }
        // Walk to the start of this WORD.
        while col > 0 && !chars[col - 1].is_whitespace() {
            col -= 1;
        }
        (row, col)
    }

    /// `E` — the end of the next WORD after `pos`; `None` when no WORD
    /// follows (vim fails the motion). Pure.
    fn word_end_big(lines: &[String], pos: (usize, usize)) -> Option<(usize, usize)> {
        let (mut row, mut col) = pos;
        let last = lines.len().saturating_sub(1);
        let mut chars: Vec<char> = lines[row].chars().collect();
        // Step one position forward, then find the next non-blank.
        col += 1;
        loop {
            if col >= chars.len() {
                if row == last {
                    return None; // nothing ahead — cursor stays
                }
                row += 1;
                chars = lines[row].chars().collect();
                col = 0;
                continue;
            }
            if chars[col].is_whitespace() {
                col += 1;
            } else {
                break;
            }
        }
        // Advance to the last char of this WORD.
        while col + 1 < chars.len() && !chars[col + 1].is_whitespace() {
            col += 1;
        }
        Some((row, col))
    }

    /// `ge` / `gE` — the nearest previous word end before `pos`: a non-blank
    /// char whose successor is blank/EOL (or, for small words, a different
    /// char class). `None` when none exists. Pure.
    fn word_end_back(lines: &[String], pos: (usize, usize), big: bool) -> Option<(usize, usize)> {
        let (mut row, mut col) = pos;
        let mut chars: Vec<char> = lines[row].chars().collect();
        // The textarea cursor can sit one past the last char ($ / line end);
        // vim's cursor is ON the last char — clamp so "before the cursor"
        // doesn't match the char under the cursor itself.
        if !chars.is_empty() && col >= chars.len() {
            col = chars.len() - 1;
        }
        loop {
            // Step one position back, crossing lines (EOL is a position).
            if col == 0 {
                if row == 0 {
                    return None;
                }
                row -= 1;
                chars = lines[row].chars().collect();
                col = chars.len();
                continue;
            }
            col -= 1;
            let ch = chars[col];
            if ch.is_whitespace() {
                continue;
            }
            let is_end = match chars.get(col + 1) {
                None => true, // EOL after it
                Some(&n) => {
                    n.is_whitespace() || (!big && Self::char_class(n) != Self::char_class(ch))
                }
            };
            if is_end {
                return Some((row, col));
            }
        }
    }

    /// Jump to the bracket that matches the one under the cursor, scanning
    /// across lines. Opening bracket → forward with depth counting to the
    /// matching close; closing bracket → backward to the matching open.
    /// No-op when the cursor is not on a bracket or no match exists.
    fn match_pair(ta: &mut TextArea<'static>) {
        let (row, col) = super::cursor_tuple(ta);
        let lines = ta.lines();
        let here = match lines.get(row).and_then(|l| l.chars().nth(col)) {
            Some(c) => c,
            None => return,
        };
        let pairs = [('(', ')'), ('[', ']'), ('{', '}'), ('<', '>')];
        let target = if let Some(&(_, close)) = pairs.iter().find(|&&(o, _)| o == here) {
            // open → scan forward through the buffer
            let mut depth = 0i32;
            let mut found = None;
            'fwd: for (r, line) in lines.iter().enumerate().skip(row) {
                let start = if r == row { col } else { 0 };
                for (i, ch) in line.chars().enumerate().skip(start) {
                    if ch == here {
                        depth += 1;
                    } else if ch == close {
                        depth -= 1;
                        if depth == 0 {
                            found = Some((r, i));
                            break 'fwd;
                        }
                    }
                }
            }
            found
        } else if let Some(&(open, _)) = pairs.iter().find(|&&(_, c)| c == here) {
            // close → scan backward through the buffer
            let mut depth = 0i32;
            let mut found = None;
            'back: for r in (0..=row).rev() {
                let chars: Vec<char> = lines[r].chars().collect();
                let last = if r == row {
                    col
                } else {
                    chars.len().saturating_sub(1)
                };
                if chars.is_empty() {
                    continue;
                }
                for i in (0..=last.min(chars.len() - 1)).rev() {
                    if chars[i] == here {
                        depth += 1;
                    } else if chars[i] == open {
                        depth -= 1;
                        if depth == 0 {
                            found = Some((r, i));
                            break 'back;
                        }
                    }
                }
            }
            found
        } else {
            None
        };
        if let Some((r, c)) = target {
            ta.move_cursor(CursorMove::Jump(r as u16, c as u16));
        }
    }

    /// Move to the `count`-th occurrence of `ch` on the current line —
    /// atomically: fewer than `count` occurrences fails the whole motion and
    /// the cursor does not move (vim). `forward`: search right from col+1;
    /// otherwise left from col-1. `till`: stop one column short (t/T).
    fn find_char_count(
        ta: &mut TextArea<'static>,
        ch: char,
        till: bool,
        forward: bool,
        count: usize,
    ) {
        let (row, col) = super::cursor_tuple(ta);
        let Some(line) = ta.lines().get(row).cloned() else {
            return;
        };
        let chars: Vec<char> = line.chars().collect();
        let n = count.max(1);
        let pos = if forward {
            ((col + 1)..chars.len())
                .filter(|&i| chars[i] == ch)
                .nth(n - 1)
        } else {
            (0..col).rev().filter(|&i| chars[i] == ch).nth(n - 1)
        };
        let Some(pos) = pos else { return };
        let target = if till {
            if forward {
                pos.saturating_sub(1)
            } else {
                pos + 1
            }
        } else {
            pos
        };
        ta.move_cursor(CursorMove::Jump(row as u16, target as u16));
    }

    // ── Operator framework ───────────────────────────────────────────────────

    fn outcome_for(op: Operator) -> VimKeyOutcome {
        match op {
            Operator::Yank => VimKeyOutcome::CursorOnly, // yank doesn't change text
            _ => VimKeyOutcome::TextMutated,
        }
    }

    /// Operate over the range from the cursor through `motion` (× count).
    /// The range's shape is the motion's `SpanKind`: linewise motions (j/k,
    /// gg/G) operate on whole lines, inclusive motions (e, f/t, %, $) take
    /// the char they land on, exclusive motions stop short of it.
    /// Returns `false` when the motion failed and the whole operation was a
    /// vim no-op (nothing deleted, no Insert entry, register untouched).
    fn apply_operator_motion(
        &mut self,
        op: Operator,
        m: Motion,
        count: usize,
        inserted: Option<&str>,
        ta: &mut TextArea<'static>,
    ) -> bool {
        // Vim `cw`/`cW` semantics: change + word-forward uses word-end (not
        // word-start of the next word), so the trailing space is preserved.
        // This is vim's well-known `cw = ce` behaviour. Other operators (dw, yw)
        // use the motion as-is (including the trailing space).
        let effective_motion = if op == Operator::Change {
            match m {
                Motion::WordForward => Motion::WordEnd,
                Motion::WordForwardBig => Motion::WordEndBig, // cW = cE
                other => other,
            }
        } else {
            m
        };
        let origin = super::cursor_tuple(ta);
        let target = self.resolve_motion(effective_motion, count, ta);
        match Self::kind_of(effective_motion) {
            SpanKind::Linewise => {
                // j/k must actually traverse `count` rows; at a buffer edge
                // the motion fails and vim no-ops the whole operation (dj on
                // the last line deletes nothing). gg/G always resolve —
                // operating on the current line is valid for them.
                if matches!(effective_motion, Motion::Up | Motion::Down)
                    && origin.0.abs_diff(target.0) < count
                {
                    return false;
                }
                let top = origin.0.min(target.0);
                let lines = origin.0.abs_diff(target.0) + 1;
                ta.move_cursor(CursorMove::Jump(top as u16, 0));
                self.apply_operator_linewise(op, lines, inserted, ta);
                true
            }
            kind => {
                if target == origin
                    && (kind == SpanKind::Exclusive
                        || matches!(
                            effective_motion,
                            // Inclusive motions that signal failure by not
                            // moving: failed find/pair-match, ge at buffer
                            // start, E at buffer end.
                            Motion::FindChar { .. }
                                | Motion::MatchingPair
                                | Motion::WordEndBack { .. }
                                | Motion::WordEndBig
                        ))
                {
                    // Failed motion or zero-width exclusive range: vim no-op
                    // — nothing deleted, no Insert, register kept.
                    return false;
                }
                let (start, end) = if target < origin {
                    (target, origin)
                } else {
                    (origin, target)
                };
                Self::select_range(ta, start, end, kind == SpanKind::Inclusive);
                // For Change, capture under the actual command (original
                // motion, not the cw=ce substitute) so `.` replays it right.
                if op == Operator::Change {
                    ta.cut();
                    self.fill_from_textarea(ta, RegisterKind::Charwise);
                    self.finish_insert_entry(&Command::OperateMotion(op, m, count), inserted, ta);
                } else {
                    self.apply_operator_on_selection(op, ta);
                }
                true
            }
        }
    }

    fn apply_operator_linewise(
        &mut self,
        op: Operator,
        count: usize,
        inserted: Option<&str>,
        ta: &mut TextArea<'static>,
    ) {
        let (r0, _) = super::cursor_tuple(ta);
        let last = ta.lines().len().saturating_sub(1);
        let r1 = (r0 + count.saturating_sub(1)).min(last);

        // Register content: the line bodies plus a trailing newline (linewise).
        let body: String = ta.lines()[r0..=r1].join("\n");
        let register_text = format!("{body}\n");

        match op {
            Operator::Yank => {
                self.registers.fill(register_text, RegisterKind::Linewise);
                // cursor stays at start of first yanked line
                ta.move_cursor(CursorMove::Jump(r0 as u16, 0));
            }
            Operator::Delete | Operator::Change => {
                // Select the lines. Include the trailing newline if there is a
                // line after r1; otherwise (last line) include the PRECEDING
                // newline so no empty remnant is left.
                if r1 < last {
                    ta.move_cursor(CursorMove::Jump(r0 as u16, 0));
                    ta.start_selection();
                    ta.move_cursor(CursorMove::Jump((r1 + 1) as u16, 0));
                } else if r0 > 0 {
                    let prev_end = ta.lines()[r0 - 1].chars().count();
                    ta.move_cursor(CursorMove::Jump((r0 - 1) as u16, prev_end as u16));
                    ta.start_selection();
                    let end = ta.lines()[r1].chars().count();
                    ta.move_cursor(CursorMove::Jump(r1 as u16, end as u16));
                } else {
                    // whole buffer: select everything, leaving one empty line
                    ta.move_cursor(CursorMove::Jump(0, 0));
                    ta.start_selection();
                    let end = ta.lines()[r1].chars().count();
                    ta.move_cursor(CursorMove::Jump(r1 as u16, end as u16));
                }
                ta.cut();
                // The cut selection may include a leading newline on the
                // last-line path; fill the register with the proper linewise
                // content computed above instead.
                self.registers.fill(register_text, RegisterKind::Linewise);
                if op == Operator::Change {
                    // cc: open a fresh empty line to type into, at the right spot
                    if r0 == 0 && r1 == last {
                        // whole-buffer case: cut() left [""], the cursor is already
                        // at (0,0) on an empty line — no extra newline needed.
                        ta.move_cursor(CursorMove::Jump(0, 0));
                    } else if r0 > 0 && r1 == last {
                        // we consumed the preceding newline; add a line back
                        ta.move_cursor(CursorMove::End);
                        ta.insert_newline();
                    } else {
                        ta.insert_newline();
                        ta.move_cursor(CursorMove::Up);
                    }
                    self.finish_insert_entry(&Command::OperateLine(op, count), inserted, ta);
                }
            }
            Operator::Indent | Operator::Outdent => {
                // Linewise indent/outdent triggered by e.g. ">>" reaching
                // apply_operator_linewise is handled via normal_char's direct
                // indent_lines path. This arm is a safety net; it should not
                // normally be reached (>> goes through the doubled-operator path).
                let outdent = op == Operator::Outdent;
                self.indent_lines(outdent, count, ta);
            }
            Operator::Lowercase | Operator::Uppercase | Operator::ToggleCase => {
                // guu / gUU / g~~ / guj…: transform whole lines in ONE
                // cut+insert so undo reverts the command in one step, not
                // per line. Case operators never touch the register (vim).
                let transformed = ta.lines()[r0..=r1]
                    .iter()
                    .map(|l| Self::transform_case(l, op))
                    .collect::<Vec<_>>()
                    .join("\n");
                let end_len = ta.lines()[r1].chars().count();
                ta.move_cursor(CursorMove::Jump(r0 as u16, 0));
                ta.start_selection();
                ta.move_cursor(CursorMove::Jump(r1 as u16, end_len as u16));
                ta.cut();
                ta.insert_str(&transformed);
                ta.move_cursor(CursorMove::Jump(r0 as u16, 0));
            }
        }
    }

    fn apply_operator_to_line_end(
        &mut self,
        op: Operator,
        inserted: Option<&str>,
        ta: &mut TextArea<'static>,
    ) {
        ta.start_selection();
        ta.move_cursor(CursorMove::End);
        if op == Operator::Change {
            ta.cut();
            self.fill_from_textarea(ta, RegisterKind::Charwise);
            self.finish_insert_entry(&Command::OperateToLineEnd(op), inserted, ta);
        } else {
            self.apply_operator_on_selection(op, ta);
        }
    }

    /// Indent (add 4 spaces) or outdent (remove up to 4 leading spaces) the
    /// cursor's line, then repeat for `count` lines total (moving down after
    /// each). Used by `>>`, `<<`, and the visual `>`/`<` operators.
    fn indent_lines(&self, outdent: bool, count: usize, ta: &mut TextArea<'static>) {
        let (start_row, start_col) = super::cursor_tuple(ta);
        let mut first_line_delta = 0usize; // indent change on the cursor's own line
        for i in 0..count.max(1) {
            ta.move_cursor(CursorMove::Head);
            if outdent {
                // Remove up to 4 leading spaces.
                let (row, _) = super::cursor_tuple(ta);
                let n = ta
                    .lines()
                    .get(row)
                    .map(|l| l.chars().take(4).take_while(|c| *c == ' ').count())
                    .unwrap_or(0);
                if i == 0 {
                    first_line_delta = n;
                }
                for _ in 0..n {
                    ta.delete_next_char();
                }
            } else {
                if i == 0 {
                    first_line_delta = 4;
                }
                ta.insert_str("    ");
            }
            ta.move_cursor(CursorMove::Down);
        }
        // Keep the cursor over the same character it sat on, shifted by the
        // indent change — matches neovim's >> behavior.
        let col = if outdent {
            start_col.saturating_sub(first_line_delta)
        } else {
            start_col + first_line_delta
        };
        ta.move_cursor(CursorMove::Jump(start_row as u16, col as u16));
    }

    /// Capture the text the textarea just cut/copied (its yank buffer) into
    /// the engine's unnamed register. The textarea yank buffer is only a
    /// transport here — the engine never reads it back at paste time.
    fn fill_from_textarea(&mut self, ta: &TextArea<'static>, kind: RegisterKind) {
        self.registers.fill(ta.yank_text(), kind);
    }

    /// Charwise operator over the live selection. Change never reaches here —
    /// every Change path captures its own command before cutting (so `.`
    /// replays the right thing); linewise flows use apply_operator_linewise.
    fn apply_operator_on_selection(&mut self, op: Operator, ta: &mut TextArea<'static>) {
        match op {
            Operator::Yank => {
                let start = ta.selection_range().map(|(s, _)| s);
                ta.copy();
                self.fill_from_textarea(ta, RegisterKind::Charwise);
                ta.cancel_selection();
                if let Some((r, c)) = start {
                    ta.move_cursor(CursorMove::Jump(r as u16, c as u16));
                }
            }
            Operator::Delete | Operator::Change => {
                ta.cut();
                self.fill_from_textarea(ta, RegisterKind::Charwise);
            }
            Operator::Indent | Operator::Outdent => {
                // Compute the selected row range, cancel the selection, then
                // indent/outdent those rows. This covers operator+motion (e.g.
                // `>j`) and visual `>`/`<` (which call this via handle_visual).
                let outdent = op == Operator::Outdent;
                let (rows, start_row) = if let Some(((sr, _), (er, _))) = ta.selection_range() {
                    (er.saturating_sub(sr) + 1, sr)
                } else {
                    let (r, _) = super::cursor_tuple(ta);
                    (1, r)
                };
                ta.cancel_selection();
                ta.move_cursor(CursorMove::Jump(start_row as u16, 0));
                self.indent_lines(outdent, rows, ta);
            }
            Operator::Lowercase | Operator::Uppercase | Operator::ToggleCase => {
                // Replace the selection with its case-transformed text and
                // leave the cursor at the start (vim). The cut only passes
                // through the textarea yank buffer — the engine register is
                // deliberately NOT filled (vim: case operators don't yank).
                let start = ta.selection_range().map(|(s, _)| s);
                ta.cut();
                let transformed = Self::transform_case(&ta.yank_text(), op);
                ta.insert_str(&transformed);
                if let Some((r, c)) = start {
                    ta.move_cursor(CursorMove::Jump(r as u16, c as u16));
                }
            }
        }
    }

    /// Flip one char's case. The single home of toggle-case semantics,
    /// shared by bare `~`, visual/operator `g~`, and `transform_case`.
    fn flip_case(ch: char) -> String {
        if ch.is_uppercase() {
            ch.to_lowercase().collect()
        } else {
            ch.to_uppercase().collect()
        }
    }

    fn transform_case(text: &str, op: Operator) -> String {
        match op {
            Operator::Lowercase => text.to_lowercase(),
            Operator::Uppercase => text.to_uppercase(),
            _ => text.chars().map(Self::flip_case).collect(),
        }
    }

    /// Slice the buffer text between two cursor positions (row, col), inclusive
    /// of `start` and exclusive of `end`. Works across lines: the result for a
    /// two-line insert is `"line1_suffix\nline2_prefix"`. Returns `""` when
    /// `end <= start`.
    fn text_between(lines: &[String], start: (usize, usize), end: (usize, usize)) -> String {
        if end <= start {
            return String::new();
        }
        let (sr, sc) = start;
        let (er, ec) = end;
        if sr == er {
            return lines
                .get(sr)
                .map(|l| l.chars().skip(sc).take(ec.saturating_sub(sc)).collect())
                .unwrap_or_default();
        }
        let mut out = String::new();
        if let Some(l) = lines.get(sr) {
            out.extend(l.chars().skip(sc));
        }
        out.push('\n');
        for r in (sr + 1)..er {
            if let Some(l) = lines.get(r) {
                out.push_str(l);
            }
            out.push('\n');
        }
        if let Some(l) = lines.get(er) {
            out.extend(l.chars().take(ec));
        }
        out
    }

    fn enter_insert_capture(&mut self, command: Command, ta: &TextArea<'static>) {
        self.mode = EditorMode::Insert;
        self.insert_capture = Some(InsertCapture {
            command,
            start: super::cursor_tuple(ta),
        });
    }

    // ── Dot-repeat recording ─────────────────────────────────────────────────

    /// Record a completed mutating command in `last_change` (no inserted text).
    /// Called at every mutating, non-insert completion point.
    fn record(&mut self, command: Command) {
        self.last_change = Some(Change {
            command,
            inserted: None,
        });
    }

    // ── Paste p/P ────────────────────────────────────────────────────────────

    /// Returns `false` when the register is empty (nothing pasted).
    fn paste(&mut self, after: bool, count: usize, ta: &mut TextArea<'static>) -> bool {
        // Borrow, don't clone — the body only mutates `ta`, never `self`,
        // so a large register isn't copied on every p/P.
        let Some(reg) = self.registers.read() else {
            return false;
        };
        let text = &reg.text;
        match reg.kind {
            RegisterKind::Linewise => {
                let body = text.strip_suffix('\n').unwrap_or(text);
                let n = count.max(1);
                if after {
                    ta.move_cursor(CursorMove::End);
                    for _ in 0..n {
                        ta.insert_newline();
                        ta.insert_str(body);
                    }
                } else {
                    ta.move_cursor(CursorMove::Head);
                    for _ in 0..n {
                        ta.insert_str(body);
                        ta.insert_newline();
                    }
                }
            }
            RegisterKind::Charwise => {
                if after {
                    let (row, col) = super::cursor_tuple(ta);
                    let len = ta
                        .lines()
                        .get(row)
                        .map(|l| l.chars().count())
                        .unwrap_or(col);
                    ta.move_cursor(CursorMove::Jump(row as u16, (col + 1).min(len) as u16));
                }
                for _ in 0..count.max(1) {
                    ta.insert_str(text);
                }
            }
        }
        true
    }

    // ── Text object helpers ──────────────────────────────────────────────────

    /// Map an object char (e.g. `w`, `(`, `"`) to a `TextObject`.
    fn object_for_char(c: char, around: bool) -> Option<TextObject> {
        match c {
            'w' => Some(TextObject::Word { around }),
            '(' | ')' | 'b' => Some(TextObject::Pair {
                open: '(',
                close: ')',
                around,
            }),
            '{' | '}' | 'B' => Some(TextObject::Pair {
                open: '{',
                close: '}',
                around,
            }),
            '[' | ']' => Some(TextObject::Pair {
                open: '[',
                close: ']',
                around,
            }),
            '<' | '>' => Some(TextObject::Pair {
                open: '<',
                close: '>',
                around,
            }),
            '"' => Some(TextObject::Quote { ch: '"', around }),
            '\'' => Some(TextObject::Quote { ch: '\'', around }),
            '`' => Some(TextObject::Quote { ch: '`', around }),
            _ => None,
        }
    }

    /// Apply `op` over the text object `obj` at the current cursor position.
    /// Resolve `obj` at the cursor to `(row, start, end)` — half-open cols on
    /// the cursor's row (text objects are single-line for now). Shared by the
    /// operator path (`diw`) and the visual path (`vi(`).
    fn object_range_at_cursor(
        ta: &TextArea<'static>,
        obj: TextObject,
    ) -> Option<(usize, usize, usize)> {
        let (row, col) = super::cursor_tuple(ta);
        let line = ta.lines().get(row)?;
        let chars: Vec<char> = line.chars().collect();
        let (start, end) = Self::object_range(&chars, col, obj)?;
        Some((row, start, end))
    }

    /// Returns `false` when no object exists at the cursor (vim no-op).
    fn apply_operator_object(
        &mut self,
        op: Operator,
        obj: TextObject,
        inserted: Option<&str>,
        ta: &mut TextArea<'static>,
    ) -> bool {
        let Some((row, start, end)) = Self::object_range_at_cursor(ta, obj) else {
            return false;
        };
        Self::select_range(ta, (row, start), (row, end), false);
        if op == Operator::Change {
            ta.cut();
            self.fill_from_textarea(ta, RegisterKind::Charwise);
            self.finish_insert_entry(&Command::OperateObject(op, obj), inserted, ta);
        } else {
            self.apply_operator_on_selection(op, ta);
        }
        true
    }

    /// Find the innermost enclosing pair `(open, close)` around `col`.
    /// If the cursor is on an open bracket, that bracket is the enclosing open.
    /// Otherwise scans left with depth counting (closing chars raise depth) to
    /// find the nearest unmatched open, then scans right from that open with
    /// depth counting to find the matching close.
    fn find_enclosing_pair(
        chars: &[char],
        col: usize,
        open: char,
        close: char,
    ) -> Option<(usize, usize)> {
        // Locate the open bracket that encloses col.
        let open_idx = if chars.get(col) == Some(&open) {
            col
        } else {
            let mut depth = 0usize;
            let mut found = None;
            for i in (0..col).rev() {
                if chars[i] == close {
                    depth += 1;
                } else if chars[i] == open {
                    if depth == 0 {
                        found = Some(i);
                        break;
                    }
                    depth -= 1;
                }
            }
            found?
        };
        // Find the matching close bracket scanning right from open_idx+1.
        let mut depth = 0usize;
        let mut close_idx = None;
        for (i, &ch) in chars.iter().enumerate().skip(open_idx + 1) {
            if ch == open {
                depth += 1;
            } else if ch == close {
                if depth == 0 {
                    close_idx = Some(i);
                    break;
                }
                depth -= 1;
            }
        }
        Some((open_idx, close_idx?))
    }

    /// Returns the half-open `[start, end)` char range for `obj` centred at
    /// `col` within `chars`.
    ///
    /// NOTE: text objects are **single-line** in this implementation.
    /// Multi-line pair/quote spans are a later enhancement.
    fn object_range(chars: &[char], col: usize, obj: TextObject) -> Option<(usize, usize)> {
        if chars.is_empty() || col >= chars.len() {
            return None;
        }
        match obj {
            TextObject::Word { around } => {
                let is_word = |c: char| c.is_alphanumeric() || c == '_';
                // Expand left to the start of the word.
                let mut s = col;
                while s > 0 && is_word(chars[s - 1]) {
                    s -= 1;
                }
                // Expand right past the end of the word.
                let mut e = col;
                while e < chars.len() && is_word(chars[e]) {
                    e += 1;
                }
                if around {
                    // Also consume trailing whitespace (vim `aw` behaviour).
                    while e < chars.len() && chars[e].is_whitespace() {
                        e += 1;
                    }
                }
                Some((s, e))
            }
            TextObject::Quote { ch, around } => {
                // Collect all positions of the quote character on this line.
                let positions: Vec<usize> = chars
                    .iter()
                    .enumerate()
                    .filter(|&(_, &c)| c == ch)
                    .map(|(i, _)| i)
                    .collect();
                // Find the pair that strictly contains the cursor (p[0] <= col <= p[1]).
                // Cursor in the gap between two quoted spans returns None (no-op).
                let pair = positions
                    .chunks(2)
                    .find(|p| p.len() == 2 && p[0] <= col && col <= p[1])?;
                let (o, c) = (pair[0], pair[1]);
                if around {
                    Some((o, c + 1))
                } else {
                    Some((o + 1, c))
                }
            }
            TextObject::Pair {
                open,
                close,
                around,
            } => {
                let (o, c) = Self::find_enclosing_pair(chars, col, open, close)?;
                if around {
                    Some((o, c + 1))
                } else {
                    Some((o + 1, c))
                }
            }
        }
    }

    // ── Single-key edit helpers ──────────────────────────────────────────────

    /// Delete `count` chars at the cursor (`forward`: under-and-after, vim
    /// `x`; otherwise before, vim `X`), clamped to the current line — vim's
    /// x/X never join lines — filling the unnamed register with the deleted
    /// text (vim rule: every delete fills the register; `xp` swaps chars).
    /// Returns `false` when nothing was deleted (empty line, X at col 0).
    fn delete_chars(&mut self, forward: bool, count: usize, ta: &mut TextArea<'static>) -> bool {
        let (row, col) = super::cursor_tuple(ta);
        // Borrow, don't clone: all reads of `line` finish before the first
        // mutation, so held-down x on a long line doesn't copy it each press.
        let Some(line) = ta.lines().get(row) else {
            return false;
        };
        let line_len = line.chars().count();
        let (n, start) = if forward {
            (count.min(line_len.saturating_sub(col)), col)
        } else {
            let n = count.min(col);
            (n, col - n)
        };
        let deleted: String = line.chars().skip(start).take(n).collect();
        self.registers.fill(deleted, RegisterKind::Charwise);
        for _ in 0..n {
            if forward {
                ta.delete_next_char();
            } else {
                ta.delete_char();
            }
        }
        n > 0
    }

    /// Replace the char under the cursor with `c`, stay in Normal mode.
    fn replace_char(&mut self, c: char, ta: &mut TextArea<'static>) -> VimKeyOutcome {
        if ta.delete_next_char() {
            ta.insert_char(c);
            ta.move_cursor(CursorMove::Back);
            VimKeyOutcome::TextMutated
        } else {
            VimKeyOutcome::NoOp
        }
    }

    /// Join the next line onto the current one. `spaced` (vim `J`): the next
    /// line's leading whitespace is stripped and a single space separates the
    /// parts (none when the current line is empty or already ends in
    /// whitespace), cursor left on the join point. Raw (`gJ`): the newline is
    /// removed verbatim.
    fn join_line(ta: &mut TextArea<'static>, spaced: bool) {
        let (row, _) = super::cursor_tuple(ta);
        let lines = ta.lines();
        if row + 1 >= lines.len() {
            return;
        }
        let cur_empty = lines[row].is_empty();
        let cur_ends_ws = lines[row].chars().last().is_some_and(|c| c.is_whitespace());
        ta.move_cursor(CursorMove::End);
        ta.delete_next_char(); // removes the newline
        if !spaced {
            return;
        }
        let (r, c) = super::cursor_tuple(ta);
        let strip = ta.lines()[r]
            .chars()
            .skip(c)
            .take_while(|ch| ch.is_whitespace())
            .count();
        for _ in 0..strip {
            ta.delete_next_char();
        }
        let rest_nonempty = ta.lines()[r].chars().count() > c;
        if !cur_empty && !cur_ends_ws && rest_nonempty {
            ta.insert_char(' ');
            ta.move_cursor(CursorMove::Back);
        }
    }

    /// Toggle the case of the char under the cursor and advance one char.
    fn toggle_case_at_cursor(ta: &mut TextArea<'static>) {
        let (row, col) = super::cursor_tuple(ta);
        let flipped = ta
            .lines()
            .get(row)
            .and_then(|line| line.chars().nth(col))
            .map(Self::flip_case);
        if let Some(flipped) = flipped {
            ta.delete_next_char();
            ta.insert_str(&flipped);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
    use ratatui_textarea::TextArea;

    fn key(c: char) -> KeyEvent {
        KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)
    }
    fn esc() -> KeyEvent {
        KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)
    }
    fn ta() -> TextArea<'static> {
        TextArea::from(["hello world", "second line"])
    }

    // ── Mode-entry + basic motion tests ──────────────────────────────────────

    #[test]
    fn i_enters_insert_mode() {
        let mut e = VimEngine::default();
        let mut t = ta();
        let out = e.handle_key(&key('i'), &mut t);
        assert_eq!(*e.mode(), EditorMode::Insert);
        assert_eq!(out, VimKeyOutcome::CursorOnly);
    }

    #[test]
    fn esc_returns_to_normal_and_steps_back() {
        let mut e = VimEngine::default();
        let mut t = ta();
        e.handle_key(&key('i'), &mut t);
        t.move_cursor(ratatui_textarea::CursorMove::Forward);
        t.move_cursor(ratatui_textarea::CursorMove::Forward);
        let col_before = super::super::cursor_tuple(&t).1;
        let out = e.handle_key(&esc(), &mut t);
        assert_eq!(*e.mode(), EditorMode::Normal);
        assert_eq!(out, VimKeyOutcome::CursorOnly);
        assert_eq!(super::super::cursor_tuple(&t).1, col_before - 1);
    }

    #[test]
    fn insert_mode_passes_through() {
        let mut e = VimEngine::default();
        let mut t = ta();
        e.handle_key(&key('i'), &mut t);
        let out = e.handle_key(&key('x'), &mut t);
        assert_eq!(out, VimKeyOutcome::PassThrough);
    }

    #[test]
    fn l_moves_right_cursor_only() {
        let mut e = VimEngine::default();
        let mut t = ta();
        let out = e.handle_key(&key('l'), &mut t);
        assert_eq!(out, VimKeyOutcome::CursorOnly);
        assert_eq!(super::super::cursor_tuple(&t), (0, 1));
        assert_eq!(*e.mode(), EditorMode::Normal);
    }

    #[test]
    fn a_enters_insert_after_cursor() {
        let mut e = VimEngine::default();
        let mut t = ta();
        e.handle_key(&key('a'), &mut t);
        assert_eq!(*e.mode(), EditorMode::Insert);
        assert_eq!(super::super::cursor_tuple(&t), (0, 1));
    }

    #[test]
    fn o_opens_line_below_in_insert() {
        let mut e = VimEngine::default();
        let mut t = ta();
        let out = e.handle_key(&key('o'), &mut t);
        assert_eq!(*e.mode(), EditorMode::Insert);
        assert_eq!(out, VimKeyOutcome::TextMutated);
        assert_eq!(t.lines().len(), 3);
        assert_eq!(super::super::cursor_tuple(&t).0, 1);
    }

    #[test]
    fn reset_returns_to_normal_from_insert() {
        let mut e = VimEngine::default();
        let mut t = ta();
        e.handle_key(&key('i'), &mut t);
        assert_eq!(*e.mode(), EditorMode::Insert);
        e.reset_to_normal();
        assert_eq!(*e.mode(), EditorMode::Normal);
    }

    #[test]
    fn unknown_normal_key_is_noop() {
        let mut e = VimEngine::default();
        let mut t = ta();
        let out = e.handle_key(&key('z'), &mut t);
        assert_eq!(out, VimKeyOutcome::NoOp);
        assert_eq!(*e.mode(), EditorMode::Normal);
    }

    // ── Count accumulation tests ─────────────────────────────────────────────

    #[test]
    fn count_accumulates_then_moves() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abcdef"]);
        e.handle_key(&key('3'), &mut t);
        e.handle_key(&key('l'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 3));
        // pending cleared after the motion
        e.handle_key(&key('l'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 4));
    }

    #[test]
    fn zero_without_count_is_line_start() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abcdef"]);
        e.handle_key(&key('l'), &mut t);
        e.handle_key(&key('l'), &mut t);
        e.handle_key(&key('0'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 0));
    }

    // ── gg/G motion tests ────────────────────────────────────────────────────

    #[test]
    #[allow(non_snake_case)]
    fn gg_and_G_jump_file_ends() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two", "three"]);
        e.handle_key(&key('G'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t).0, 2);
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('g'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t).0, 0);
    }

    #[test]
    fn pending_g_cancels_on_unmapped_key() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two", "three"]);
        e.handle_key(&key('G'), &mut t); // go to last line
        assert_eq!(super::super::cursor_tuple(&t).0, 2);
        e.handle_key(&key('g'), &mut t); // start gg
        e.handle_key(&key('z'), &mut t); // unmapped → should cancel pending g
        e.handle_key(&key('g'), &mut t); // lone g, NOT gg
        assert_eq!(
            super::super::cursor_tuple(&t).0,
            2,
            "stray g after cancelled prefix must not jump to file start"
        );
    }

    #[test]
    fn pending_g_cleared_through_insert() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two", "three"]);
        e.handle_key(&key('G'), &mut t);
        e.handle_key(&key('g'), &mut t); // start gg
        e.handle_key(&key('a'), &mut t); // enter insert (should clear pending_g)
        e.handle_key(&KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE), &mut t);
        e.handle_key(&key('g'), &mut t); // lone g
        assert_eq!(
            super::super::cursor_tuple(&t).0,
            2,
            "g after insert must not complete a stale gg"
        );
    }

    // ── Operator + motion tests ──────────────────────────────────────────────

    #[test]
    fn dw_deletes_word() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["hello world"]);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('w'), &mut t);
        assert_eq!(t.lines(), &["world"]);
    }

    #[test]
    fn dd_deletes_line_linewise() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two", "three"]);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('d'), &mut t);
        assert_eq!(t.lines(), &["two", "three"]);
        let reg = e.registers.read().expect("dd must fill the register");
        assert_eq!(reg.kind, RegisterKind::Linewise);
        assert_eq!(reg.text, "one\n");
    }

    #[test]
    fn yy_then_p_duplicates_line() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two"]);
        e.handle_key(&key('y'), &mut t);
        e.handle_key(&key('y'), &mut t);
        e.handle_key(&key('p'), &mut t);
        assert_eq!(t.lines(), &["one", "one", "two"]);
    }

    #[test]
    fn cw_deletes_word_and_enters_insert() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["hello world"]);
        e.handle_key(&key('c'), &mut t);
        e.handle_key(&key('w'), &mut t);
        assert_eq!(*e.mode(), EditorMode::Insert);
        // Vim `cw` = `ce`: deletes up to end of word (exclusive of trailing
        // space), so " world" remains (space preserved). This matches vim's
        // actual cw = ce behaviour.
        assert_eq!(t.lines(), &[" world"]);
    }

    // ── Linewise delete/paste tests ──────────────────────────────────────────

    #[test]
    fn charwise_p_pastes_after_cursor() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abc"]);
        // yank the first char with `yl`
        e.handle_key(&key('y'), &mut t);
        e.handle_key(&key('l'), &mut t);
        e.handle_key(&key('p'), &mut t);
        assert_eq!(t.lines(), &["aabc"]);
    }

    #[test]
    fn dd_on_last_line_removes_it() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two", "three"]);
        e.handle_key(&key('G'), &mut t); // to last line
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('d'), &mut t);
        assert_eq!(t.lines(), &["one", "two"]);
    }

    #[test]
    fn dd_on_only_line_leaves_empty() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["only"]);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('d'), &mut t);
        assert_eq!(t.lines(), &[""]);
    }

    #[test]
    fn linewise_2p_inserts_two_copies() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two"]);
        e.handle_key(&key('y'), &mut t);
        e.handle_key(&key('y'), &mut t); // yank "one" linewise
        e.handle_key(&key('2'), &mut t);
        e.handle_key(&key('p'), &mut t);
        assert_eq!(t.lines(), &["one", "one", "one", "two"]);
    }

    #[test]
    fn yy_last_line_then_p_duplicates() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two"]);
        e.handle_key(&key('G'), &mut t); // last line "two"
        e.handle_key(&key('y'), &mut t);
        e.handle_key(&key('y'), &mut t);
        e.handle_key(&key('p'), &mut t);
        assert_eq!(t.lines(), &["one", "two", "two"]);
    }

    // ── Single-key edit tests ────────────────────────────────────────────────

    #[test]
    fn x_deletes_char_under_cursor() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abc"]);
        e.handle_key(&key('x'), &mut t);
        assert_eq!(t.lines(), &["bc"]);
    }

    #[test]
    fn r_replaces_char() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abc"]);
        e.handle_key(&key('r'), &mut t);
        e.handle_key(&key('Z'), &mut t);
        assert_eq!(t.lines(), &["Zbc"]);
        assert_eq!(*e.mode(), EditorMode::Normal);
    }

    #[test]
    fn u_undoes_last_edit() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abc"]);
        e.handle_key(&key('x'), &mut t);
        e.handle_key(&key('u'), &mut t);
        assert_eq!(t.lines(), &["abc"]);
    }

    #[test]
    fn tilde_toggles_case() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abc"]);
        e.handle_key(&key('~'), &mut t);
        assert_eq!(t.lines(), &["Abc"]);
    }

    // ── Find (f/t/;/,) tests ─────────────────────────────────────────────────

    #[test]
    fn f_moves_to_char() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["hello, world"]);
        e.handle_key(&key('f'), &mut t);
        e.handle_key(&key(','), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 5));
    }

    #[test]
    fn df_deletes_through_char() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["hello, world"]);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('f'), &mut t);
        e.handle_key(&key(','), &mut t);
        assert_eq!(t.lines(), &[" world"]);
    }

    #[test]
    fn t_stops_before_char() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["hello, world"]);
        e.handle_key(&key('t'), &mut t);
        e.handle_key(&key(','), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 4)); // on 'o', before ','
    }

    #[test]
    fn semicolon_repeats_find() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["a.b.c.d"]);
        e.handle_key(&key('f'), &mut t);
        e.handle_key(&key('.'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t).1, 1);
        e.handle_key(&key(';'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t).1, 3);
    }

    // ── Text object tests ────────────────────────────────────────────────────

    #[test]
    fn diw_deletes_inner_word() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo bar baz"]);
        // cursor on 'b' of "bar"
        e.handle_key(&key('w'), &mut t);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('i'), &mut t);
        e.handle_key(&key('w'), &mut t);
        assert_eq!(t.lines(), &["foo  baz"]);
    }

    #[test]
    fn ci_quote_changes_inside_quotes() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["say \"hi\" now"]);
        // move onto the text inside quotes: f then h lands on 'h' (col 5)
        e.handle_key(&key('f'), &mut t);
        e.handle_key(&key('h'), &mut t);
        e.handle_key(&key('c'), &mut t);
        e.handle_key(&key('i'), &mut t);
        e.handle_key(&key('"'), &mut t);
        assert_eq!(t.lines(), &["say \"\" now"]);
        assert_eq!(*e.mode(), EditorMode::Insert);
    }

    #[test]
    fn di_paren_deletes_inside_parens() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo(bar)baz"]);
        e.handle_key(&key('f'), &mut t);
        e.handle_key(&key('('), &mut t); // cursor on '('
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('i'), &mut t);
        e.handle_key(&key('('), &mut t);
        assert_eq!(t.lines(), &["foo()baz"]);
    }

    #[test]
    fn daw_deletes_word_and_trailing_space() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo bar baz"]);
        e.handle_key(&key('w'), &mut t); // onto "bar"
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('a'), &mut t);
        e.handle_key(&key('w'), &mut t);
        assert_eq!(t.lines(), &["foo baz"]);
    }

    // ── Matching pair (%) tests ──────────────────────────────────────────────

    #[test]
    fn percent_jumps_to_matching_paren() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo(bar)baz"]);
        e.handle_key(&key('f'), &mut t);
        e.handle_key(&key('('), &mut t); // cursor on '('
        e.handle_key(&key('%'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 7)); // matching ')'
    }

    #[test]
    fn percent_jumps_back_from_close() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo(bar)baz"]);
        e.handle_key(&key('f'), &mut t);
        e.handle_key(&key(')'), &mut t); // cursor on ')'
        e.handle_key(&key('%'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 3)); // back to '('
    }

    #[test]
    fn percent_handles_nested() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["(a(b)c)"]);
        // cursor on outer '(' at col 0
        e.handle_key(&key('%'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 6)); // matching outer ')'
    }

    // ── Visual mode tests ────────────────────────────────────────────────────

    /// Charwise Visual is inclusive of the cursor char. `v` + 2×`l` leaves
    /// the cursor on col 2 ('l'); the inclusive range covers cols 0,1,2 = "hel".
    #[test]
    fn v_motion_d_deletes_selection() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["hello"]);
        e.handle_key(&key('v'), &mut t); // anchor col 0
        e.handle_key(&key('l'), &mut t); // cursor → col 1
        e.handle_key(&key('l'), &mut t); // cursor → col 2, inclusive covers "hel"
        e.handle_key(&key('d'), &mut t); // delete "hel"
        assert_eq!(t.lines(), &["lo"]); // inclusive: deletes cols 0,1,2 ("hel")
        assert_eq!(*e.mode(), EditorMode::Normal);
    }

    #[test]
    #[allow(non_snake_case)]
    fn V_then_d_deletes_line() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two"]);
        e.handle_key(&key('V'), &mut t);
        e.handle_key(&key('d'), &mut t);
        assert_eq!(t.lines(), &["two"]);
        assert_eq!(*e.mode(), EditorMode::Normal);
    }

    /// Inclusive yank: v + l (cursor col 1) yanks "he" (2 chars, inclusive).
    /// After p pastes the yanked text, buffer grew by 2.
    #[test]
    fn visual_y_yanks_and_returns_to_normal() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["hello"]);
        e.handle_key(&key('v'), &mut t); // anchor col 0
        e.handle_key(&key('l'), &mut t); // cursor col 1, inclusive selection "he"
        e.handle_key(&key('y'), &mut t); // yank "he" (2 chars), mode → Normal
        assert_eq!(*e.mode(), EditorMode::Normal);
        // p pastes the yanked "he" after current cursor
        let before_len: usize = t.lines().iter().map(|l| l.len()).sum();
        e.handle_key(&key('p'), &mut t);
        let after_len: usize = t.lines().iter().map(|l| l.len()).sum();
        // buffer grew by exactly 2 chars (the yanked "he")
        assert_eq!(after_len, before_len + 2);
    }

    #[test]
    fn visual_esc_cancels_and_returns_normal() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["hello"]);
        e.handle_key(&key('v'), &mut t);
        e.handle_key(&key('l'), &mut t);
        assert_eq!(*e.mode(), EditorMode::Visual);
        e.handle_key(&esc(), &mut t);
        assert_eq!(*e.mode(), EditorMode::Normal);
        // selection should be cancelled
        assert!(t.selection_range().is_none());
    }

    #[test]
    fn visual_c_enters_insert_after_delete() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["hello"]);
        e.handle_key(&key('v'), &mut t); // anchor col 0
        e.handle_key(&key('l'), &mut t); // cursor col 1, inclusive covers "he"
        e.handle_key(&key('c'), &mut t); // delete "he" (inclusive), enter Insert
        assert_eq!(*e.mode(), EditorMode::Insert);
        assert_eq!(t.lines(), &["llo"]); // inclusive: deletes cols 0,1 ("he")
    }

    // ── Indent/outdent tests ─────────────────────────────────────────────────

    #[test]
    fn indent_line_adds_spaces() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["x"]);
        e.handle_key(&key('>'), &mut t);
        e.handle_key(&key('>'), &mut t);
        assert_eq!(t.lines(), &["    x"]);
    }

    #[test]
    fn indent_keeps_cursor_over_same_char() {
        // regression: >> left the cursor one row BELOW the indented block;
        // the cursor must stay over the char it sat on, shifted with the
        // indent (neovim behavior).
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two", "three"]);
        e.handle_key(&key('l'), &mut t); // onto 'n' (col 1)
        e.handle_key(&key('>'), &mut t);
        e.handle_key(&key('>'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 5)); // still on 'n'
        // counted form too: cursor stays on the first line of the block
        e.handle_key(&key('2'), &mut t);
        e.handle_key(&key('>'), &mut t);
        e.handle_key(&key('>'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t).0, 0);
    }

    #[test]
    fn outdent_keeps_cursor_over_same_char() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["    x"]);
        e.handle_key(&key('f'), &mut t);
        e.handle_key(&key('x'), &mut t); // ON 'x' (col 4)
        e.handle_key(&key('<'), &mut t);
        e.handle_key(&key('<'), &mut t);
        assert_eq!(t.lines(), &["x"]);
        assert_eq!(super::super::cursor_tuple(&t).1, 0); // still on 'x'
    }

    #[test]
    fn outdent_removes_spaces() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["        x"]); // 8 spaces
        e.handle_key(&key('<'), &mut t);
        e.handle_key(&key('<'), &mut t);
        assert_eq!(t.lines(), &["    x"]); // removed 4
    }

    #[test]
    fn pending_hint_shows_operator_and_count() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abc"]);
        e.handle_key(&key('2'), &mut t);
        e.handle_key(&key('d'), &mut t);
        assert_eq!(e.pending_hint().as_deref(), Some("2d"));
    }

    // ── Dot-repeat tests ─────────────────────────────────────────────────────

    #[test]
    fn dot_repeats_x() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abcdef"]);
        e.handle_key(&key('x'), &mut t);
        e.handle_key(&key('.'), &mut t);
        assert_eq!(t.lines(), &["cdef"]);
    }

    #[test]
    fn dot_repeats_dw() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one two three four"]);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('w'), &mut t); // delete "one "
        e.handle_key(&key('.'), &mut t); // delete "two "
        assert_eq!(t.lines(), &["three four"]);
    }

    #[test]
    fn dot_repeats_change_with_typed_text() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo bar"]);
        // cw -> type "X" -> Esc, then move to next word and dot
        e.handle_key(&key('c'), &mut t);
        e.handle_key(&key('w'), &mut t); // cw: deletes "foo" (cw=ce keeps trailing space), enters Insert at col 0
        // simulate the user typing "X" via the host PassThrough path:
        t.insert_str("X");
        e.handle_key(&esc(), &mut t); // capture "X"
        e.handle_key(&key('w'), &mut t); // move to "bar"
        e.handle_key(&key('.'), &mut t); // repeat cw+X
        assert_eq!(t.lines(), &["X X"]);
    }

    #[test]
    fn dot_repeats_multiline_change() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo bar"]);
        e.handle_key(&key('c'), &mut t);
        e.handle_key(&key('w'), &mut t); // cw on "foo" → Insert at col 0
        t.insert_str("a");
        t.insert_newline();
        t.insert_str("b"); // typed "a\nb"
        e.handle_key(&esc(), &mut t); // captures "a\nb"
        // Buffer is now ["a", "b bar"]; cursor stepped back to col 0 of row 1 ("b bar").
        // Confirm the multi-line buffer state from the insert:
        assert_eq!(t.lines(), &["a", "b bar"]);

        // Verify replay: position on "bar", run `.`, should produce "a\nb" again.
        // Move to word "bar" (it is at col 2 of row 1).
        e.handle_key(&key('w'), &mut t); // move to "bar" (word-forward from "b" → "bar")
        e.handle_key(&key('.'), &mut t); // replay: cw on "bar" → insert "a\nb"
        // After replay the buffer should have "a\nb" inserted in place of "bar":
        // row 1 was "b bar", cw from "bar" removes "bar", inserts "a\nb" → ["a", "b a", "b"]
        assert!(
            t.lines().len() >= 3,
            "replay of multiline insert should produce >=3 lines: {:?}",
            t.lines()
        );
    }

    // ── space_leads predicate tests ──────────────────────────────────────────

    #[test]
    fn space_leads_only_in_clean_normal() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["x"]);
        assert!(e.space_leads());
        e.handle_key(&key('d'), &mut t); // operator pending
        assert!(!e.space_leads());
        e.handle_key(&key('w'), &mut t); // completes dw, clears pending
        assert!(e.space_leads());
        e.handle_key(&key('i'), &mut t); // insert
        assert!(!e.space_leads());
    }

    // ── Host-action tests ────────────────────────────────────────────────────

    #[test]
    fn colon_emits_open_palette() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["x"]);
        assert_eq!(
            e.handle_key(&key(':'), &mut t),
            VimKeyOutcome::Host(VimHostAction::OpenPalette)
        );
    }

    #[test]
    fn slash_emits_open_search_forward() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["x"]);
        assert_eq!(
            e.handle_key(&key('/'), &mut t),
            VimKeyOutcome::Host(VimHostAction::OpenSearch { forward: true })
        );
    }

    #[test]
    #[allow(non_snake_case)]
    fn n_and_N_emit_search_nav() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["x"]);
        assert_eq!(
            e.handle_key(&key('n'), &mut t),
            VimKeyOutcome::Host(VimHostAction::SearchNext)
        );
        assert_eq!(
            e.handle_key(&key('N'), &mut t),
            VimKeyOutcome::Host(VimHostAction::SearchPrev)
        );
    }

    // ── Mouse → Visual mode tests ────────────────────────────────────────────

    #[test]
    fn mouse_selection_enters_and_leaves_visual() {
        let mut e = VimEngine::default();
        e.sync_mouse_selection(true);
        assert_eq!(*e.mode(), EditorMode::Visual);
        e.sync_mouse_selection(false);
        assert_eq!(*e.mode(), EditorMode::Normal);
    }

    #[test]
    fn mouse_no_selection_in_normal_stays_normal() {
        let mut e = VimEngine::default();
        e.sync_mouse_selection(false);
        assert_eq!(*e.mode(), EditorMode::Normal);
    }

    #[test]
    fn mouse_does_not_disturb_insert() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["x"]);
        e.handle_key(&key('i'), &mut t); // Insert
        e.sync_mouse_selection(true);
        assert_eq!(*e.mode(), EditorMode::Insert); // mouse doesn't yank Insert into Visual
    }

    // ── Bug-fix regression tests ─────────────────────────────────────────────

    #[test]
    fn di_paren_on_empty_line_does_not_panic() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from([""]); // empty line
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('i'), &mut t);
        e.handle_key(&key('('), &mut t); // must not panic; no-op
        assert_eq!(t.lines(), &[""]);
    }

    #[test]
    fn esc_clears_pending_g_in_normal() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two", "three"]);
        e.handle_key(&key('G'), &mut t); // last line
        assert_eq!(super::super::cursor_tuple(&t).0, 2);
        e.handle_key(&key('g'), &mut t); // start gg
        e.handle_key(&KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE), &mut t); // cancel
        e.handle_key(&key('g'), &mut t); // lone g
        assert_eq!(
            super::super::cursor_tuple(&t).0,
            2,
            "Esc must cancel pending g"
        );
    }

    #[test]
    fn esc_clears_pending_operator_object_in_normal() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo bar baz"]);
        e.handle_key(&key('d'), &mut t); // operator pending
        e.handle_key(&key('i'), &mut t); // object kind pending (NOT insert — operator pending)
        e.handle_key(&KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE), &mut t); // cancel
        // buffer unchanged (no diw happened)
        assert_eq!(t.lines(), &["foo bar baz"]);
        // and we're back to clean Normal: a plain motion works, mode still Normal
        e.handle_key(&key('w'), &mut t);
        assert_eq!(*e.mode(), EditorMode::Normal);
        assert_eq!(
            t.lines(),
            &["foo bar baz"],
            "w after Esc must be a motion, not diw"
        );
    }

    // ── Bug A: di( on nested parens ─────────────────────────────────────────

    #[test]
    fn di_paren_nested_selects_inner_of_outer() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["((x))"]);
        // cursor at col 0 (outer '(')
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('i'), &mut t);
        e.handle_key(&key('('), &mut t);
        assert_eq!(t.lines(), &["()"]); // outer kept, inner content "(x)" deleted
    }

    #[test]
    fn di_paren_from_inside_nested() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["((x))"]);
        e.handle_key(&key('l'), &mut t); // col1 (inner '(')
        e.handle_key(&key('l'), &mut t); // col2 ('x')
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('i'), &mut t);
        e.handle_key(&key('('), &mut t);
        assert_eq!(t.lines(), &["(())"]); // inner content "x" deleted
    }

    // ── Bug B: di" in gap between pairs ─────────────────────────────────────

    #[test]
    fn di_quote_in_gap_is_noop() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["\"foo\" \"bar\""]);
        // move cursor to the space (col 5) between the two strings
        for _ in 0..5 {
            e.handle_key(&key('l'), &mut t);
        }
        assert_eq!(super::super::cursor_tuple(&t).1, 5);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('i'), &mut t);
        e.handle_key(&key('"'), &mut t);
        assert_eq!(t.lines(), &["\"foo\" \"bar\""]); // unchanged (no-op)
    }

    #[test]
    fn di_quote_inside_still_works() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["\"foo\" \"bar\""]);
        for _ in 0..7 {
            e.handle_key(&key('l'), &mut t);
        } // inside "bar"
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('i'), &mut t);
        e.handle_key(&key('"'), &mut t);
        assert_eq!(t.lines(), &["\"foo\" \"\""]); // bar deleted, foo intact
    }

    // ── Bug C: df<last-char> must not join next line ─────────────────────────

    #[test]
    fn df_last_char_does_not_join_next_line() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abc", "xyz"]);
        // cursor at (0,0); df c  → delete through the 'c' (last char of line 0)
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('f'), &mut t);
        e.handle_key(&key('c'), &mut t);
        assert_eq!(t.lines(), &["", "xyz"]); // line 0 emptied, newline + line 1 intact
    }

    // ── Bug D: cc on a single-line buffer ────────────────────────────────────

    #[test]
    fn cc_single_line_leaves_one_empty_line() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["hello"]);
        e.handle_key(&key('c'), &mut t);
        e.handle_key(&key('c'), &mut t);
        assert_eq!(t.lines(), &[""]);
        assert_eq!(*e.mode(), EditorMode::Insert);
    }

    #[test]
    fn cc_middle_line_still_works() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two", "three"]);
        e.handle_key(&key('j'), &mut t); // line "two"
        e.handle_key(&key('c'), &mut t);
        e.handle_key(&key('c'), &mut t);
        assert_eq!(t.lines(), &["one", "", "three"]);
        assert_eq!(*e.mode(), EditorMode::Insert);
    }

    // ── Bug E: r on empty line must be no-op ────────────────────────────────

    #[test]
    fn r_on_empty_line_is_noop() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from([""]);
        e.handle_key(&key('r'), &mut t);
        let out = e.handle_key(&key('Z'), &mut t);
        assert_eq!(out, VimKeyOutcome::NoOp);
        assert_eq!(t.lines(), &[""]);
    }

    // ── P2.G: charwise Visual inclusive tests ────────────────────────────────

    #[test]
    fn visual_v_then_d_deletes_char_under_cursor() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abc"]);
        e.handle_key(&key('v'), &mut t); // select just 'a' (cursor col0)
        e.handle_key(&key('d'), &mut t);
        assert_eq!(t.lines(), &["bc"]); // 'a' deleted (inclusive of cursor char)
    }

    #[test]
    fn visual_e_then_d_inclusive() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["hello world"]);
        e.handle_key(&key('v'), &mut t);
        e.handle_key(&key('e'), &mut t); // cursor on 'o' col4
        e.handle_key(&key('d'), &mut t);
        assert_eq!(t.lines(), &[" world"]); // "hello" deleted inclusive
    }

    // ── Bug fix: vim `e` must land ON the last word char (inclusive) ─────────

    #[test]
    fn e_lands_on_last_word_char() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["hello world"]);
        e.handle_key(&key('e'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 4)); // 'o', last char of "hello"
    }

    #[test]
    fn e_twice_reaches_second_word_end() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["hello world"]);
        e.handle_key(&key('e'), &mut t);
        e.handle_key(&key('e'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 10)); // 'd', last char of "world"
    }

    #[test]
    fn de_deletes_to_word_end_inclusive() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["hello world"]);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('e'), &mut t);
        assert_eq!(t.lines(), &[" world"]); // deletes "hello" inclusive of 'o'
    }

    // ── Bug fix: vim yank leaves cursor at selection start; charwise p never wraps ──

    #[test]
    fn visual_y_leaves_cursor_at_selection_start() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo bar", "baz"]);
        for _ in 0..4 {
            e.handle_key(&key('l'), &mut t);
        } // onto 'b' of "bar" (col 4)
        e.handle_key(&key('v'), &mut t);
        e.handle_key(&key('e'), &mut t); // select "bar"
        e.handle_key(&key('y'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 4)); // cursor at start of selection, not the end
    }

    #[test]
    fn charwise_p_after_eol_word_does_not_touch_next_line() {
        // reproduce the user's bug: yank an end-of-line word, paste, must NOT hit the line below
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo bar", "baz"]);
        for _ in 0..4 {
            e.handle_key(&key('l'), &mut t);
        } // 'b' of "bar"
        e.handle_key(&key('v'), &mut t);
        e.handle_key(&key('e'), &mut t); // select "bar" (end of line 0)
        e.handle_key(&key('y'), &mut t); // yank; cursor → col 4
        e.handle_key(&key('p'), &mut t); // paste after cursor char 'b'
        assert_eq!(t.lines()[1], "baz"); // line below UNTOUCHED
        assert_eq!(t.lines().len(), 2); // no new line, no merge
        assert_eq!(t.lines()[0], "foo bbarar"); // "bar" pasted after 'b' on line 0 (vim p-after)
    }

    #[test]
    fn charwise_p_at_line_end_appends_same_line() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["ab", "cd"]);
        // yank "ab" charwise via v e y
        e.handle_key(&key('v'), &mut t);
        e.handle_key(&key('e'), &mut t); // select "ab"
        e.handle_key(&key('y'), &mut t); // cursor → col 0
        e.handle_key(&key('$'), &mut t); // to last char of line 0 ('b')
        e.handle_key(&key('p'), &mut t); // append "ab" after 'b'
        assert_eq!(t.lines()[0], "abab");
        assert_eq!(t.lines()[1], "cd"); // line below untouched
    }

    // ── Visual p: replace selection with register ────────────────────────────

    #[test]
    fn visual_p_replaces_charwise_selection() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo bar"]);
        // yank "foo" (v e y at col 0) → register = "foo", cursor back to col 0
        e.handle_key(&key('v'), &mut t);
        e.handle_key(&key('e'), &mut t);
        e.handle_key(&key('y'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 0));
        // select "bar" and paste over it
        for _ in 0..4 {
            e.handle_key(&key('l'), &mut t);
        } // onto 'b' (col 4)
        e.handle_key(&key('v'), &mut t);
        e.handle_key(&key('e'), &mut t); // select "bar"
        e.handle_key(&key('p'), &mut t);
        assert_eq!(t.lines(), &["foo foo"]); // "bar" replaced by "foo"
        assert_eq!(*e.mode(), EditorMode::Normal);
    }

    #[test]
    fn visual_p_yanks_replaced_selection() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo bar"]);
        // yank "foo"
        e.handle_key(&key('v'), &mut t);
        e.handle_key(&key('e'), &mut t);
        e.handle_key(&key('y'), &mut t); // reg = "foo", cursor col 0
        // select "bar" and paste over it
        for _ in 0..4 {
            e.handle_key(&key('l'), &mut t);
        } // col 4 'b'
        e.handle_key(&key('v'), &mut t);
        e.handle_key(&key('e'), &mut t);
        e.handle_key(&key('p'), &mut t); // "bar" replaced by "foo"; "bar" now yanked
        assert_eq!(t.lines(), &["foo foo"]);
        // now paste the replaced "bar" at end of line to prove it's in the register
        e.handle_key(&key('$'), &mut t); // last char ('o', col 6)
        e.handle_key(&key('p'), &mut t); // append "bar" after it
        assert_eq!(t.lines(), &["foo foobar"]);
    }

    // ── Cheatsheet motions: g_/5G/5gg, ge/gE, WORD (W/E/B) ───────────────────

    #[test]
    fn g_underscore_jumps_to_last_non_blank() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["hi there   "]);
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('_'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 7)); // the final 'e'
    }

    #[test]
    fn d_g_underscore_deletes_through_last_non_blank() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo bar  "]);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('_'), &mut t);
        assert_eq!(t.lines(), &["  "]); // inclusive of the 'r'
    }

    #[test]
    #[allow(non_snake_case)]
    fn count_G_and_count_gg_go_to_line() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["1", "2", "3", "4", "5", "6"]);
        e.handle_key(&key('5'), &mut t);
        e.handle_key(&key('G'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t).0, 4); // line 5
        e.handle_key(&key('2'), &mut t);
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('g'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t).0, 1); // line 2
    }

    #[test]
    #[allow(non_snake_case)]
    fn d_count_G_deletes_lines_through_target() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two", "three"]);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('2'), &mut t);
        e.handle_key(&key('G'), &mut t); // delete lines 1..=2 (linewise)
        assert_eq!(t.lines(), &["three"]);
    }

    #[test]
    fn ge_jumps_to_previous_word_end() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo bar"]);
        e.handle_key(&key('$'), &mut t); // on 'r' (col 6)
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('e'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 2)); // 'o' of foo
    }

    #[test]
    fn ge_stops_at_class_change() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo.bar"]);
        e.handle_key(&key('$'), &mut t); // 'r' (col 6)
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('e'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 3)); // the '.'
    }

    #[test]
    #[allow(non_snake_case)]
    fn gE_ignores_punctuation_boundaries() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["aa bb.cc dd"]);
        e.handle_key(&key('$'), &mut t); // last 'd' (col 10)
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('E'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 7)); // end of "bb.cc"
    }

    #[test]
    fn ge_at_buffer_start_is_noop() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo"]);
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('e'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 0));
    }

    #[test]
    fn dge_deletes_backward_inclusive_of_cursor() {
        // vim: dge eats from the previous word end through the cursor char
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abc def"]);
        e.handle_key(&key('$'), &mut t); // on 'f'
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('e'), &mut t);
        assert_eq!(t.lines(), &["ab"]);
    }

    #[test]
    #[allow(non_snake_case)]
    fn W_treats_punctuated_run_as_one_word() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo.bar baz"]);
        e.handle_key(&key('W'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 8)); // 'b' of baz
    }

    #[test]
    #[allow(non_snake_case)]
    fn E_jumps_to_end_of_WORD() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo.bar baz"]);
        e.handle_key(&key('E'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 6)); // 'r' of foo.bar
    }

    #[test]
    #[allow(non_snake_case)]
    fn B_jumps_to_WORD_start() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo.bar baz"]);
        e.handle_key(&key('W'), &mut t); // col 8
        e.handle_key(&key('B'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 0));
    }

    #[test]
    #[allow(non_snake_case)]
    fn W_crosses_lines_and_stops_at_empty_line() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo", "", "bar"]);
        e.handle_key(&key('W'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (1, 0)); // empty line is a stop
        e.handle_key(&key('W'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (2, 0));
    }

    #[test]
    #[allow(non_snake_case)]
    fn dW_deletes_whole_WORD() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo.bar baz"]);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('W'), &mut t);
        assert_eq!(t.lines(), &["baz"]);
    }

    #[test]
    #[allow(non_snake_case)]
    fn cW_acts_like_cE() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo.bar baz"]);
        e.handle_key(&key('c'), &mut t);
        e.handle_key(&key('W'), &mut t);
        assert_eq!(*e.mode(), EditorMode::Insert);
        assert_eq!(t.lines(), &[" baz"]); // trailing space preserved (cW = cE)
    }

    // ── Awaiting + replace-stack fixes ───────────────────────────────────────

    #[test]
    fn hint_shows_object_scope_mid_sequence() {
        // regression: `diw` in flight showed "d" instead of "di"
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo bar"]);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('i'), &mut t);
        assert_eq!(e.pending_hint().as_deref(), Some("di"));
    }

    #[test]
    fn hint_shows_actual_find_key() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo"]);
        e.handle_key(&key('T'), &mut t);
        assert_eq!(e.pending_hint().as_deref(), Some("T")); // was always 'f'
    }

    #[test]
    fn replace_backspace_restores_overwritten_char() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abc"]);
        e.handle_key(&key('R'), &mut t);
        e.handle_key(&key('X'), &mut t); // 'a' → X
        e.handle_key(&key('Y'), &mut t); // 'b' → Y
        e.handle_key(
            &KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE),
            &mut t,
        );
        e.handle_key(&esc(), &mut t);
        assert_eq!(t.lines(), &["Xbc"]); // 'b' restored (vim replace stack)
    }

    #[test]
    fn replace_backspace_removes_appended_char() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["a"]);
        e.handle_key(&key('R'), &mut t);
        e.handle_key(&key('X'), &mut t); // 'a' → X
        e.handle_key(&key('Y'), &mut t); // appended past EOL
        e.handle_key(
            &KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE),
            &mut t,
        );
        e.handle_key(&esc(), &mut t);
        assert_eq!(t.lines(), &["X"]); // appended char removed, not restored
    }

    // ── Pure WORD-scanner unit tests (no TextArea needed) ────────────────────

    fn buf(lines: &[&str]) -> Vec<String> {
        lines.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn pure_word_forward_big_positions() {
        let b = buf(&["foo.bar baz"]);
        assert_eq!(VimEngine::word_forward_big(&b, (0, 0)), (0, 8));
        let b = buf(&["foo", "", "bar"]);
        assert_eq!(VimEngine::word_forward_big(&b, (0, 0)), (1, 0)); // empty-line stop
        assert_eq!(VimEngine::word_forward_big(&b, (1, 0)), (2, 0));
    }

    #[test]
    fn pure_word_back_big_positions() {
        let b = buf(&["foo.bar baz"]);
        assert_eq!(VimEngine::word_back_big(&b, (0, 8)), (0, 0));
        assert_eq!(VimEngine::word_back_big(&b, (0, 0)), (0, 0)); // fails in place
    }

    #[test]
    fn pure_word_end_big_positions() {
        let b = buf(&["foo.bar baz"]);
        assert_eq!(VimEngine::word_end_big(&b, (0, 0)), Some((0, 6)));
        assert_eq!(VimEngine::word_end_big(&b, (0, 10)), None); // nothing ahead
    }

    #[test]
    fn pure_word_end_back_positions() {
        let b = buf(&["foo.bar"]);
        assert_eq!(VimEngine::word_end_back(&b, (0, 6), false), Some((0, 3))); // class change
        assert_eq!(VimEngine::word_end_back(&b, (0, 6), true), None); // one WORD, no prev end
        assert_eq!(VimEngine::word_end_back(&b, (0, 0), false), None); // buffer start
    }

    // ── Holistic-review fixes ────────────────────────────────────────────────

    #[test]
    fn visual_counted_motion_extends_by_count() {
        // regression: the 5G translation consumed the count for EVERY motion
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abcdef"]);
        e.handle_key(&key('v'), &mut t);
        e.handle_key(&key('3'), &mut t);
        e.handle_key(&key('l'), &mut t); // cursor → col 3, inclusive covers "abcd"
        e.handle_key(&key('d'), &mut t);
        assert_eq!(t.lines(), &["ef"]);
    }

    #[test]
    #[allow(non_snake_case)]
    fn gUu_aborts_without_running_undo() {
        // vim: a mismatched key after a pending operator cancels everything
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["ab"]);
        e.handle_key(&key('x'), &mut t); // real change → "b"
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('U'), &mut t); // Uppercase pending
        e.handle_key(&key('u'), &mut t); // mismatch — must NOT run Undo
        assert_eq!(t.lines(), &["b"]); // x not reverted
    }

    #[test]
    fn dx_and_dp_abort_with_operator_pending() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abc"]);
        e.handle_key(&key('y'), &mut t);
        e.handle_key(&key('l'), &mut t); // register = "a"
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('x'), &mut t); // vim aborts — nothing deleted
        assert_eq!(t.lines(), &["abc"]);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('p'), &mut t); // vim aborts — nothing pasted
        assert_eq!(t.lines(), &["abc"]);
    }

    #[test]
    fn dge_at_buffer_start_is_noop() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo"]);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('e'), &mut t); // motion fails → whole op no-op
        assert_eq!(t.lines(), &["foo"]);
    }

    #[test]
    fn gugu_doubled_g_form_runs_linewise() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["ABC def"]);
        for c in "gugu".chars() {
            e.handle_key(&key(c), &mut t);
        }
        assert_eq!(t.lines(), &["abc def"]);
    }

    #[test]
    #[allow(non_snake_case)]
    fn visual_J_joins_selected_lines_with_space() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["a", "b", "c"]);
        e.handle_key(&key('V'), &mut t);
        e.handle_key(&key('j'), &mut t);
        e.handle_key(&key('j'), &mut t); // select all three
        e.handle_key(&key('J'), &mut t);
        assert_eq!(t.lines(), &["a b c"]);
        assert_eq!(*e.mode(), EditorMode::Normal);
    }

    #[test]
    #[allow(non_snake_case)]
    fn visual_gJ_joins_selected_lines_raw() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["a", "  b"]);
        e.handle_key(&key('V'), &mut t);
        e.handle_key(&key('j'), &mut t);
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('J'), &mut t);
        assert_eq!(t.lines(), &["a  b"]); // verbatim, indent kept
    }

    #[test]
    #[allow(non_snake_case)]
    fn replace_mode_arrows_move_cursor() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abcd"]);
        e.handle_key(&key('R'), &mut t);
        e.handle_key(&KeyEvent::new(KeyCode::Right, KeyModifiers::NONE), &mut t);
        e.handle_key(&KeyEvent::new(KeyCode::Right, KeyModifiers::NONE), &mut t);
        e.handle_key(&key('X'), &mut t); // overwrite 'c'
        e.handle_key(&esc(), &mut t);
        assert_eq!(t.lines(), &["abXd"]);
        // capture restarted at the movement target: '.' overwrites one char
        e.handle_key(&key('0'), &mut t);
        e.handle_key(&key('.'), &mut t);
        assert_eq!(t.lines(), &["XbXd"]);
    }

    #[test]
    fn esc_from_insert_clears_stray_selection() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["hello"]);
        e.handle_key(&key('i'), &mut t);
        // simulate a mouse drag mid-insert leaving a live selection
        t.start_selection();
        t.move_cursor(ratatui_textarea::CursorMove::Forward);
        e.handle_key(&esc(), &mut t);
        assert!(
            t.selection_range().is_none(),
            "Esc must drop the stray selection"
        );
        assert_eq!(*e.mode(), EditorMode::Normal);
    }

    #[test]
    fn guu_undoes_in_one_step() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["Mixed Case Line"]);
        for c in "guu".chars() {
            e.handle_key(&key(c), &mut t);
        }
        assert_eq!(t.lines(), &["mixed case line"]);
        e.handle_key(&key('u'), &mut t); // single undo restores...
        e.handle_key(&key('u'), &mut t); // (cut+insert = 2 textarea edits)
        assert_eq!(t.lines(), &["Mixed Case Line"]);
    }

    // ── Visual g~ (case toggle; bare ~ is auto-surround) ─────────────────────

    #[test]
    fn visual_g_tilde_toggles_case_of_selection() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["FooBar"]);
        e.handle_key(&key('v'), &mut t);
        e.handle_key(&key('e'), &mut t); // select all of "FooBar"
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('~'), &mut t);
        assert_eq!(t.lines(), &["fOObAR"]);
        assert_eq!(*e.mode(), EditorMode::Normal);
    }

    #[test]
    fn visual_bare_tilde_still_passes_through_for_surround() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["FooBar"]);
        e.handle_key(&key('v'), &mut t);
        e.handle_key(&key('e'), &mut t);
        let out = e.handle_key(&key('~'), &mut t);
        assert_eq!(out, VimKeyOutcome::PassThrough); // host auto-surround wraps
        assert_eq!(*e.mode(), EditorMode::Normal);
    }

    // ── Case operators gu/gU/g~ ──────────────────────────────────────────────

    #[test]
    fn guw_lowercases_word() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["HELLO world"]);
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('u'), &mut t);
        e.handle_key(&key('w'), &mut t);
        assert_eq!(t.lines(), &["hello world"]);
        assert_eq!(super::super::cursor_tuple(&t), (0, 0)); // cursor at start
    }

    #[test]
    #[allow(non_snake_case)]
    fn gU_iw_uppercases_inner_word() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo bar baz"]);
        e.handle_key(&key('w'), &mut t); // onto "bar"
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('U'), &mut t);
        e.handle_key(&key('i'), &mut t);
        e.handle_key(&key('w'), &mut t);
        assert_eq!(t.lines(), &["foo BAR baz"]);
    }

    #[test]
    fn g_tilde_toggles_case_to_word_end() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["FooBar baz"]);
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('~'), &mut t);
        e.handle_key(&key('e'), &mut t); // inclusive to end of "FooBar"
        assert_eq!(t.lines(), &["fOObAR baz"]);
    }

    #[test]
    fn guu_lowercases_whole_line() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["HELLO World", "NEXT"]);
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('u'), &mut t);
        e.handle_key(&key('u'), &mut t);
        assert_eq!(t.lines(), &["hello world", "NEXT"]);
    }

    #[test]
    #[allow(non_snake_case)]
    fn visual_U_uppercases_selection() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["hello"]);
        e.handle_key(&key('v'), &mut t);
        e.handle_key(&key('l'), &mut t);
        e.handle_key(&key('l'), &mut t); // select "hel"
        e.handle_key(&key('U'), &mut t);
        assert_eq!(t.lines(), &["HELlo"]);
        assert_eq!(*e.mode(), EditorMode::Normal);
    }

    #[test]
    fn case_op_does_not_touch_register() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["keep CHANGE"]);
        e.handle_key(&key('y'), &mut t);
        e.handle_key(&key('e'), &mut t); // register = "keep"
        e.handle_key(&key('w'), &mut t); // onto "CHANGE"
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('u'), &mut t);
        e.handle_key(&key('w'), &mut t); // lowercase it
        assert_eq!(e.registers.read().unwrap().text, "keep"); // unchanged
    }

    #[test]
    #[allow(non_snake_case)]
    fn dot_repeats_gU_word() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one two"]);
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('U'), &mut t);
        e.handle_key(&key('e'), &mut t); // ONE
        e.handle_key(&key('w'), &mut t); // onto "two"
        e.handle_key(&key('.'), &mut t);
        assert_eq!(t.lines(), &["ONE TWO"]);
    }

    // ── Replace mode (R) ─────────────────────────────────────────────────────

    #[test]
    #[allow(non_snake_case)]
    fn R_overwrites_chars() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abcdef"]);
        e.handle_key(&key('R'), &mut t);
        assert_eq!(*e.mode(), EditorMode::Replace);
        e.handle_key(&key('X'), &mut t);
        e.handle_key(&key('Y'), &mut t);
        e.handle_key(&esc(), &mut t);
        assert_eq!(t.lines(), &["XYcdef"]); // overwrote, didn't insert
        assert_eq!(*e.mode(), EditorMode::Normal);
        assert_eq!(super::super::cursor_tuple(&t), (0, 1)); // stepped back onto 'Y'
    }

    #[test]
    #[allow(non_snake_case)]
    fn R_appends_past_line_end() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["ab"]);
        e.handle_key(&key('R'), &mut t);
        for c in "XYZ".chars() {
            e.handle_key(&key(c), &mut t);
        }
        e.handle_key(&esc(), &mut t);
        assert_eq!(t.lines(), &["XYZ"]); // overwrote "ab", appended 'Z'
    }

    #[test]
    #[allow(non_snake_case)]
    fn R_is_dot_repeatable() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["aaaa bbbb"]);
        e.handle_key(&key('R'), &mut t);
        e.handle_key(&key('X'), &mut t);
        e.handle_key(&key('X'), &mut t);
        e.handle_key(&esc(), &mut t); // "XXaa bbbb"
        e.handle_key(&key('w'), &mut t); // onto "bbbb"
        e.handle_key(&key('.'), &mut t); // overwrite "bb"
        assert_eq!(t.lines(), &["XXaa XXbb"]);
    }

    #[test]
    #[allow(non_snake_case)]
    fn aborted_R_keeps_dot_register() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abc"]);
        e.handle_key(&key('x'), &mut t); // real change
        e.handle_key(&key('R'), &mut t);
        e.handle_key(&esc(), &mut t); // typed nothing
        e.handle_key(&key('.'), &mut t); // must repeat x
        assert_eq!(t.lines(), &["c"]);
    }

    #[test]
    #[allow(non_snake_case)]
    fn R_mode_does_not_pass_through() {
        // Replace mode is engine-owned: chars must never reach the host's
        // textarea path (no auto-surround under R).
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["ab"]);
        e.handle_key(&key('R'), &mut t);
        let out = e.handle_key(&key('('), &mut t);
        assert_eq!(out, VimKeyOutcome::TextMutated); // consumed, not PassThrough
        assert_eq!(t.lines()[0].chars().next(), Some('(')); // raw overwrite
    }

    // ── J / gJ join semantics ────────────────────────────────────────────────

    #[test]
    #[allow(non_snake_case)]
    fn J_joins_with_single_space_stripping_indent() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo", "   bar"]);
        e.handle_key(&key('J'), &mut t);
        assert_eq!(t.lines(), &["foo bar"]);
        // cursor on the join-point space (vim)
        assert_eq!(super::super::cursor_tuple(&t), (0, 3));
    }

    #[test]
    #[allow(non_snake_case)]
    fn J_adds_no_extra_space_when_line_ends_in_whitespace() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo ", "bar"]);
        e.handle_key(&key('J'), &mut t);
        assert_eq!(t.lines(), &["foo bar"]);
    }

    #[test]
    #[allow(non_snake_case)]
    fn gJ_joins_without_space() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo", "   bar"]);
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('J'), &mut t);
        assert_eq!(t.lines(), &["foo   bar"]); // verbatim, indent kept
    }

    #[test]
    #[allow(non_snake_case)]
    fn three_J_joins_three_lines() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["a", "b", "c"]);
        e.handle_key(&key('3'), &mut t);
        e.handle_key(&key('J'), &mut t);
        assert_eq!(t.lines(), &["a b c"]);
    }

    // ── Insert entries ───────────────────────────────────────────────────────

    #[test]
    #[allow(non_snake_case)]
    fn I_inserts_at_first_non_blank() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["    indented"]);
        e.handle_key(&key('$'), &mut t); // away from the start
        e.handle_key(&key('I'), &mut t);
        assert_eq!(*e.mode(), EditorMode::Insert);
        assert_eq!(super::super::cursor_tuple(&t), (0, 4)); // on 'i', not col 0
    }

    // ── % across lines ───────────────────────────────────────────────────────

    #[test]
    fn percent_matches_across_lines() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo (bar", "baz) qux"]);
        e.handle_key(&key('f'), &mut t);
        e.handle_key(&key('('), &mut t); // on '(' (0,4)
        e.handle_key(&key('%'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (1, 3)); // ')' on line 2
        e.handle_key(&key('%'), &mut t); // and back
        assert_eq!(super::super::cursor_tuple(&t), (0, 4));
    }

    #[test]
    fn percent_nested_across_lines() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["{a {b", "c}", "d}"]);
        e.handle_key(&key('%'), &mut t); // outer '{' at (0,0)
        assert_eq!(super::super::cursor_tuple(&t), (2, 1)); // outer '}' line 3
    }

    #[test]
    fn d_percent_deletes_across_lines_inclusive() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["a(b", "c)d"]);
        e.handle_key(&key('f'), &mut t);
        e.handle_key(&key('('), &mut t); // on '('
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('%'), &mut t); // delete '(' through ')' inclusive
        assert_eq!(t.lines(), &["ad"]);
    }

    #[test]
    fn percent_unmatched_across_buffer_is_noop() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["(a", "b"]);
        e.handle_key(&key('%'), &mut t); // no closing paren anywhere
        assert_eq!(super::super::cursor_tuple(&t), (0, 0));
    }

    // ── Review fixes: failed-op no-ops, dot-register protection ─────────────

    #[test]
    fn visual_c_dot_repeats_same_width() {
        // `.` after a visual change replays a same-sized change (vim), not cl
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abcde fghij"]);
        e.handle_key(&key('v'), &mut t);
        e.handle_key(&key('l'), &mut t);
        e.handle_key(&key('l'), &mut t); // select "abc"
        e.handle_key(&key('c'), &mut t); // change it
        t.insert_str("X");
        e.handle_key(&esc(), &mut t); // "Xde fghij"
        e.handle_key(&key('w'), &mut t); // onto 'f'
        e.handle_key(&key('.'), &mut t); // change 3 chars "fgh" → "X"
        assert_eq!(t.lines(), &["Xde Xij"]);
    }

    #[test]
    fn count_find_is_atomic() {
        // vim 2fx with one 'x': whole motion fails, cursor stays
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["a x b"]);
        e.handle_key(&key('2'), &mut t);
        e.handle_key(&key('f'), &mut t);
        e.handle_key(&key('x'), &mut t);
        assert_eq!(super::super::cursor_tuple(&t), (0, 0)); // did not move
        // and with two: lands on the second
        let mut t2 = TextArea::from(["axbx"]);
        e.handle_key(&key('2'), &mut t2);
        e.handle_key(&key('f'), &mut t2);
        e.handle_key(&key('x'), &mut t2);
        assert_eq!(super::super::cursor_tuple(&t2), (0, 3));
    }

    #[test]
    fn d2fx_with_one_x_is_noop() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["a x b"]);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('2'), &mut t);
        e.handle_key(&key('f'), &mut t);
        e.handle_key(&key('x'), &mut t); // only one 'x' — vim no-ops everything
        assert_eq!(t.lines(), &["a x b"]);
    }

    #[test]
    fn reset_to_normal_clears_insert_capture() {
        // regression: stale capture from interrupted cw silently disabled
        // dot-recording for every later change
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo bar"]);
        e.handle_key(&key('c'), &mut t);
        e.handle_key(&key('w'), &mut t); // Insert, capture live
        e.reset_to_normal(); // note switch mid-insert
        e.handle_key(&key('x'), &mut t); // must record (deletes ' ')
        e.handle_key(&key('.'), &mut t); // must repeat x (deletes 'b')
        assert_eq!(t.lines(), &["ar"]); // cw left " bar"; x then . removed 2 chars
    }

    #[test]
    fn dj_on_last_line_is_noop() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["only line"]);
        e.handle_key(&key('y'), &mut t);
        e.handle_key(&key('y'), &mut t); // register = line
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('j'), &mut t); // motion fails → whole op no-op
        assert_eq!(t.lines(), &["only line"]);
        assert_eq!(e.registers.read().unwrap().text, "only line\n"); // register kept
    }

    #[test]
    fn dk_on_first_line_is_noop() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two"]);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('k'), &mut t);
        assert_eq!(t.lines(), &["one", "two"]);
    }

    #[test]
    fn failed_find_op_does_not_clobber_dot() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abcdef"]);
        e.handle_key(&key('x'), &mut t); // real change: delete 'a'
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('f'), &mut t);
        e.handle_key(&key('z'), &mut t); // failed find — must not record
        e.handle_key(&key('.'), &mut t); // repeats x, not the failed dfz
        assert_eq!(t.lines(), &["cdef"]);
    }

    #[test]
    fn noop_x_does_not_clobber_dot() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one two three", ""]);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('w'), &mut t); // delete "one "
        e.handle_key(&key('j'), &mut t); // empty line
        let out = e.handle_key(&key('x'), &mut t); // no-op
        assert_eq!(out, VimKeyOutcome::NoOp); // host must not bump content
        e.handle_key(&key('k'), &mut t);
        e.handle_key(&key('.'), &mut t); // repeats dw, not the no-op x
        assert_eq!(t.lines(), &["three", ""]);
    }

    #[test]
    fn d_percent_without_pair_is_noop() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abc"]);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('%'), &mut t); // no bracket under cursor
        assert_eq!(t.lines(), &["abc"]);
        e.handle_key(&key('c'), &mut t);
        e.handle_key(&key('%'), &mut t);
        assert_eq!(*e.mode(), EditorMode::Normal); // failed c% must not enter Insert
    }

    #[test]
    fn visual_inner_empty_pair_is_noop() {
        // regression: vi( on "()" widened onto the ')' and deleted it
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo()bar"]);
        e.handle_key(&key('f'), &mut t);
        e.handle_key(&key('('), &mut t); // cursor on '('
        e.handle_key(&key('v'), &mut t);
        e.handle_key(&key('i'), &mut t);
        e.handle_key(&key('('), &mut t); // empty object: selection unchanged
        e.handle_key(&esc(), &mut t);
        assert_eq!(t.lines(), &["foo()bar"]);
    }

    #[test]
    fn aborted_insert_keeps_dot_register() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abc"]);
        e.handle_key(&key('x'), &mut t); // real change
        e.handle_key(&key('i'), &mut t); // changed mind
        e.handle_key(&esc(), &mut t); // nothing typed — not a change
        e.handle_key(&key('.'), &mut t); // must repeat x
        assert_eq!(t.lines(), &["c"]);
    }

    #[test]
    fn o_then_esc_is_still_dot_repeatable() {
        // vim: o<Esc> IS a change (the opened line); `.` opens another
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["x"]);
        e.handle_key(&key('o'), &mut t);
        e.handle_key(&esc(), &mut t);
        e.handle_key(&key('.'), &mut t);
        assert_eq!(t.lines().len(), 3);
    }

    // ── Visual mode: shared motion/object machinery ──────────────────────────

    #[test]
    fn visual_inner_object_then_delete() {
        // vi( selects inside the parens; d deletes it
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["foo(bar)baz"]);
        e.handle_key(&key('f'), &mut t);
        e.handle_key(&key('a'), &mut t); // cursor on 'a' of "bar" (col 5)
        e.handle_key(&key('v'), &mut t);
        e.handle_key(&key('i'), &mut t);
        e.handle_key(&key('('), &mut t); // select "bar"
        e.handle_key(&key('d'), &mut t);
        assert_eq!(t.lines(), &["foo()baz"]);
    }

    #[test]
    fn visual_around_quote_then_yank() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["say \"hi\" now"]);
        e.handle_key(&key('f'), &mut t);
        e.handle_key(&key('h'), &mut t); // inside quotes
        e.handle_key(&key('v'), &mut t);
        e.handle_key(&key('a'), &mut t);
        e.handle_key(&key('"'), &mut t); // select "\"hi\""
        e.handle_key(&key('y'), &mut t);
        let reg = e.registers.read().unwrap();
        assert_eq!(reg.text, "\"hi\"");
    }

    #[test]
    fn visual_find_extends_selection() {
        // vf, then d deletes through the ','
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["hello, world"]);
        e.handle_key(&key('v'), &mut t);
        e.handle_key(&key('f'), &mut t);
        e.handle_key(&key(','), &mut t); // cursor on ',' — selection covers "hello,"
        e.handle_key(&key('d'), &mut t);
        assert_eq!(t.lines(), &[" world"]);
    }

    #[test]
    fn visual_gg_extends_to_file_start() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two", "three"]);
        e.handle_key(&key('j'), &mut t);
        e.handle_key(&key('j'), &mut t); // row 2
        e.handle_key(&key('v'), &mut t);
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('g'), &mut t); // extend to (0,0)
        e.handle_key(&key('d'), &mut t); // delete from 't' of "three" back to start
        assert_eq!(t.lines(), &["hree"]);
    }

    #[test]
    fn visual_o_swaps_selection_ends() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abcde"]);
        e.handle_key(&key('l'), &mut t);
        e.handle_key(&key('l'), &mut t); // col 2 ('c')
        e.handle_key(&key('v'), &mut t);
        e.handle_key(&key('l'), &mut t); // select c..d, cursor at 'd' (col 3)
        e.handle_key(&key('o'), &mut t); // cursor swaps to 'c' (col 2)
        assert_eq!(super::super::cursor_tuple(&t), (0, 2));
        e.handle_key(&key('h'), &mut t); // extend left from the anchor end
        e.handle_key(&key('d'), &mut t); // delete b..d inclusive
        assert_eq!(t.lines(), &["ae"]);
    }

    // ── Command spine: dot-repeat through the one apply() door ───────────────

    #[test]
    fn dot_repeats_cc_with_typed_text() {
        // previously a silent no-op (replay's `_other` arm)
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two"]);
        e.handle_key(&key('c'), &mut t);
        e.handle_key(&key('c'), &mut t); // cc on "one"
        t.insert_str("X");
        e.handle_key(&esc(), &mut t); // line 0 = "X"
        e.handle_key(&key('j'), &mut t); // onto "two"
        e.handle_key(&key('.'), &mut t); // repeat cc+X
        assert_eq!(t.lines(), &["X", "X"]);
    }

    #[test]
    fn dot_repeats_substitute_char() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["ab cd"]);
        e.handle_key(&key('s'), &mut t); // delete 'a', Insert
        t.insert_str("Z");
        e.handle_key(&esc(), &mut t); // "Zb cd"
        e.handle_key(&key('w'), &mut t); // onto 'c'
        e.handle_key(&key('.'), &mut t); // repeat s+Z on 'c'
        assert_eq!(t.lines(), &["Zb Zd"]);
    }

    #[test]
    fn dot_repeats_plain_insert() {
        // vim: `ihello<Esc>` then `.` inserts "hello" again
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["world"]);
        e.handle_key(&key('i'), &mut t);
        t.insert_str("ab");
        e.handle_key(&esc(), &mut t); // "abworld", cursor on 'b'
        e.handle_key(&key('.'), &mut t); // insert "ab" again before 'b'
        assert_eq!(t.lines(), &["aabbworld"]);
    }

    #[test]
    fn dot_repeats_indent() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["x"]);
        e.handle_key(&key('>'), &mut t);
        e.handle_key(&key('>'), &mut t); // indent
        e.handle_key(&key('.'), &mut t); // repeat
        assert_eq!(t.lines(), &["        x"]);
    }

    #[test]
    fn dot_does_not_repeat_yank() {
        // vim: `.` repeats the last CHANGE; a yank after it must not displace it
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abc"]);
        e.handle_key(&key('x'), &mut t); // delete 'a' (the change)
        e.handle_key(&key('y'), &mut t);
        e.handle_key(&key('l'), &mut t); // yank 'b' — not a change
        e.handle_key(&key('.'), &mut t); // must repeat x, not the yank
        assert_eq!(t.lines(), &["c"]);
    }

    // ── Range model: motion SpanKind classification + count composition ─────

    #[test]
    fn counts_before_and_after_operator_multiply() {
        // vim: 2d3w = 6 words, not count "23"
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["a b c d e f g"]);
        e.handle_key(&key('2'), &mut t);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('3'), &mut t);
        e.handle_key(&key('w'), &mut t);
        assert_eq!(t.lines(), &["g"]); // six words deleted
    }

    #[test]
    fn dj_deletes_two_whole_lines_linewise() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two", "three"]);
        e.handle_key(&key('l'), &mut t); // col 1 — must not matter (linewise)
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('j'), &mut t);
        assert_eq!(t.lines(), &["three"]);
        let reg = e.registers.read().unwrap();
        assert_eq!(reg.kind, RegisterKind::Linewise);
        assert_eq!(reg.text, "one\ntwo\n");
    }

    #[test]
    fn dk_deletes_two_whole_lines_upward() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two", "three"]);
        e.handle_key(&key('j'), &mut t); // row 1
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('k'), &mut t);
        assert_eq!(t.lines(), &["three"]);
    }

    #[test]
    #[allow(non_snake_case)]
    fn dG_deletes_to_file_end_linewise() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two", "three"]);
        e.handle_key(&key('j'), &mut t); // row 1
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('G'), &mut t);
        assert_eq!(t.lines(), &["one"]);
    }

    #[test]
    fn d_gg_deletes_to_file_start_linewise() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two", "three"]);
        e.handle_key(&key('j'), &mut t); // row 1
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('g'), &mut t);
        e.handle_key(&key('g'), &mut t);
        assert_eq!(t.lines(), &["three"]);
    }

    #[test]
    fn dt_deletes_up_to_but_not_including_target() {
        // vim t is inclusive of the char BEFORE the target: dtx on "abx" → "x"
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abx"]);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('t'), &mut t);
        e.handle_key(&key('x'), &mut t);
        assert_eq!(t.lines(), &["x"]);
    }

    #[test]
    fn failed_find_with_operator_is_noop() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["hello"]);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('f'), &mut t);
        e.handle_key(&key('z'), &mut t); // no 'z' on the line
        assert_eq!(t.lines(), &["hello"]); // nothing deleted
        e.handle_key(&key('c'), &mut t);
        e.handle_key(&key('f'), &mut t);
        e.handle_key(&key('z'), &mut t);
        assert_eq!(*e.mode(), EditorMode::Normal); // failed cf must not enter Insert
    }

    #[test]
    fn d_semicolon_repeats_find_as_operator_range() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["a.b.c"]);
        e.handle_key(&key('f'), &mut t);
        e.handle_key(&key('.'), &mut t); // cursor on first '.' (col 1)
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key(';'), &mut t); // delete through next '.' (inclusive)
        assert_eq!(t.lines(), &["ac"]);
    }

    #[test]
    fn cj_changes_two_lines_and_enters_insert() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two", "three"]);
        e.handle_key(&key('c'), &mut t);
        e.handle_key(&key('j'), &mut t);
        assert_eq!(*e.mode(), EditorMode::Insert);
        assert_eq!(t.lines(), &["", "three"]); // both lines gone, fresh empty line
    }

    // ── Register file: engine-owned unnamed register ────────────────────────

    #[test]
    fn x_then_p_swaps_chars() {
        // the classic vim `xp` idiom: x fills the register with the deleted char
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["ab"]);
        e.handle_key(&key('x'), &mut t); // delete 'a' → register "a"; line "b"
        e.handle_key(&key('p'), &mut t); // paste "a" after 'b'
        assert_eq!(t.lines(), &["ba"]);
    }

    #[test]
    fn x_at_line_end_does_not_join_next_line() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["ab", "cd"]);
        e.handle_key(&key('l'), &mut t); // onto 'b' (last char)
        e.handle_key(&key('3'), &mut t);
        e.handle_key(&key('x'), &mut t); // vim: deletes only 'b', never the newline
        assert_eq!(t.lines(), &["a", "cd"]);
    }

    #[test]
    fn s_fills_register_with_deleted_char() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["abc"]);
        e.handle_key(&key('s'), &mut t); // delete 'a', enter Insert
        assert_eq!(*e.mode(), EditorMode::Insert);
        let reg = e.registers.read().expect("s must fill the register");
        assert_eq!(reg.text, "a");
        assert_eq!(reg.kind, RegisterKind::Charwise);
    }

    #[test]
    #[allow(non_snake_case)]
    fn S_fills_register_linewise_no_kind_desync() {
        // regression: S used to cut() (charwise content) while the engine kept
        // a stale Linewise kind from a prior yy — kind and content desynced.
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one", "two"]);
        e.handle_key(&key('y'), &mut t);
        e.handle_key(&key('y'), &mut t); // register = "one\n" linewise
        e.handle_key(&key('j'), &mut t);
        e.handle_key(&key('S'), &mut t); // substitute line "two"
        let reg = e.registers.read().expect("S must fill the register");
        assert_eq!(reg.text, "two\n");
        assert_eq!(reg.kind, RegisterKind::Linewise);
    }

    #[test]
    fn dw_fills_register_charwise() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["one two"]);
        e.handle_key(&key('d'), &mut t);
        e.handle_key(&key('w'), &mut t); // delete "one "
        let reg = e.registers.read().expect("dw must fill the register");
        assert_eq!(reg.text, "one ");
        assert_eq!(reg.kind, RegisterKind::Charwise);
        // and p pastes it back charwise
        e.handle_key(&key('p'), &mut t);
        assert_eq!(t.lines(), &["tone wo"]); // "one " pasted after 't'
    }

    #[test]
    fn empty_delete_keeps_previous_register() {
        let mut e = VimEngine::default();
        let mut t = TextArea::from(["ab", ""]);
        e.handle_key(&key('y'), &mut t);
        e.handle_key(&key('l'), &mut t); // yank "a" charwise
        e.handle_key(&key('j'), &mut t); // empty line
        e.handle_key(&key('x'), &mut t); // no-op delete (empty line)
        let reg = e
            .registers
            .read()
            .expect("register must survive a no-op delete");
        assert_eq!(reg.text, "a");
    }

    #[test]
    fn esc_in_normal_clears_stray_selection() {
        let mut e = VimEngine::default(); // Normal mode
        let mut t = TextArea::from(["hello world"]);
        // simulate a live selection while in Normal mode (as auto-surround/mouse-sync can leave)
        t.start_selection();
        t.move_cursor(ratatui_textarea::CursorMove::Forward);
        t.move_cursor(ratatui_textarea::CursorMove::Forward);
        assert!(t.selection_range().is_some());
        let out = e.handle_key(&esc(), &mut t);
        assert!(
            t.selection_range().is_none(),
            "Esc in Normal must cancel a stray selection"
        );
        assert_eq!(out, VimKeyOutcome::CursorOnly);
        assert_eq!(*e.mode(), EditorMode::Normal);
    }
}