hjkl-engine 0.7.0

Vim FSM, motion grammar, and ex commands. Pre-1.0 churn.
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
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
//! Vim-mode engine.
//!
//! Implements a command grammar of the form
//!
//! ```text
//! Command := count? (operator count? (motion | text-object)
//!                   | motion
//!                   | insert-entry
//!                   | misc)
//! ```
//!
//! The parser is a small state machine driven by one `Input` at a time.
//! Motions and text objects produce a [`Range`] (with inclusive/exclusive
//! / linewise classification). A single [`Operator`] implementation
//! applies a range — so `dw`, `d$`, `daw`, and visual `d` all go through
//! the same code path.
//!
//! The most recent mutating command is stored in
//! [`VimState::last_change`] so `.` can replay it.
//!
//! # Roadmap
//!
//! Tracked in the original plan at
//! `~/.claude/plans/look-at-the-vim-curried-fern.md`. Phases still
//! outstanding — each one can land as an isolated PR.
//!
//! ## P3 — Registers & marks
//!
//! - TODO: `RegisterBank` indexed by char:
//!     - unnamed `""`, last-yank `"0`, small-delete `"-`
//!     - named `"a-"z` (uppercase `"A-"Z` appends instead of overwriting)
//!     - blackhole `"_`
//!     - system clipboard `"+` / `"*` (wire to `crate::clipboard::Clipboard`)
//!     - read-only `":`, `".`, `"%` — surface in `:reg` output
//! - TODO: route every yank / cut / paste through the bank. Parser needs
//!   a `"{reg}` prefix state that captures the target register before a
//!   count / operator.
//! - TODO: `m{a-z}` sets a mark in a `HashMap<char, (buffer_id, row, col)>`;
//!   `'x` jumps to the line (FirstNonBlank), `` `x `` to the exact cell.
//!   Uppercase marks are global across tabs; lowercase are per-buffer.
//! - TODO: `''` and `` `` `` jump to the last-jump position; `'[` `']`
//!   `'<` `'>` bound the last change / visual region.
//! - TODO: `:reg` and `:marks` ex commands.
//!
//! ## P4 — Macros
//!
//! - TODO: `q{a-z}` starts recording raw `Input`s into the register;
//!   next `q` stops.
//! - TODO: `@{a-z}` replays the register by re-feeding inputs through
//!   `step`. `@@` repeats the last macro. Nested macros need a sane
//!   depth cap (e.g. 100) to avoid runaway loops.
//! - TODO: ensure recording doesn't capture the initial `q{a-z}` itself.
//!
//! ## P6 — Polish (still outstanding)
//!
//! - TODO: indent operators `>` / `<` (with line + text-object targets).
//! - TODO: format operator `=` — map to whatever SQL formatter we wire
//!   up; for now stub that returns the range unchanged with a toast.
//! - TODO: case operators `gU` / `gu` / `g~` on a range (already have
//!   single-char `~`).
//! - TODO: screen motions `H` / `M` / `L` once we track the render
//!   viewport height inside Editor.
//! - TODO: scroll-to-cursor motions `zz` / `zt` / `zb`.
//!
//! ## Known substrate / divergence notes
//!
//! - TODO: insert-mode indent helpers — `Ctrl-t` / `Ctrl-d` (increase /
//!   decrease indent on current line) and `Ctrl-r <reg>` (paste from a
//!   register). `Ctrl-r` needs the `RegisterBank` from P3 to be useful.
//! - TODO: `/` and `?` search prompts still live in `the host/src/lib.rs`.
//!   The plan calls for moving them into the editor (so the editor owns
//!   `last_search_pattern` rather than the TUI loop). Safe to defer.

use crate::VimMode;
use crate::input::{Input, Key};

use crate::buf_helpers::{
    buf_cursor_pos, buf_line, buf_line_bytes, buf_line_chars, buf_lines_to_vec, buf_row_count,
    buf_set_cursor_pos, buf_set_cursor_rc,
};
use crate::editor::Editor;

// ─── Modes & parser state ───────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Mode {
    #[default]
    Normal,
    Insert,
    Visual,
    VisualLine,
    /// Column-oriented selection (`Ctrl-V`). Unlike the other visual
    /// modes this one doesn't use tui-textarea's single-range selection
    /// — the block corners live in [`VimState::block_anchor`] and the
    /// live cursor. Operators read the rectangle off those two points.
    VisualBlock,
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum Pending {
    #[default]
    None,
    /// Operator seen; still waiting for a motion / text-object / double-op.
    /// `count1` is any count pressed before the operator.
    Op { op: Operator, count1: usize },
    /// Operator + 'i' or 'a' seen; waiting for the text-object character.
    OpTextObj {
        op: Operator,
        count1: usize,
        inner: bool,
    },
    /// Operator + 'g' seen (for `dgg`).
    OpG { op: Operator, count1: usize },
    /// Bare `g` seen in normal/visual — looking for `g`, `e`, `E`, …
    G,
    /// Bare `f`/`F`/`t`/`T` — looking for the target char.
    Find { forward: bool, till: bool },
    /// Operator + `f`/`F`/`t`/`T` — looking for target char.
    OpFind {
        op: Operator,
        count1: usize,
        forward: bool,
        till: bool,
    },
    /// `r` pressed — waiting for the replacement char.
    Replace,
    /// Visual mode + `i` or `a` pressed — waiting for the text-object
    /// character to extend the selection over.
    VisualTextObj { inner: bool },
    /// Bare `z` seen — looking for `z` (center), `t` (top), `b` (bottom).
    Z,
    /// `m` pressed — waiting for the mark letter to set.
    SetMark,
    /// `'` pressed — waiting for the mark letter to jump to its line
    /// (lands on first non-blank, linewise for operators).
    GotoMarkLine,
    /// `` ` `` pressed — waiting for the mark letter to jump to the
    /// exact `(row, col)` stored at set time (charwise for operators).
    GotoMarkChar,
    /// `"` pressed — waiting for the register selector. The next char
    /// (`a`–`z`, `A`–`Z`, `0`–`9`, or `"`) sets `pending_register`.
    SelectRegister,
    /// `q` pressed (not currently recording) — waiting for the macro
    /// register name. The macro records every key after the chord
    /// resolves, until a bare `q` ends the recording.
    RecordMacroTarget,
    /// `@` pressed — waiting for the macro register name to play.
    /// `count` is the prefix multiplier (`3@a` plays the macro 3
    /// times); 0 means "no prefix" and is treated as 1.
    PlayMacroTarget { count: usize },
}

// ─── Operator / Motion / TextObject ────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Operator {
    Delete,
    Change,
    Yank,
    /// `gU{motion}` — uppercase the range. Entered via the `g` prefix
    /// in normal mode or `U` in visual mode.
    Uppercase,
    /// `gu{motion}` — lowercase the range. `u` in visual mode.
    Lowercase,
    /// `g~{motion}` — toggle case of the range. `~` in visual mode
    /// (character at the cursor for the single-char `~` command stays
    /// its own code path in normal mode).
    ToggleCase,
    /// `>{motion}` — indent the line range by `shiftwidth` spaces.
    /// Always linewise, even when the motion is char-wise — mirrors
    /// vim's behaviour where `>w` indents the current line, not the
    /// word on it.
    Indent,
    /// `<{motion}` — outdent the line range (remove up to
    /// `shiftwidth` leading spaces per line).
    Outdent,
    /// `zf{motion}` / `zf{textobj}` / Visual `zf` — create a closed
    /// fold spanning the row range. Doesn't mutate the buffer text;
    /// cursor restores to the operator's start position.
    Fold,
    /// `gq{motion}` — reflow the row range to `settings.textwidth`.
    /// Greedy word-wrap: collapses each paragraph (blank-line-bounded
    /// run) into space-separated words, then re-emits lines whose
    /// width stays under `textwidth`. Always linewise, like indent.
    Reflow,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Motion {
    Left,
    Right,
    Up,
    Down,
    WordFwd,
    BigWordFwd,
    WordBack,
    BigWordBack,
    WordEnd,
    BigWordEnd,
    /// `ge` — backward word end.
    WordEndBack,
    /// `gE` — backward WORD end.
    BigWordEndBack,
    LineStart,
    FirstNonBlank,
    LineEnd,
    FileTop,
    FileBottom,
    Find {
        ch: char,
        forward: bool,
        till: bool,
    },
    FindRepeat {
        reverse: bool,
    },
    MatchBracket,
    WordAtCursor {
        forward: bool,
        /// `*` / `#` use `\bword\b` boundaries; `g*` / `g#` drop them so
        /// the search hits substrings (e.g. `foo` matches inside `foobar`).
        whole_word: bool,
    },
    /// `n` / `N` — repeat the last `/` or `?` search.
    SearchNext {
        reverse: bool,
    },
    /// `H` — cursor to viewport top (plus `count - 1` rows down).
    ViewportTop,
    /// `M` — cursor to viewport middle.
    ViewportMiddle,
    /// `L` — cursor to viewport bottom (minus `count - 1` rows up).
    ViewportBottom,
    /// `g_` — last non-blank char on the line.
    LastNonBlank,
    /// `gM` — cursor to the middle char column of the current line
    /// (`floor(chars / 2)`). Vim's variant ignoring screen wrap.
    LineMiddle,
    /// `{` — previous paragraph (preceding blank line, or top).
    ParagraphPrev,
    /// `}` — next paragraph (following blank line, or bottom).
    ParagraphNext,
    /// `(` — previous sentence boundary.
    SentencePrev,
    /// `)` — next sentence boundary.
    SentenceNext,
    /// `gj` — `count` visual rows down (one screen segment per step
    /// under `:set wrap`; falls back to `Down` otherwise).
    ScreenDown,
    /// `gk` — `count` visual rows up; mirror of [`Motion::ScreenDown`].
    ScreenUp,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextObject {
    Word {
        big: bool,
    },
    Quote(char),
    Bracket(char),
    Paragraph,
    /// `it` / `at` — XML/HTML-style tag pair. `inner = true` covers
    /// content between `>` and `</`; `inner = false` covers the open
    /// tag through the close tag inclusive.
    XmlTag,
    /// `is` / `as` — sentence: a run ending at `.`, `?`, or `!`
    /// followed by whitespace or end-of-line. `inner = true` covers
    /// the sentence text only; `inner = false` includes trailing
    /// whitespace.
    Sentence,
}

/// Classification determines how operators treat the range end.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RangeKind {
    /// Range end is exclusive (end column not included). Typical: h, l, w, 0, $.
    Exclusive,
    /// Range end is inclusive. Typical: e, f, t, %.
    Inclusive,
    /// Whole lines from top row to bottom row. Typical: j, k, gg, G.
    Linewise,
}

// ─── Dot-repeat storage ────────────────────────────────────────────────────

/// Information needed to replay a mutating change via `.`.
#[derive(Debug, Clone)]
pub enum LastChange {
    /// Operator over a motion.
    OpMotion {
        op: Operator,
        motion: Motion,
        count: usize,
        inserted: Option<String>,
    },
    /// Operator over a text-object.
    OpTextObj {
        op: Operator,
        obj: TextObject,
        inner: bool,
        inserted: Option<String>,
    },
    /// `dd`, `cc`, `yy` with a count.
    LineOp {
        op: Operator,
        count: usize,
        inserted: Option<String>,
    },
    /// `x`, `X` with a count.
    CharDel { forward: bool, count: usize },
    /// `r<ch>` with a count.
    ReplaceChar { ch: char, count: usize },
    /// `~` with a count.
    ToggleCase { count: usize },
    /// `J` with a count.
    JoinLine { count: usize },
    /// `p` / `P` with a count.
    Paste { before: bool, count: usize },
    /// `D` (delete to EOL).
    DeleteToEol { inserted: Option<String> },
    /// `o` / `O` + the inserted text.
    OpenLine { above: bool, inserted: String },
    /// `i`/`I`/`a`/`A` + inserted text.
    InsertAt {
        entry: InsertEntry,
        inserted: String,
        count: usize,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InsertEntry {
    I,
    A,
    ShiftI,
    ShiftA,
}

// ─── VimState ──────────────────────────────────────────────────────────────

#[derive(Default)]
pub struct VimState {
    /// Internal FSM mode. Kept in sync with `current_mode` after every
    /// `step`. Phase 6.6b: promoted from private to `pub` so the FSM
    /// body (moving to hjkl-vim in 6.6c–6.6g) can read/write it directly
    /// until the migration is complete.
    pub mode: Mode,
    /// Two-key chord in progress. `Pending::None` when idle.
    pub pending: Pending,
    /// Digit prefix accumulated before an operator or motion. `0` means
    /// no prefix was typed (treated as 1 by most commands).
    pub count: usize,
    /// Last `f`/`F`/`t`/`T` target, for `;` / `,` repeat.
    pub last_find: Option<(char, bool, bool)>,
    /// Most-recent mutating command for `.` dot-repeat.
    pub last_change: Option<LastChange>,
    /// Captured on insert-mode entry: count, buffer snapshot, entry kind.
    pub insert_session: Option<InsertSession>,
    /// (row, col) anchor for char-wise Visual mode. Set on entry, used
    /// to compute the highlight range and the operator range without
    /// relying on tui-textarea's live selection.
    pub visual_anchor: (usize, usize),
    /// Row anchor for VisualLine mode.
    pub visual_line_anchor: usize,
    /// (row, col) anchor for VisualBlock mode. The live cursor is the
    /// opposite corner.
    pub block_anchor: (usize, usize),
    /// Intended "virtual" column for the block's active corner. j/k
    /// clamp cursor.col to shorter rows, which would collapse the
    /// block across ragged content — so we remember the desired column
    /// separately and use it for block bounds / insert-column
    /// computations. Updated by h/l only.
    pub block_vcol: usize,
    /// Track whether the last yank/cut was linewise (drives `p`/`P` layout).
    pub yank_linewise: bool,
    /// Active register selector — set by `"reg` prefix, consumed by
    /// the next y / d / c / p. `None` falls back to the unnamed `"`.
    pub pending_register: Option<char>,
    /// Recording target — set by `q{reg}`, cleared by a bare `q`.
    /// While `Some`, every consumed `Input` is appended to
    /// `recording_keys`.
    pub recording_macro: Option<char>,
    /// Keys recorded into the in-progress macro. On `q` finish, these
    /// are encoded via [`crate::input::encode_macro`] and written to
    /// the matching named register slot, so macros and yanks share a
    /// single store.
    pub recording_keys: Vec<crate::input::Input>,
    /// Set during `@reg` replay so the recorder doesn't capture the
    /// replayed keystrokes a second time.
    pub replaying_macro: bool,
    /// Last register played via `@reg`. `@@` re-plays this one.
    pub last_macro: Option<char>,
    /// Position of the most recent buffer mutation. Surfaced via
    /// the `'.` / `` `. `` marks for quick "back to last edit".
    pub last_edit_pos: Option<(usize, usize)>,
    /// Position where the cursor was when insert mode last exited (Esc).
    /// Used by `gi` to return to the exact (row, col) where the user
    /// last typed, matching vim's `:h gi`.
    pub last_insert_pos: Option<(usize, usize)>,
    /// Bounded ring of recent edit positions (newest at the back).
    /// `g;` walks toward older entries, `g,` toward newer ones. Capped
    /// at [`CHANGE_LIST_MAX`].
    pub change_list: Vec<(usize, usize)>,
    /// Index into `change_list` while walking. `None` outside a walk —
    /// any new edit clears it (and trims forward entries past it).
    pub change_list_cursor: Option<usize>,
    /// Snapshot of the last visual selection for `gv` re-entry.
    /// Stored on every Visual / VisualLine / VisualBlock exit.
    pub last_visual: Option<LastVisual>,
    /// `zz` / `zt` / `zb` set this so the end-of-step scrolloff
    /// pass doesn't override the user's explicit viewport pinning.
    /// Cleared every step.
    pub viewport_pinned: bool,
    /// Set while replaying `.` / last-change so we don't re-record it.
    pub replaying: bool,
    /// Entered Normal from Insert via `Ctrl-o`; after the next complete
    /// normal-mode command we return to Insert.
    pub one_shot_normal: bool,
    /// Live `/` or `?` prompt. `None` outside search-prompt mode.
    pub search_prompt: Option<SearchPrompt>,
    /// Most recent committed search pattern. Surfaced to host apps via
    /// [`Editor::last_search`] so their status line can render a hint
    /// and so `n` / `N` have something to repeat.
    pub last_search: Option<String>,
    /// Direction of the last committed search. `n` repeats this; `N`
    /// inverts it. Defaults to forward so a never-searched buffer's
    /// `n` still walks downward.
    pub last_search_forward: bool,
    /// Back half of the jumplist — `Ctrl-o` pops from here. Populated
    /// with the pre-motion cursor when a "big jump" motion fires
    /// (`gg`/`G`, `%`, `*`/`#`, `n`/`N`, `H`/`M`/`L`, committed `/` or
    /// `?`). Capped at 100 entries.
    pub jump_back: Vec<(usize, usize)>,
    /// Forward half — `Ctrl-i` pops from here. Cleared by any new big
    /// jump, matching vim's "branch off trims forward history" rule.
    pub jump_fwd: Vec<(usize, usize)>,
    /// Set by `Ctrl-R` in insert mode while waiting for the register
    /// selector. The next typed char names the register; its contents
    /// are inserted inline at the cursor and the flag clears.
    pub insert_pending_register: bool,
    /// Stashed start position for the `[` mark on a Change operation.
    /// Set to `top` before the cut in `run_operator_over_range` (Change
    /// arm); consumed by `finish_insert_session` on Esc-from-insert
    /// when the reason is `AfterChange`. Mirrors vim's `:h '[` / `:h ']`
    /// rule that `[` = start of change, `]` = last typed char on exit.
    pub change_mark_start: Option<(usize, usize)>,
    /// Bounded history of committed `/` / `?` search patterns. Newest
    /// entries are at the back; capped at [`SEARCH_HISTORY_MAX`] to
    /// avoid unbounded growth on long sessions.
    pub search_history: Vec<String>,
    /// Index into `search_history` while the user walks past patterns
    /// in the prompt via `Ctrl-P` / `Ctrl-N`. `None` outside that walk
    /// — typing or backspacing in the prompt resets it so the next
    /// `Ctrl-P` starts from the most recent entry again.
    pub search_history_cursor: Option<usize>,
    /// Wall-clock instant of the last keystroke. Drives the
    /// `:set timeoutlen` multi-key timeout — if `now() - last_input_at`
    /// exceeds the configured budget, any pending prefix is cleared
    /// before the new key dispatches. `None` before the first key.
    /// 0.0.29 (Patch B): `:set timeoutlen` math now reads
    /// [`crate::types::Host::now`] via `last_input_host_at`. This
    /// `Instant`-flavoured field stays for snapshot tests that still
    /// observe it directly.
    pub last_input_at: Option<std::time::Instant>,
    /// `Host::now()` reading at the last keystroke. Drives
    /// `:set timeoutlen` so macro replay / headless drivers stay
    /// deterministic regardless of wall-clock skew.
    pub last_input_host_at: Option<core::time::Duration>,
    /// Canonical current mode. Mirrors `mode` (the FSM-internal field)
    /// AND is written by every Phase 6.3 primitive (`set_mode`,
    /// `enter_visual_char_bridge`, …). Once the FSM is gone this is the
    /// sole source of truth; until then both fields are kept in sync.
    /// Initialized to `Normal` via `#[derive(Default)]`.
    pub(crate) current_mode: crate::VimMode,
}

pub(crate) const SEARCH_HISTORY_MAX: usize = 100;
pub(crate) const CHANGE_LIST_MAX: usize = 100;

/// Active `/` or `?` search prompt. Text mutations drive the textarea's
/// live search pattern so matches highlight as the user types.
#[derive(Debug, Clone)]
pub struct SearchPrompt {
    pub text: String,
    pub cursor: usize,
    pub forward: bool,
}

#[derive(Debug, Clone)]
pub struct InsertSession {
    pub count: usize,
    /// Min/max row visited during this session. Widens on every key.
    pub row_min: usize,
    pub row_max: usize,
    /// Snapshot of the full buffer at session entry. Used to diff the
    /// affected row window at finish without being fooled by cursor
    /// navigation through rows the user never edited.
    pub before_lines: Vec<String>,
    pub reason: InsertReason,
}

#[derive(Debug, Clone)]
pub enum InsertReason {
    /// Plain entry via i/I/a/A — recorded as `InsertAt`.
    Enter(InsertEntry),
    /// Entry via `o`/`O` — records OpenLine on Esc.
    Open { above: bool },
    /// Entry via an operator's change side-effect. Retro-fills the
    /// stored last-change's `inserted` field on Esc.
    AfterChange,
    /// Entry via `C` (delete to EOL + insert).
    DeleteToEol,
    /// Entry via an insert triggered during dot-replay — don't touch
    /// last_change because the outer replay will restore it.
    ReplayOnly,
    /// `I` or `A` from VisualBlock: insert the typed text at `col` on
    /// every row in `top..=bot`. `col` is the start column for `I`, the
    /// one-past-block-end column for `A`.
    BlockEdge { top: usize, bot: usize, col: usize },
    /// `c` from VisualBlock: block content deleted, then user types
    /// replacement text replicated across all block rows on Esc. Cursor
    /// advances to the last typed char after replication (unlike BlockEdge
    /// which leaves cursor at the insertion column).
    BlockChange { top: usize, bot: usize, col: usize },
    /// `R` — Replace mode. Each typed char overwrites the cell under
    /// the cursor instead of inserting; at end-of-line the session
    /// falls through to insert (same as vim).
    Replace,
}

/// Saved visual-mode anchor + cursor for `gv` (re-enters the last
/// visual selection). `mode` carries which visual flavour to
/// restore; `anchor` / `cursor` mean different things per flavour:
///
/// - `Visual`     — `anchor` is the char-wise visual anchor.
/// - `VisualLine` — `anchor.0` is the `visual_line_anchor` row;
///   `anchor.1` is unused.
/// - `VisualBlock`— `anchor` is `block_anchor`, `block_vcol` is the
///   sticky vcol that survives j/k clamping.
#[derive(Debug, Clone, Copy)]
pub struct LastVisual {
    pub mode: Mode,
    pub anchor: (usize, usize),
    pub cursor: (usize, usize),
    pub block_vcol: usize,
}

impl VimState {
    pub fn public_mode(&self) -> VimMode {
        match self.mode {
            Mode::Normal => VimMode::Normal,
            Mode::Insert => VimMode::Insert,
            Mode::Visual => VimMode::Visual,
            Mode::VisualLine => VimMode::VisualLine,
            Mode::VisualBlock => VimMode::VisualBlock,
        }
    }

    pub fn force_normal(&mut self) {
        self.mode = Mode::Normal;
        self.pending = Pending::None;
        self.count = 0;
        self.insert_session = None;
        // Phase 6.3: keep current_mode in sync for callers that bypass step().
        self.current_mode = crate::VimMode::Normal;
    }

    /// Reset every prefix-tracking field so the next keystroke starts
    /// a fresh sequence. Drives `:set timeoutlen` — when the user
    /// pauses past the configured budget, `hjkl_vim::dispatch_input` calls
    /// this before dispatching the new key.
    ///
    /// Resets: `pending`, `count`, `pending_register`,
    /// `insert_pending_register`. Does NOT touch `mode`,
    /// `insert_session`, marks, jump list, or visual anchors —
    /// those aren't part of the in-flight chord.
    pub(crate) fn clear_pending_prefix(&mut self) {
        self.pending = Pending::None;
        self.count = 0;
        self.pending_register = None;
        self.insert_pending_register = false;
    }

    /// Widen the active insert session's row window to include `row`. Called
    /// by the Phase 6.1 public `Editor::insert_*` methods after each
    /// mutation so `finish_insert_session` diffs the right range on Esc.
    /// No-op when no insert session is active (e.g. calling from Normal mode).
    pub(crate) fn widen_insert_row(&mut self, row: usize) {
        if let Some(ref mut session) = self.insert_session {
            session.row_min = session.row_min.min(row);
            session.row_max = session.row_max.max(row);
        }
    }

    pub fn is_visual(&self) -> bool {
        matches!(
            self.mode,
            Mode::Visual | Mode::VisualLine | Mode::VisualBlock
        )
    }

    pub fn is_visual_char(&self) -> bool {
        self.mode == Mode::Visual
    }

    pub fn enter_visual(&mut self, anchor: (usize, usize)) {
        self.visual_anchor = anchor;
        self.mode = Mode::Visual;
    }

    /// The pending repeat count (typed digits before a motion/operator),
    /// or `None` when no digits are pending. Zero is treated as absent.
    pub(crate) fn pending_count_val(&self) -> Option<u32> {
        if self.count == 0 {
            None
        } else {
            Some(self.count as u32)
        }
    }

    /// `true` when an in-flight chord is awaiting more keys. Inverse of
    /// `matches!(self.pending, Pending::None)`.
    pub(crate) fn is_chord_pending(&self) -> bool {
        !matches!(self.pending, Pending::None)
    }

    /// Return a single char representing the pending operator, if any.
    /// Used by host apps (status line "showcmd" area) to display e.g.
    /// `d`, `y`, `c` while waiting for a motion.
    pub(crate) fn pending_op_char(&self) -> Option<char> {
        let op = match &self.pending {
            Pending::Op { op, .. }
            | Pending::OpTextObj { op, .. }
            | Pending::OpG { op, .. }
            | Pending::OpFind { op, .. } => Some(*op),
            _ => None,
        };
        op.map(|o| match o {
            Operator::Delete => 'd',
            Operator::Change => 'c',
            Operator::Yank => 'y',
            Operator::Uppercase => 'U',
            Operator::Lowercase => 'u',
            Operator::ToggleCase => '~',
            Operator::Indent => '>',
            Operator::Outdent => '<',
            Operator::Fold => 'z',
            Operator::Reflow => 'q',
        })
    }
}

// ─── Entry point ───────────────────────────────────────────────────────────

/// Open the `/` (forward) or `?` (backward) search prompt. Clears any
/// live search highlight until the user commits a query. `last_search`
/// is preserved so an empty `<CR>` can re-run the previous pattern.
pub(crate) fn enter_search<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    forward: bool,
) {
    ed.vim.search_prompt = Some(SearchPrompt {
        text: String::new(),
        cursor: 0,
        forward,
    });
    ed.vim.search_history_cursor = None;
    // 0.0.37: clear via the engine search state (the buffer-side
    // bridge from 0.0.35 was removed in this patch — the `BufferView`
    // renderer reads the pattern from `Editor::search_state()`).
    ed.set_search_pattern(None);
}

/// `g;` / `g,` body. `dir = -1` walks toward older entries (g;),
/// `dir = 1` toward newer (g,). `count` repeats the step. Stops at
/// the ends of the ring; off-ring positions are silently ignored.
fn walk_change_list<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    dir: isize,
    count: usize,
) {
    if ed.vim.change_list.is_empty() {
        return;
    }
    let len = ed.vim.change_list.len();
    let mut idx: isize = match (ed.vim.change_list_cursor, dir) {
        (None, -1) => len as isize - 1,
        (None, 1) => return, // already past the newest entry
        (Some(i), -1) => i as isize - 1,
        (Some(i), 1) => i as isize + 1,
        _ => return,
    };
    for _ in 1..count {
        let next = idx + dir;
        if next < 0 || next >= len as isize {
            break;
        }
        idx = next;
    }
    if idx < 0 || idx >= len as isize {
        return;
    }
    let idx = idx as usize;
    ed.vim.change_list_cursor = Some(idx);
    let (row, col) = ed.vim.change_list[idx];
    ed.jump_cursor(row, col);
}

/// `Ctrl-R {reg}` body — insert the named register's contents at the
/// cursor as charwise text. Embedded newlines split lines naturally via
/// `Edit::InsertStr`. Unknown selectors and empty slots are no-ops so
/// stray keystrokes don't mutate the buffer.
fn insert_register_text<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    selector: char,
) {
    use hjkl_buffer::Edit;
    let text = match ed.registers().read(selector) {
        Some(slot) if !slot.text.is_empty() => slot.text.clone(),
        _ => return,
    };
    ed.sync_buffer_content_from_textarea();
    let cursor = buf_cursor_pos(&ed.buffer);
    ed.mutate_edit(Edit::InsertStr {
        at: cursor,
        text: text.clone(),
    });
    // Advance cursor to the end of the inserted payload — multi-line
    // pastes land on the last inserted row at the post-text column.
    let mut row = cursor.row;
    let mut col = cursor.col;
    for ch in text.chars() {
        if ch == '\n' {
            row += 1;
            col = 0;
        } else {
            col += 1;
        }
    }
    buf_set_cursor_rc(&mut ed.buffer, row, col);
    ed.push_buffer_cursor_to_textarea();
    ed.mark_content_dirty();
    if let Some(ref mut session) = ed.vim.insert_session {
        session.row_min = session.row_min.min(row);
        session.row_max = session.row_max.max(row);
    }
}

/// Compute the indent string to insert at the start of a new line
/// after Enter is pressed at `cursor`. Walks the smartindent rules:
///
/// - autoindent off → empty string
/// - autoindent on  → copy prev line's leading whitespace
/// - smartindent on → bump one `shiftwidth` if prev line's last
///   non-whitespace char is `{` / `(` / `[`
///
/// Indent unit (used for the smartindent bump):
///
/// - `expandtab && softtabstop > 0` → `softtabstop` spaces
/// - `expandtab` → `shiftwidth` spaces
/// - `!expandtab` → one literal `\t`
///
/// This is the placeholder for a future tree-sitter indent provider:
/// when a language has an `indents.scm` query, the engine will route
/// the same call through that provider and only fall back to this
/// heuristic when no query matches.
pub(super) fn compute_enter_indent(settings: &crate::editor::Settings, prev_line: &str) -> String {
    if !settings.autoindent {
        return String::new();
    }
    // Copy the prev line's leading whitespace (autoindent base).
    let base: String = prev_line
        .chars()
        .take_while(|c| *c == ' ' || *c == '\t')
        .collect();

    if settings.smartindent {
        // If the last non-whitespace character is an open bracket, bump
        // indent by one unit. This is the heuristic seam: a tree-sitter
        // `indents.scm` provider would replace this branch.
        let last_non_ws = prev_line.chars().rev().find(|c| !c.is_whitespace());
        if matches!(last_non_ws, Some('{' | '(' | '[')) {
            let unit = if settings.expandtab {
                if settings.softtabstop > 0 {
                    " ".repeat(settings.softtabstop)
                } else {
                    " ".repeat(settings.shiftwidth)
                }
            } else {
                "\t".to_string()
            };
            return format!("{base}{unit}");
        }
    }

    base
}

/// Strip one indent unit from the beginning of `line` and insert `ch`
/// instead. Returns `true` when it consumed the keystroke (dedent +
/// insert), `false` when the caller should insert normally.
///
/// Dedent fires when:
///   - `smartindent` is on
///   - `ch` is `}` / `)` / `]`
///   - all bytes BEFORE the cursor on the current line are whitespace
///   - there is at least one full indent unit of leading whitespace
fn try_dedent_close_bracket<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    cursor: hjkl_buffer::Position,
    ch: char,
) -> bool {
    use hjkl_buffer::{Edit, MotionKind, Position};

    if !ed.settings.smartindent {
        return false;
    }
    if !matches!(ch, '}' | ')' | ']') {
        return false;
    }

    let line = match buf_line(&ed.buffer, cursor.row) {
        Some(l) => l.to_string(),
        None => return false,
    };

    // All chars before cursor must be whitespace.
    let before: String = line.chars().take(cursor.col).collect();
    if !before.chars().all(|c| c == ' ' || c == '\t') {
        return false;
    }
    if before.is_empty() {
        // Nothing to strip — just insert normally (cursor at col 0).
        return false;
    }

    // Compute indent unit.
    let unit_len: usize = if ed.settings.expandtab {
        if ed.settings.softtabstop > 0 {
            ed.settings.softtabstop
        } else {
            ed.settings.shiftwidth
        }
    } else {
        // Tab: one literal tab character.
        1
    };

    // Check there's at least one full unit to strip.
    let strip_len = if ed.settings.expandtab {
        // Count leading spaces; need at least `unit_len`.
        let spaces = before.chars().filter(|c| *c == ' ').count();
        if spaces < unit_len {
            return false;
        }
        unit_len
    } else {
        // noexpandtab: strip one leading tab.
        if !before.starts_with('\t') {
            return false;
        }
        1
    };

    // Delete the leading `strip_len` chars of the current line.
    ed.mutate_edit(Edit::DeleteRange {
        start: Position::new(cursor.row, 0),
        end: Position::new(cursor.row, strip_len),
        kind: MotionKind::Char,
    });
    // Insert the close bracket at column 0 (after the delete the cursor
    // is still positioned at the end of the remaining whitespace; the
    // delete moved the text so the cursor is now at col = before.len() -
    // strip_len).
    let new_col = cursor.col.saturating_sub(strip_len);
    ed.mutate_edit(Edit::InsertChar {
        at: Position::new(cursor.row, new_col),
        ch,
    });
    true
}

fn finish_insert_session<H: crate::types::Host>(ed: &mut Editor<hjkl_buffer::Buffer, H>) {
    let Some(session) = ed.vim.insert_session.take() else {
        return;
    };
    let lines = buf_lines_to_vec(&ed.buffer);
    // Clamp both slices to their respective bounds — the buffer may have
    // grown (Enter splits rows) or shrunk (Backspace joins rows) during
    // the session, so row_max can overshoot either side.
    let after_end = session.row_max.min(lines.len().saturating_sub(1));
    let before_end = session
        .row_max
        .min(session.before_lines.len().saturating_sub(1));
    let before = if before_end >= session.row_min && session.row_min < session.before_lines.len() {
        session.before_lines[session.row_min..=before_end].join("\n")
    } else {
        String::new()
    };
    let after = if after_end >= session.row_min && session.row_min < lines.len() {
        lines[session.row_min..=after_end].join("\n")
    } else {
        String::new()
    };
    let inserted = extract_inserted(&before, &after);
    if !inserted.is_empty() && session.count > 1 && !ed.vim.replaying {
        use hjkl_buffer::{Edit, Position};
        for _ in 0..session.count - 1 {
            let (row, col) = ed.cursor();
            ed.mutate_edit(Edit::InsertStr {
                at: Position::new(row, col),
                text: inserted.clone(),
            });
        }
    }
    // Helper: replicate `inserted` text across block rows top+1..=bot at `col`,
    // padding short rows to reach `col` first. Returns without touching the
    // cursor — callers position the cursor afterward according to their needs.
    fn replicate_block_text<H: crate::types::Host>(
        ed: &mut Editor<hjkl_buffer::Buffer, H>,
        inserted: &str,
        top: usize,
        bot: usize,
        col: usize,
    ) {
        use hjkl_buffer::{Edit, Position};
        for r in (top + 1)..=bot {
            let line_len = buf_line_chars(&ed.buffer, r);
            if col > line_len {
                let pad: String = std::iter::repeat_n(' ', col - line_len).collect();
                ed.mutate_edit(Edit::InsertStr {
                    at: Position::new(r, line_len),
                    text: pad,
                });
            }
            ed.mutate_edit(Edit::InsertStr {
                at: Position::new(r, col),
                text: inserted.to_string(),
            });
        }
    }

    if let InsertReason::BlockEdge { top, bot, col } = session.reason {
        // `I` / `A` from VisualBlock: replicate text across rows; cursor
        // stays at the block-start column (vim leaves cursor there).
        if !inserted.is_empty() && top < bot && !ed.vim.replaying {
            replicate_block_text(ed, &inserted, top, bot, col);
            buf_set_cursor_rc(&mut ed.buffer, top, col);
            ed.push_buffer_cursor_to_textarea();
        }
        return;
    }
    if let InsertReason::BlockChange { top, bot, col } = session.reason {
        // `c` from VisualBlock: replicate text across rows; cursor advances
        // to `col + ins_chars` (pre-step-back) so the Esc step-back lands
        // on the last typed char (col + ins_chars - 1), matching nvim.
        if !inserted.is_empty() && top < bot && !ed.vim.replaying {
            replicate_block_text(ed, &inserted, top, bot, col);
            let ins_chars = inserted.chars().count();
            let line_len = buf_line_chars(&ed.buffer, top);
            let target_col = (col + ins_chars).min(line_len);
            buf_set_cursor_rc(&mut ed.buffer, top, target_col);
            ed.push_buffer_cursor_to_textarea();
        }
        return;
    }
    if ed.vim.replaying {
        return;
    }
    match session.reason {
        InsertReason::Enter(entry) => {
            ed.vim.last_change = Some(LastChange::InsertAt {
                entry,
                inserted,
                count: session.count,
            });
        }
        InsertReason::Open { above } => {
            ed.vim.last_change = Some(LastChange::OpenLine { above, inserted });
        }
        InsertReason::AfterChange => {
            if let Some(
                LastChange::OpMotion { inserted: ins, .. }
                | LastChange::OpTextObj { inserted: ins, .. }
                | LastChange::LineOp { inserted: ins, .. },
            ) = ed.vim.last_change.as_mut()
            {
                *ins = Some(inserted);
            }
            // Vim `:h '[` / `:h ']`: on change, `[` = start of the
            // changed range (stashed before the cut), `]` = the cursor
            // at Esc time (last inserted char, before the step-back).
            // When nothing was typed cursor still sits at the change
            // start, satisfying vim's "both at start" parity for `c<m><Esc>`.
            if let Some(start) = ed.vim.change_mark_start.take() {
                let end = ed.cursor();
                ed.set_mark('[', start);
                ed.set_mark(']', end);
            }
        }
        InsertReason::DeleteToEol => {
            ed.vim.last_change = Some(LastChange::DeleteToEol {
                inserted: Some(inserted),
            });
        }
        InsertReason::ReplayOnly => {}
        InsertReason::BlockEdge { .. } => unreachable!("handled above"),
        InsertReason::BlockChange { .. } => unreachable!("handled above"),
        InsertReason::Replace => {
            // Record overstrike sessions as DeleteToEol-style — replay
            // re-types each character but doesn't try to restore prior
            // content (vim's R has its own replay path; this is the
            // pragmatic approximation).
            ed.vim.last_change = Some(LastChange::DeleteToEol {
                inserted: Some(inserted),
            });
        }
    }
}

pub(crate) fn begin_insert<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    count: usize,
    reason: InsertReason,
) {
    let record = !matches!(reason, InsertReason::ReplayOnly);
    if record {
        ed.push_undo();
    }
    let reason = if ed.vim.replaying {
        InsertReason::ReplayOnly
    } else {
        reason
    };
    let (row, _) = ed.cursor();
    ed.vim.insert_session = Some(InsertSession {
        count,
        row_min: row,
        row_max: row,
        before_lines: buf_lines_to_vec(&ed.buffer),
        reason,
    });
    ed.vim.mode = Mode::Insert;
    // Phase 6.3: keep current_mode in sync for callers that bypass step().
    ed.vim.current_mode = crate::VimMode::Insert;
}

/// `:set undobreak` semantics for insert-mode motions. When the
/// toggle is on, a non-character keystroke that moves the cursor
/// (arrow keys, Home/End, mouse click) ends the current undo group
/// and starts a new one mid-session. After this, a subsequent `u`
/// in normal mode reverts only the post-break run, leaving the
/// pre-break edits in place — matching vim's behaviour.
///
/// Implementation: snapshot the current buffer onto the undo stack
/// (the new break point) and reset the active `InsertSession`'s
/// `before_lines` so `finish_insert_session`'s diff window only
/// captures the post-break run for `last_change` / dot-repeat.
///
/// During replay we skip the break — replay shouldn't pollute the
/// undo stack with intra-replay snapshots.
pub(crate) fn break_undo_group_in_insert<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
) {
    if !ed.settings.undo_break_on_motion {
        return;
    }
    if ed.vim.replaying {
        return;
    }
    if ed.vim.insert_session.is_none() {
        return;
    }
    ed.push_undo();
    let n = crate::types::Query::line_count(&ed.buffer) as usize;
    let mut lines: Vec<String> = Vec::with_capacity(n);
    for r in 0..n {
        lines.push(crate::types::Query::line(&ed.buffer, r as u32).to_string());
    }
    let row = crate::types::Cursor::cursor(&ed.buffer).line as usize;
    if let Some(ref mut session) = ed.vim.insert_session {
        session.before_lines = lines;
        session.row_min = row;
        session.row_max = row;
    }
}

// ─── Phase 6.1: public insert-mode primitives ──────────────────────────────
//
// Each `pub(crate)` free function below implements one insert-mode action.
// hjkl-vim's insert dispatcher calls them through `Editor::insert_*` methods.
// External callers can also invoke the public Editor methods directly.
//
// Invariants every function upholds:
//   - Opens with `ed.sync_buffer_content_from_textarea()` (no-op, kept for
//     forward compatibility once textarea is gone).
//   - All buffer mutations go through `ed.mutate_edit(...)` so dirty flag,
//     undo, change-list, content-edit fan-out all fire uniformly.
//   - Navigation-only functions call `break_undo_group_in_insert` when the
//     FSM did so, then return `false` (no mutation).
//   - After mutations, `ed.push_buffer_cursor_to_textarea()` is called
//     (currently a no-op but kept for migration hygiene).
//   - Returns `true` when the buffer was mutated, `false` otherwise.

/// Insert a single character at the cursor. Handles replace-mode overstrike
/// (when `InsertSession::reason` is `Replace`) and smart-indent dedent of
/// closing brackets (}/)]/). Returns `true`.
pub(crate) fn insert_char_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    ch: char,
) -> bool {
    use hjkl_buffer::{Edit, MotionKind, Position};
    ed.sync_buffer_content_from_textarea();
    let cursor = buf_cursor_pos(&ed.buffer);
    let line_chars = buf_line_chars(&ed.buffer, cursor.row);
    let in_replace = matches!(
        ed.vim.insert_session.as_ref().map(|s| &s.reason),
        Some(InsertReason::Replace)
    );
    if in_replace && cursor.col < line_chars {
        ed.mutate_edit(Edit::DeleteRange {
            start: cursor,
            end: Position::new(cursor.row, cursor.col + 1),
            kind: MotionKind::Char,
        });
        ed.mutate_edit(Edit::InsertChar { at: cursor, ch });
    } else if !try_dedent_close_bracket(ed, cursor, ch) {
        ed.mutate_edit(Edit::InsertChar { at: cursor, ch });
    }
    ed.push_buffer_cursor_to_textarea();
    true
}

/// Insert a newline at the cursor, applying autoindent / smartindent.
/// Returns `true`.
pub(crate) fn insert_newline_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
) -> bool {
    use hjkl_buffer::Edit;
    ed.sync_buffer_content_from_textarea();
    let cursor = buf_cursor_pos(&ed.buffer);
    let prev_line = buf_line(&ed.buffer, cursor.row)
        .unwrap_or_default()
        .to_string();
    let indent = compute_enter_indent(&ed.settings, &prev_line);
    let text = format!("\n{indent}");
    ed.mutate_edit(Edit::InsertStr { at: cursor, text });
    ed.push_buffer_cursor_to_textarea();
    true
}

/// Insert a tab character (or spaces up to the next softtabstop boundary when
/// `expandtab` is set). Returns `true`.
pub(crate) fn insert_tab_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
) -> bool {
    use hjkl_buffer::Edit;
    ed.sync_buffer_content_from_textarea();
    let cursor = buf_cursor_pos(&ed.buffer);
    if ed.settings.expandtab {
        let sts = ed.settings.softtabstop;
        let n = if sts > 0 {
            sts - (cursor.col % sts)
        } else {
            ed.settings.tabstop.max(1)
        };
        ed.mutate_edit(Edit::InsertStr {
            at: cursor,
            text: " ".repeat(n),
        });
    } else {
        ed.mutate_edit(Edit::InsertChar {
            at: cursor,
            ch: '\t',
        });
    }
    ed.push_buffer_cursor_to_textarea();
    true
}

/// Delete the character before the cursor (vim Backspace / `^H`). With
/// `softtabstop` active, deletes the entire soft-tab run at an aligned
/// boundary. Joins with the previous line when at column 0. Returns
/// `true` when something was deleted, `false` at the very start of the
/// buffer.
pub(crate) fn insert_backspace_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
) -> bool {
    use hjkl_buffer::{Edit, MotionKind, Position};
    ed.sync_buffer_content_from_textarea();
    let cursor = buf_cursor_pos(&ed.buffer);
    let sts = ed.settings.softtabstop;
    if sts > 0 && cursor.col >= sts && cursor.col.is_multiple_of(sts) {
        let line = buf_line(&ed.buffer, cursor.row).unwrap_or_default();
        let chars: Vec<char> = line.chars().collect();
        let run_start = cursor.col - sts;
        if (run_start..cursor.col).all(|i| chars.get(i).copied() == Some(' ')) {
            ed.mutate_edit(Edit::DeleteRange {
                start: Position::new(cursor.row, run_start),
                end: cursor,
                kind: MotionKind::Char,
            });
            ed.push_buffer_cursor_to_textarea();
            return true;
        }
    }
    let result = if cursor.col > 0 {
        ed.mutate_edit(Edit::DeleteRange {
            start: Position::new(cursor.row, cursor.col - 1),
            end: cursor,
            kind: MotionKind::Char,
        });
        true
    } else if cursor.row > 0 {
        let prev_row = cursor.row - 1;
        let prev_chars = buf_line_chars(&ed.buffer, prev_row);
        ed.mutate_edit(Edit::JoinLines {
            row: prev_row,
            count: 1,
            with_space: false,
        });
        buf_set_cursor_rc(&mut ed.buffer, prev_row, prev_chars);
        true
    } else {
        false
    };
    ed.push_buffer_cursor_to_textarea();
    result
}

/// Delete the character under the cursor (vim `Delete`). Joins with the
/// next line when at end-of-line. Returns `true` when something was deleted.
pub(crate) fn insert_delete_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
) -> bool {
    use hjkl_buffer::{Edit, MotionKind, Position};
    ed.sync_buffer_content_from_textarea();
    let cursor = buf_cursor_pos(&ed.buffer);
    let line_chars = buf_line_chars(&ed.buffer, cursor.row);
    let result = if cursor.col < line_chars {
        ed.mutate_edit(Edit::DeleteRange {
            start: cursor,
            end: Position::new(cursor.row, cursor.col + 1),
            kind: MotionKind::Char,
        });
        buf_set_cursor_pos(&mut ed.buffer, cursor);
        true
    } else if cursor.row + 1 < buf_row_count(&ed.buffer) {
        ed.mutate_edit(Edit::JoinLines {
            row: cursor.row,
            count: 1,
            with_space: false,
        });
        buf_set_cursor_pos(&mut ed.buffer, cursor);
        true
    } else {
        false
    };
    ed.push_buffer_cursor_to_textarea();
    result
}

/// Direction for insert-mode arrow movement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InsertDir {
    Left,
    Right,
    Up,
    Down,
}

/// Move the cursor one step in `dir`, breaking the undo group per
/// `undo_break_on_motion`. Returns `false` (no mutation).
pub(crate) fn insert_arrow_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    dir: InsertDir,
) -> bool {
    ed.sync_buffer_content_from_textarea();
    match dir {
        InsertDir::Left => {
            crate::motions::move_left(&mut ed.buffer, 1);
        }
        InsertDir::Right => {
            crate::motions::move_right_to_end(&mut ed.buffer, 1);
        }
        InsertDir::Up => {
            let folds = crate::buffer_impl::SnapshotFoldProvider::from_buffer(&ed.buffer);
            crate::motions::move_up(&mut ed.buffer, &folds, 1, &mut ed.sticky_col);
        }
        InsertDir::Down => {
            let folds = crate::buffer_impl::SnapshotFoldProvider::from_buffer(&ed.buffer);
            crate::motions::move_down(&mut ed.buffer, &folds, 1, &mut ed.sticky_col);
        }
    }
    break_undo_group_in_insert(ed);
    ed.push_buffer_cursor_to_textarea();
    false
}

/// Move the cursor to the start of the current line, breaking the undo group.
/// Returns `false` (no mutation).
pub(crate) fn insert_home_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
) -> bool {
    ed.sync_buffer_content_from_textarea();
    crate::motions::move_line_start(&mut ed.buffer);
    break_undo_group_in_insert(ed);
    ed.push_buffer_cursor_to_textarea();
    false
}

/// Move the cursor to the end of the current line, breaking the undo group.
/// Returns `false` (no mutation).
pub(crate) fn insert_end_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
) -> bool {
    ed.sync_buffer_content_from_textarea();
    crate::motions::move_line_end(&mut ed.buffer);
    break_undo_group_in_insert(ed);
    ed.push_buffer_cursor_to_textarea();
    false
}

/// Scroll up one full viewport height, moving the cursor with it.
/// Breaks the undo group. Returns `false` (no mutation).
pub(crate) fn insert_pageup_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    viewport_h: u16,
) -> bool {
    let rows = viewport_h.saturating_sub(2).max(1) as isize;
    scroll_cursor_rows(ed, -rows);
    false
}

/// Scroll down one full viewport height, moving the cursor with it.
/// Breaks the undo group. Returns `false` (no mutation).
pub(crate) fn insert_pagedown_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    viewport_h: u16,
) -> bool {
    let rows = viewport_h.saturating_sub(2).max(1) as isize;
    scroll_cursor_rows(ed, rows);
    false
}

/// Delete from the cursor back to the start of the previous word (`Ctrl-W`).
/// At col 0, joins with the previous line (vim semantics). Returns `true`
/// when something was deleted.
pub(crate) fn insert_ctrl_w_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
) -> bool {
    use hjkl_buffer::{Edit, MotionKind};
    ed.sync_buffer_content_from_textarea();
    let cursor = buf_cursor_pos(&ed.buffer);
    if cursor.row == 0 && cursor.col == 0 {
        return true;
    }
    crate::motions::move_word_back(&mut ed.buffer, false, 1, &ed.settings.iskeyword);
    let word_start = buf_cursor_pos(&ed.buffer);
    if word_start == cursor {
        return true;
    }
    buf_set_cursor_pos(&mut ed.buffer, cursor);
    ed.mutate_edit(Edit::DeleteRange {
        start: word_start,
        end: cursor,
        kind: MotionKind::Char,
    });
    ed.push_buffer_cursor_to_textarea();
    true
}

/// Delete from the cursor back to the start of the current line (`Ctrl-U`).
/// No-op when already at column 0. Returns `true` when something was deleted.
pub(crate) fn insert_ctrl_u_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
) -> bool {
    use hjkl_buffer::{Edit, MotionKind, Position};
    ed.sync_buffer_content_from_textarea();
    let cursor = buf_cursor_pos(&ed.buffer);
    if cursor.col > 0 {
        ed.mutate_edit(Edit::DeleteRange {
            start: Position::new(cursor.row, 0),
            end: cursor,
            kind: MotionKind::Char,
        });
        ed.push_buffer_cursor_to_textarea();
    }
    true
}

/// Delete one character backwards (`Ctrl-H`) — alias for Backspace in insert
/// mode. Joins with the previous line when at col 0. Returns `true` when
/// something was deleted.
pub(crate) fn insert_ctrl_h_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
) -> bool {
    use hjkl_buffer::{Edit, MotionKind, Position};
    ed.sync_buffer_content_from_textarea();
    let cursor = buf_cursor_pos(&ed.buffer);
    if cursor.col > 0 {
        ed.mutate_edit(Edit::DeleteRange {
            start: Position::new(cursor.row, cursor.col - 1),
            end: cursor,
            kind: MotionKind::Char,
        });
    } else if cursor.row > 0 {
        let prev_row = cursor.row - 1;
        let prev_chars = buf_line_chars(&ed.buffer, prev_row);
        ed.mutate_edit(Edit::JoinLines {
            row: prev_row,
            count: 1,
            with_space: false,
        });
        buf_set_cursor_rc(&mut ed.buffer, prev_row, prev_chars);
    }
    ed.push_buffer_cursor_to_textarea();
    true
}

/// Indent the current line by one `shiftwidth` and shift the cursor right by
/// the same amount (`Ctrl-T`). Returns `true`.
pub(crate) fn insert_ctrl_t_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
) -> bool {
    let (row, col) = ed.cursor();
    let sw = ed.settings().shiftwidth;
    indent_rows(ed, row, row, 1);
    ed.jump_cursor(row, col + sw);
    true
}

/// Outdent the current line by up to one `shiftwidth` and shift the cursor
/// left by the amount stripped (`Ctrl-D`). Returns `true`.
pub(crate) fn insert_ctrl_d_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
) -> bool {
    let (row, col) = ed.cursor();
    let before_len = buf_line_bytes(&ed.buffer, row);
    outdent_rows(ed, row, row, 1);
    let after_len = buf_line_bytes(&ed.buffer, row);
    let stripped = before_len.saturating_sub(after_len);
    let new_col = col.saturating_sub(stripped);
    ed.jump_cursor(row, new_col);
    true
}

/// Enter "one-shot normal" mode (`Ctrl-O`): suspend insert for the next
/// complete normal-mode command, then return to insert. Returns `false`
/// (no buffer mutation — only mode state changes).
pub(crate) fn insert_ctrl_o_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
) -> bool {
    ed.vim.one_shot_normal = true;
    ed.vim.mode = Mode::Normal;
    // Phase 6.3: keep current_mode in sync for callers that bypass step().
    ed.vim.current_mode = crate::VimMode::Normal;
    false
}

/// Arm the register-paste selector (`Ctrl-R`): the next typed character
/// names the register whose text will be inserted inline. Returns `false`
/// (no buffer mutation yet — mutation happens when the register char arrives).
pub(crate) fn insert_ctrl_r_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
) -> bool {
    ed.vim.insert_pending_register = true;
    false
}

/// Paste the contents of `reg` at the cursor (the body of `Ctrl-R {reg}`).
/// Unknown or empty registers are a no-op. Returns `true` when text was
/// inserted.
pub(crate) fn insert_paste_register_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    reg: char,
) -> bool {
    insert_register_text(ed, reg);
    // insert_register_text already calls mark_content_dirty internally;
    // return true to signal that the session row window should be widened.
    true
}

/// Exit insert mode to Normal: finish the insert session, step the cursor one
/// cell left (vim convention), record the `gi` target, and update the sticky
/// column. Returns `true` (always consumed — even if no buffer mutation, the
/// mode change itself is a meaningful step).
pub(crate) fn leave_insert_to_normal_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
) -> bool {
    finish_insert_session(ed);
    ed.vim.mode = Mode::Normal;
    // Phase 6.3: keep current_mode in sync for callers that bypass step().
    ed.vim.current_mode = crate::VimMode::Normal;
    let col = ed.cursor().1;
    ed.vim.last_insert_pos = Some(ed.cursor());
    if col > 0 {
        crate::motions::move_left(&mut ed.buffer, 1);
        ed.push_buffer_cursor_to_textarea();
    }
    ed.sticky_col = Some(ed.cursor().1);
    true
}

// ─── Phase 6.2: normal-mode primitive bridges ──────────────────────────────

/// Scroll direction for `scroll_full_page`, `scroll_half_page`, and
/// `scroll_line` controller methods.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScrollDir {
    /// Move forward / downward (toward end of buffer).
    Down,
    /// Move backward / upward (toward start of buffer).
    Up,
}

// ── Insert-mode entry bridges ──────────────────────────────────────────────

/// `i` — begin Insert at the cursor. `count` is stored in the session for
/// insert-exit replay. Returns `true`.
pub(crate) fn enter_insert_i_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    count: usize,
) {
    begin_insert(ed, count.max(1), InsertReason::Enter(InsertEntry::I));
}

/// `I` — move to first non-blank then begin Insert. `count` stored for replay.
pub(crate) fn enter_insert_shift_i_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    count: usize,
) {
    move_first_non_whitespace(ed);
    begin_insert(ed, count.max(1), InsertReason::Enter(InsertEntry::ShiftI));
}

/// `a` — advance past the cursor char then begin Insert. `count` for replay.
pub(crate) fn enter_insert_a_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    count: usize,
) {
    crate::motions::move_right_to_end(&mut ed.buffer, 1);
    ed.push_buffer_cursor_to_textarea();
    begin_insert(ed, count.max(1), InsertReason::Enter(InsertEntry::A));
}

/// `A` — move to end-of-line then begin Insert. `count` for replay.
pub(crate) fn enter_insert_shift_a_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    count: usize,
) {
    crate::motions::move_line_end(&mut ed.buffer);
    crate::motions::move_right_to_end(&mut ed.buffer, 1);
    ed.push_buffer_cursor_to_textarea();
    begin_insert(ed, count.max(1), InsertReason::Enter(InsertEntry::ShiftA));
}

/// `o` — open a new line below the cursor and begin Insert.
pub(crate) fn open_line_below_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    count: usize,
) {
    use hjkl_buffer::{Edit, Position};
    ed.push_undo();
    begin_insert_noundo(ed, count.max(1), InsertReason::Open { above: false });
    ed.sync_buffer_content_from_textarea();
    let row = buf_cursor_pos(&ed.buffer).row;
    let line_chars = buf_line_chars(&ed.buffer, row);
    let prev_line = buf_line(&ed.buffer, row).unwrap_or_default();
    let indent = compute_enter_indent(&ed.settings, prev_line);
    ed.mutate_edit(Edit::InsertStr {
        at: Position::new(row, line_chars),
        text: format!("\n{indent}"),
    });
    ed.push_buffer_cursor_to_textarea();
}

/// `O` — open a new line above the cursor and begin Insert.
pub(crate) fn open_line_above_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    count: usize,
) {
    use hjkl_buffer::{Edit, Position};
    ed.push_undo();
    begin_insert_noundo(ed, count.max(1), InsertReason::Open { above: true });
    ed.sync_buffer_content_from_textarea();
    let row = buf_cursor_pos(&ed.buffer).row;
    let indent = if row > 0 {
        let above = buf_line(&ed.buffer, row - 1).unwrap_or_default();
        compute_enter_indent(&ed.settings, above)
    } else {
        let cur = buf_line(&ed.buffer, row).unwrap_or_default();
        cur.chars()
            .take_while(|c| *c == ' ' || *c == '\t')
            .collect::<String>()
    };
    ed.mutate_edit(Edit::InsertStr {
        at: Position::new(row, 0),
        text: format!("{indent}\n"),
    });
    let folds = crate::buffer_impl::SnapshotFoldProvider::from_buffer(&ed.buffer);
    crate::motions::move_up(&mut ed.buffer, &folds, 1, &mut ed.sticky_col);
    let new_row = buf_cursor_pos(&ed.buffer).row;
    buf_set_cursor_rc(&mut ed.buffer, new_row, indent.chars().count());
    ed.push_buffer_cursor_to_textarea();
}

/// `R` — enter Replace mode (overstrike). `count` stored for replay.
pub(crate) fn enter_replace_mode_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    count: usize,
) {
    begin_insert(ed, count.max(1), InsertReason::Replace);
}

// ── Char / line ops ────────────────────────────────────────────────────────

/// `x` — delete `count` chars forward from the cursor, writing to the unnamed
/// register. Records `LastChange::CharDel` for dot-repeat.
pub(crate) fn delete_char_forward_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    count: usize,
) {
    do_char_delete(ed, true, count.max(1));
    if !ed.vim.replaying {
        ed.vim.last_change = Some(LastChange::CharDel {
            forward: true,
            count: count.max(1),
        });
    }
}

/// `X` — delete `count` chars backward from the cursor, writing to the unnamed
/// register. Records `LastChange::CharDel` for dot-repeat.
pub(crate) fn delete_char_backward_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    count: usize,
) {
    do_char_delete(ed, false, count.max(1));
    if !ed.vim.replaying {
        ed.vim.last_change = Some(LastChange::CharDel {
            forward: false,
            count: count.max(1),
        });
    }
}

/// `s` — substitute `count` chars (delete then enter Insert). Equivalent to
/// `cl`. Records `LastChange::OpMotion` for dot-repeat.
pub(crate) fn substitute_char_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    count: usize,
) {
    use hjkl_buffer::{Edit, MotionKind, Position};
    ed.push_undo();
    ed.sync_buffer_content_from_textarea();
    for _ in 0..count.max(1) {
        let cursor = buf_cursor_pos(&ed.buffer);
        let line_chars = buf_line_chars(&ed.buffer, cursor.row);
        if cursor.col >= line_chars {
            break;
        }
        ed.mutate_edit(Edit::DeleteRange {
            start: cursor,
            end: Position::new(cursor.row, cursor.col + 1),
            kind: MotionKind::Char,
        });
    }
    ed.push_buffer_cursor_to_textarea();
    begin_insert_noundo(ed, 1, InsertReason::AfterChange);
    if !ed.vim.replaying {
        ed.vim.last_change = Some(LastChange::OpMotion {
            op: Operator::Change,
            motion: Motion::Right,
            count: count.max(1),
            inserted: None,
        });
    }
}

/// `S` — substitute the whole line (delete line contents then enter Insert).
/// Equivalent to `cc`. Records `LastChange::LineOp` for dot-repeat.
pub(crate) fn substitute_line_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    count: usize,
) {
    execute_line_op(ed, Operator::Change, count.max(1));
    if !ed.vim.replaying {
        ed.vim.last_change = Some(LastChange::LineOp {
            op: Operator::Change,
            count: count.max(1),
            inserted: None,
        });
    }
}

/// `D` — delete from the cursor to end-of-line, writing to the unnamed
/// register. Cursor parks on the new last char. Records for dot-repeat.
pub(crate) fn delete_to_eol_bridge<H: crate::types::Host>(ed: &mut Editor<hjkl_buffer::Buffer, H>) {
    ed.push_undo();
    delete_to_eol(ed);
    crate::motions::move_left(&mut ed.buffer, 1);
    ed.push_buffer_cursor_to_textarea();
    if !ed.vim.replaying {
        ed.vim.last_change = Some(LastChange::DeleteToEol { inserted: None });
    }
}

/// `C` — change from the cursor to end-of-line (delete then enter Insert).
/// Equivalent to `c$`. Shares the delete path with `D`.
pub(crate) fn change_to_eol_bridge<H: crate::types::Host>(ed: &mut Editor<hjkl_buffer::Buffer, H>) {
    ed.push_undo();
    delete_to_eol(ed);
    begin_insert_noundo(ed, 1, InsertReason::DeleteToEol);
}

/// `Y` — yank from the cursor to end-of-line (same as `y$` in Vim 8 default).
pub(crate) fn yank_to_eol_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    count: usize,
) {
    apply_op_with_motion(ed, Operator::Yank, &Motion::LineEnd, count.max(1));
}

/// `J` — join `count` lines (default 2) onto the current one, inserting a
/// single space between each pair (vim semantics). Records for dot-repeat.
pub(crate) fn join_line_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    count: usize,
) {
    for _ in 0..count.max(1) {
        ed.push_undo();
        join_line(ed);
    }
    if !ed.vim.replaying {
        ed.vim.last_change = Some(LastChange::JoinLine {
            count: count.max(1),
        });
    }
}

/// `~` — toggle the case of `count` chars from the cursor, advancing right.
/// Records `LastChange::ToggleCase` for dot-repeat.
pub(crate) fn toggle_case_at_cursor_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    count: usize,
) {
    for _ in 0..count.max(1) {
        ed.push_undo();
        toggle_case_at_cursor(ed);
    }
    if !ed.vim.replaying {
        ed.vim.last_change = Some(LastChange::ToggleCase {
            count: count.max(1),
        });
    }
}

/// `p` — paste the unnamed register (or `"reg` register) after the cursor.
/// Linewise yanks open a new line below; charwise pastes inline.
/// Records `LastChange::Paste` for dot-repeat.
pub(crate) fn paste_after_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    count: usize,
) {
    do_paste(ed, false, count.max(1));
    if !ed.vim.replaying {
        ed.vim.last_change = Some(LastChange::Paste {
            before: false,
            count: count.max(1),
        });
    }
}

/// `P` — paste the unnamed register (or `"reg` register) before the cursor.
/// Linewise yanks open a new line above; charwise pastes inline.
/// Records `LastChange::Paste` for dot-repeat.
pub(crate) fn paste_before_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    count: usize,
) {
    do_paste(ed, true, count.max(1));
    if !ed.vim.replaying {
        ed.vim.last_change = Some(LastChange::Paste {
            before: true,
            count: count.max(1),
        });
    }
}

// ── Jump bridges ───────────────────────────────────────────────────────────

/// `<C-o>` — jump back `count` entries in the jumplist, saving the current
/// position on the forward stack so `<C-i>` can return.
pub(crate) fn jump_back_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    count: usize,
) {
    for _ in 0..count.max(1) {
        jump_back(ed);
    }
}

/// `<C-i>` / `Tab` — redo `count` jumps on the forward stack, saving the
/// current position on the backward stack.
pub(crate) fn jump_forward_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    count: usize,
) {
    for _ in 0..count.max(1) {
        jump_forward(ed);
    }
}

// ── Scroll bridges ─────────────────────────────────────────────────────────

/// `<C-f>` / `<C-b>` — scroll the cursor by one full viewport height
/// (`h - 2` rows to preserve two-line overlap). `count` multiplies.
pub(crate) fn scroll_full_page_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    dir: ScrollDir,
    count: usize,
) {
    let rows = viewport_full_rows(ed, count) as isize;
    match dir {
        ScrollDir::Down => scroll_cursor_rows(ed, rows),
        ScrollDir::Up => scroll_cursor_rows(ed, -rows),
    }
}

/// `<C-d>` / `<C-u>` — scroll the cursor by half the viewport height.
/// `count` multiplies.
pub(crate) fn scroll_half_page_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    dir: ScrollDir,
    count: usize,
) {
    let rows = viewport_half_rows(ed, count) as isize;
    match dir {
        ScrollDir::Down => scroll_cursor_rows(ed, rows),
        ScrollDir::Up => scroll_cursor_rows(ed, -rows),
    }
}

/// `<C-e>` / `<C-y>` — scroll the viewport `count` lines without moving the
/// cursor (cursor is clamped to the new visible region if it would go
/// off-screen). `<C-e>` scrolls down; `<C-y>` scrolls up.
pub(crate) fn scroll_line_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    dir: ScrollDir,
    count: usize,
) {
    let n = count.max(1);
    let total = buf_row_count(&ed.buffer);
    let last = total.saturating_sub(1);
    let h = ed.viewport_height_value() as usize;
    let vp = ed.host().viewport();
    let cur_top = vp.top_row;
    let new_top = match dir {
        ScrollDir::Down => (cur_top + n).min(last),
        ScrollDir::Up => cur_top.saturating_sub(n),
    };
    ed.set_viewport_top(new_top);
    // Clamp cursor to stay within the new visible region.
    let (row, col) = ed.cursor();
    let bot = (new_top + h).saturating_sub(1).min(last);
    let clamped = row.max(new_top).min(bot);
    if clamped != row {
        buf_set_cursor_rc(&mut ed.buffer, clamped, col);
        ed.push_buffer_cursor_to_textarea();
    }
}

// ── Search bridges ─────────────────────────────────────────────────────────

/// `n` / `N` — repeat the last search `count` times. `forward = true` means
/// repeat in the original search direction; `false` inverts it (like `N`).
pub(crate) fn search_repeat_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    forward: bool,
    count: usize,
) {
    if let Some(pattern) = ed.vim.last_search.clone() {
        ed.push_search_pattern(&pattern);
    }
    if ed.search_state().pattern.is_none() {
        return;
    }
    let go_forward = ed.vim.last_search_forward == forward;
    for _ in 0..count.max(1) {
        if go_forward {
            ed.search_advance_forward(true);
        } else {
            ed.search_advance_backward(true);
        }
    }
    ed.push_buffer_cursor_to_textarea();
}

/// `*` / `#` / `g*` / `g#` — search for the word under the cursor.
/// `forward` picks search direction; `whole_word` wraps in `\b...\b`.
/// `count` repeats the advance.
pub(crate) fn word_search_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    forward: bool,
    whole_word: bool,
    count: usize,
) {
    word_at_cursor_search(ed, forward, whole_word, count.max(1));
}

// ── Undo / redo confirmation wrappers (already public on Editor) ───────────

/// `u` bridge — identical to `do_undo`; retained for Phase 6.6b audit.
/// The FSM now calls `ed.undo()` directly (Phase 6.6a).
#[allow(dead_code)]
#[inline]
pub(crate) fn do_undo_bridge<H: crate::types::Host>(ed: &mut Editor<hjkl_buffer::Buffer, H>) {
    do_undo(ed);
}

// ─── Phase 6.3: visual-mode primitive bridges ──────────────────────────────
//
// Each `pub(crate)` free function is the extractable body of one visual-mode
// transition. These bridges set `vim.mode` directly AND write `current_mode`
// so that `Editor::vim_mode()` can read from the stable field without going
// through `public_mode()`.
//
// Pattern identical to Phase 6.1 / 6.2:
//   - Bridge fn is `pub(crate) fn *_bridge<H: Host>(ed, …)` in this file.
//   - Public wrapper is `pub fn *(&mut self, …)` in `editor.rs` with rustdoc.

/// Helper — set both the FSM-internal `mode` and the stable `current_mode`
/// field in one call. Every Phase 6.3 bridge that changes mode calls this so
/// `vim_mode()` stays correct without going through the FSM's `step()` loop.
#[inline]
pub(crate) fn set_vim_mode_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    mode: Mode,
) {
    ed.vim.mode = mode;
    ed.vim.current_mode = ed.vim.public_mode();
}

/// `v` from Normal — enter charwise Visual mode. Anchors at the current
/// cursor position; the cursor IS the live end of the selection.
pub(crate) fn enter_visual_char_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
) {
    let cur = ed.cursor();
    ed.vim.visual_anchor = cur;
    set_vim_mode_bridge(ed, Mode::Visual);
}

/// `V` from Normal — enter linewise Visual mode. Anchors the whole line
/// containing the current cursor; `o` still swaps the anchor row.
pub(crate) fn enter_visual_line_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
) {
    let (row, _) = ed.cursor();
    ed.vim.visual_line_anchor = row;
    set_vim_mode_bridge(ed, Mode::VisualLine);
}

/// `<C-v>` from Normal — enter Visual-block mode. Anchors at the current
/// cursor; `block_vcol` is seeded from the cursor column so h/l navigation
/// preserves the desired virtual column.
pub(crate) fn enter_visual_block_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
) {
    let cur = ed.cursor();
    ed.vim.block_anchor = cur;
    ed.vim.block_vcol = cur.1;
    set_vim_mode_bridge(ed, Mode::VisualBlock);
}

/// Esc from any visual mode — set `<` / `>` marks (per `:h v_:`), stash the
/// selection for `gv` re-entry, and return to Normal. Replicates the
/// `pre_visual_snapshot` logic in `step()` so callers outside the FSM get
/// identical behaviour.
pub(crate) fn exit_visual_to_normal_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
) {
    // Build the same snapshot that `step()` captures at pre-step time.
    let snap: Option<LastVisual> = match ed.vim.mode {
        Mode::Visual => Some(LastVisual {
            mode: Mode::Visual,
            anchor: ed.vim.visual_anchor,
            cursor: ed.cursor(),
            block_vcol: 0,
        }),
        Mode::VisualLine => Some(LastVisual {
            mode: Mode::VisualLine,
            anchor: (ed.vim.visual_line_anchor, 0),
            cursor: ed.cursor(),
            block_vcol: 0,
        }),
        Mode::VisualBlock => Some(LastVisual {
            mode: Mode::VisualBlock,
            anchor: ed.vim.block_anchor,
            cursor: ed.cursor(),
            block_vcol: ed.vim.block_vcol,
        }),
        _ => None,
    };
    // Transition to Normal first (matches FSM order).
    ed.vim.pending = Pending::None;
    ed.vim.count = 0;
    ed.vim.insert_session = None;
    set_vim_mode_bridge(ed, Mode::Normal);
    // Set `<` / `>` marks and stash `last_visual` — mirrors the post-step
    // logic in `step()` that fires when a visual → non-visual transition
    // is detected.
    if let Some(snap) = snap {
        let (lo, hi) = match snap.mode {
            Mode::Visual => {
                if snap.anchor <= snap.cursor {
                    (snap.anchor, snap.cursor)
                } else {
                    (snap.cursor, snap.anchor)
                }
            }
            Mode::VisualLine => {
                let r_lo = snap.anchor.0.min(snap.cursor.0);
                let r_hi = snap.anchor.0.max(snap.cursor.0);
                let last_col = ed
                    .buffer()
                    .lines()
                    .get(r_hi)
                    .map(|l| l.chars().count().saturating_sub(1))
                    .unwrap_or(0);
                ((r_lo, 0), (r_hi, last_col))
            }
            Mode::VisualBlock => {
                let (r1, c1) = snap.anchor;
                let (r2, c2) = snap.cursor;
                ((r1.min(r2), c1.min(c2)), (r1.max(r2), c1.max(c2)))
            }
            _ => {
                if snap.anchor <= snap.cursor {
                    (snap.anchor, snap.cursor)
                } else {
                    (snap.cursor, snap.anchor)
                }
            }
        };
        ed.set_mark('<', lo);
        ed.set_mark('>', hi);
        ed.vim.last_visual = Some(snap);
    }
}

/// `o` in Visual / VisualLine / VisualBlock — swap the cursor and anchor
/// without mutating the selection range. In charwise mode the cursor jumps
/// to the old anchor and the anchor takes the old cursor. In linewise mode
/// the anchor *row* swaps with the current cursor row. In block mode the
/// block corners swap.
pub(crate) fn visual_o_toggle_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
) {
    match ed.vim.mode {
        Mode::Visual => {
            let cur = ed.cursor();
            let anchor = ed.vim.visual_anchor;
            ed.vim.visual_anchor = cur;
            ed.jump_cursor(anchor.0, anchor.1);
        }
        Mode::VisualLine => {
            let cur_row = ed.cursor().0;
            let anchor_row = ed.vim.visual_line_anchor;
            ed.vim.visual_line_anchor = cur_row;
            ed.jump_cursor(anchor_row, 0);
        }
        Mode::VisualBlock => {
            let cur = ed.cursor();
            let anchor = ed.vim.block_anchor;
            ed.vim.block_anchor = cur;
            ed.vim.block_vcol = anchor.1;
            ed.jump_cursor(anchor.0, anchor.1);
        }
        _ => {}
    }
}

/// `gv` — restore the last visual selection (mode + anchor + cursor).
/// No-op if no selection was ever stored. Mirrors the `gv` arm in
/// `handle_normal_g`.
pub(crate) fn reenter_last_visual_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
) {
    if let Some(snap) = ed.vim.last_visual {
        match snap.mode {
            Mode::Visual => {
                ed.vim.visual_anchor = snap.anchor;
                set_vim_mode_bridge(ed, Mode::Visual);
            }
            Mode::VisualLine => {
                ed.vim.visual_line_anchor = snap.anchor.0;
                set_vim_mode_bridge(ed, Mode::VisualLine);
            }
            Mode::VisualBlock => {
                ed.vim.block_anchor = snap.anchor;
                ed.vim.block_vcol = snap.block_vcol;
                set_vim_mode_bridge(ed, Mode::VisualBlock);
            }
            _ => {}
        }
        ed.jump_cursor(snap.cursor.0, snap.cursor.1);
    }
}

/// Direct mode-transition entry point for external controllers (e.g.
/// hjkl-vim). Sets both the FSM-internal `mode` and the stable
/// `current_mode`. Use sparingly — prefer the semantic primitives
/// (`enter_visual_char_bridge`, `enter_insert_i_bridge`, …) which also
/// set up the required bookkeeping (anchors, sessions, …).
pub(crate) fn set_mode_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    mode: crate::VimMode,
) {
    let internal = match mode {
        crate::VimMode::Normal => Mode::Normal,
        crate::VimMode::Insert => Mode::Insert,
        crate::VimMode::Visual => Mode::Visual,
        crate::VimMode::VisualLine => Mode::VisualLine,
        crate::VimMode::VisualBlock => Mode::VisualBlock,
    };
    ed.vim.mode = internal;
    ed.vim.current_mode = mode;
}

// ─── Normal / Visual / Operator-pending dispatcher removed in Phase 6.6g.3 ──
//
// `step_normal` and all private dispatch helpers (handle_after_op,
// handle_after_g, handle_after_z, handle_normal_only, etc.) were deleted.
// The canonical FSM body lives in `hjkl-vim::normal`. Use
// `hjkl_vim::dispatch_input` as the entry point.
//
// DELETED FUNCTION SIGNATURE (for archaeology):
// pub(crate) fn step_normal<H: crate::types::Host>(ed: ..., input: Input) -> bool {

/// `m{ch}` — public controller entry point. Validates `ch` (must be
/// alphanumeric to match vim's mark-name rules) and records the current
/// cursor position under that name. Promoted to the public surface in 0.6.7
/// so the hjkl-vim `PendingState::SetMark` reducer can dispatch
/// `EngineCmd::SetMark` without re-entering the engine FSM.
/// `handle_set_mark` delegates here to avoid logic duplication.
pub(crate) fn set_mark_at_cursor<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    ch: char,
) {
    if ch.is_ascii_lowercase() || ch.is_ascii_uppercase() {
        // 0.0.36: lowercase + uppercase marks share the unified
        // `Editor::marks` map. Uppercase entries survive
        // `set_content` so they persist across tab swaps within the
        // same Editor (the map lives on the Editor, not the buffer).
        let pos = ed.cursor();
        ed.set_mark(ch, pos);
    }
    // Invalid chars silently no-op (mirrors handle_set_mark behaviour).
}

/// `'<ch>` / `` `<ch> `` — public controller entry point. Validates `ch`
/// against the set of legal mark names (lowercase, uppercase, special:
/// `'`/`` ` ``/`.`/`[`/`]`/`<`/`>`), resolves the target position, and
/// jumps the cursor. `linewise = true` → row only, col snaps to first
/// non-blank; `linewise = false` → exact (row, col). Called by
/// `Editor::goto_mark_line` / `Editor::goto_mark_char` so that hjkl-vim's
/// `PendingState::GotoMarkLine` / `GotoMarkChar` reducers can dispatch
/// without re-entering the engine FSM.
pub(crate) fn goto_mark<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    ch: char,
    linewise: bool,
) {
    let target = match ch {
        'a'..='z' | 'A'..='Z' => ed.mark(ch),
        '\'' | '`' => ed.vim.jump_back.last().copied(),
        '.' => ed.vim.last_edit_pos,
        '[' | ']' | '<' | '>' => ed.mark(ch),
        _ => None,
    };
    let Some((row, col)) = target else {
        return;
    };
    let pre = ed.cursor();
    let (r, c_clamped) = clamp_pos(ed, (row, col));
    if linewise {
        buf_set_cursor_rc(&mut ed.buffer, r, 0);
        ed.push_buffer_cursor_to_textarea();
        move_first_non_whitespace(ed);
    } else {
        buf_set_cursor_rc(&mut ed.buffer, r, c_clamped);
        ed.push_buffer_cursor_to_textarea();
    }
    if ed.cursor() != pre {
        ed.push_jump(pre);
    }
    ed.sticky_col = Some(ed.cursor().1);
}

/// `true` when `op` records a `last_change` entry for dot-repeat purposes.
/// Promoted to `pub` in Phase 6.6e so `hjkl-vim::normal` can use it without
/// duplicating the logic.
pub fn op_is_change(op: Operator) -> bool {
    matches!(op, Operator::Delete | Operator::Change)
}

// ─── Jumplist (Ctrl-o / Ctrl-i) ────────────────────────────────────────────

/// Max jumplist depth. Matches vim default.
pub(crate) const JUMPLIST_MAX: usize = 100;

/// `Ctrl-o` — jump back to the most recent pre-jump position. Saves
/// the current cursor onto the forward stack so `Ctrl-i` can return.
fn jump_back<H: crate::types::Host>(ed: &mut Editor<hjkl_buffer::Buffer, H>) {
    let Some(target) = ed.vim.jump_back.pop() else {
        return;
    };
    let cur = ed.cursor();
    ed.vim.jump_fwd.push(cur);
    let (r, c) = clamp_pos(ed, target);
    ed.jump_cursor(r, c);
    ed.sticky_col = Some(c);
}

/// `Ctrl-i` / `Tab` — redo the last `Ctrl-o`. Saves the current cursor
/// onto the back stack.
fn jump_forward<H: crate::types::Host>(ed: &mut Editor<hjkl_buffer::Buffer, H>) {
    let Some(target) = ed.vim.jump_fwd.pop() else {
        return;
    };
    let cur = ed.cursor();
    ed.vim.jump_back.push(cur);
    if ed.vim.jump_back.len() > JUMPLIST_MAX {
        ed.vim.jump_back.remove(0);
    }
    let (r, c) = clamp_pos(ed, target);
    ed.jump_cursor(r, c);
    ed.sticky_col = Some(c);
}

/// Clamp a stored `(row, col)` to the live buffer in case edits
/// shrunk the document between push and pop.
fn clamp_pos<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
    pos: (usize, usize),
) -> (usize, usize) {
    let last_row = buf_row_count(&ed.buffer).saturating_sub(1);
    let r = pos.0.min(last_row);
    let line_len = buf_line_chars(&ed.buffer, r);
    let c = pos.1.min(line_len.saturating_sub(1));
    (r, c)
}

/// True for motions that vim treats as jumps (pushed onto the jumplist).
fn is_big_jump(motion: &Motion) -> bool {
    matches!(
        motion,
        Motion::FileTop
            | Motion::FileBottom
            | Motion::MatchBracket
            | Motion::WordAtCursor { .. }
            | Motion::SearchNext { .. }
            | Motion::ViewportTop
            | Motion::ViewportMiddle
            | Motion::ViewportBottom
    )
}

// ─── Scroll helpers (Ctrl-d / Ctrl-u / Ctrl-f / Ctrl-b) ────────────────────

/// Half-viewport row count, with a floor of 1 so tiny / un-rendered
/// viewports still step by a single row. `count` multiplies.
fn viewport_half_rows<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
    count: usize,
) -> usize {
    let h = ed.viewport_height_value() as usize;
    (h / 2).max(1).saturating_mul(count.max(1))
}

/// Full-viewport row count. Vim conventionally keeps 2 lines of overlap
/// between successive `Ctrl-f` pages; we approximate with `h - 2`.
fn viewport_full_rows<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
    count: usize,
) -> usize {
    let h = ed.viewport_height_value() as usize;
    h.saturating_sub(2).max(1).saturating_mul(count.max(1))
}

/// Move the cursor by `delta` rows (positive = down, negative = up),
/// clamp to the document, then land at the first non-blank on the new
/// row. The textarea viewport auto-scrolls to keep the cursor visible
/// when the cursor pushes off-screen.
fn scroll_cursor_rows<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    delta: isize,
) {
    if delta == 0 {
        return;
    }
    ed.sync_buffer_content_from_textarea();
    let (row, _) = ed.cursor();
    let last_row = buf_row_count(&ed.buffer).saturating_sub(1);
    let target = (row as isize + delta).max(0).min(last_row as isize) as usize;
    buf_set_cursor_rc(&mut ed.buffer, target, 0);
    crate::motions::move_first_non_blank(&mut ed.buffer);
    ed.push_buffer_cursor_to_textarea();
    ed.sticky_col = Some(buf_cursor_pos(&ed.buffer).col);
}

// ─── Motion parsing ────────────────────────────────────────────────────────

/// Parse the first key of a normal/visual-mode motion. Returns `None` for
/// keys that don't start a motion (operator keys, command keys, etc.).
/// Promoted to `pub` in Phase 6.6e so `hjkl-vim::normal` can call it.
pub fn parse_motion(input: &Input) -> Option<Motion> {
    if input.ctrl {
        return None;
    }
    match input.key {
        Key::Char('h') | Key::Backspace | Key::Left => Some(Motion::Left),
        Key::Char('l') | Key::Right => Some(Motion::Right),
        Key::Char('j') | Key::Down | Key::Enter => Some(Motion::Down),
        Key::Char('k') | Key::Up => Some(Motion::Up),
        Key::Char('w') => Some(Motion::WordFwd),
        Key::Char('W') => Some(Motion::BigWordFwd),
        Key::Char('b') => Some(Motion::WordBack),
        Key::Char('B') => Some(Motion::BigWordBack),
        Key::Char('e') => Some(Motion::WordEnd),
        Key::Char('E') => Some(Motion::BigWordEnd),
        Key::Char('0') | Key::Home => Some(Motion::LineStart),
        Key::Char('^') => Some(Motion::FirstNonBlank),
        Key::Char('$') | Key::End => Some(Motion::LineEnd),
        Key::Char('G') => Some(Motion::FileBottom),
        Key::Char('%') => Some(Motion::MatchBracket),
        Key::Char(';') => Some(Motion::FindRepeat { reverse: false }),
        Key::Char(',') => Some(Motion::FindRepeat { reverse: true }),
        Key::Char('*') => Some(Motion::WordAtCursor {
            forward: true,
            whole_word: true,
        }),
        Key::Char('#') => Some(Motion::WordAtCursor {
            forward: false,
            whole_word: true,
        }),
        Key::Char('n') => Some(Motion::SearchNext { reverse: false }),
        Key::Char('N') => Some(Motion::SearchNext { reverse: true }),
        Key::Char('H') => Some(Motion::ViewportTop),
        Key::Char('M') => Some(Motion::ViewportMiddle),
        Key::Char('L') => Some(Motion::ViewportBottom),
        Key::Char('{') => Some(Motion::ParagraphPrev),
        Key::Char('}') => Some(Motion::ParagraphNext),
        Key::Char('(') => Some(Motion::SentencePrev),
        Key::Char(')') => Some(Motion::SentenceNext),
        _ => None,
    }
}

// ─── Motion execution ──────────────────────────────────────────────────────

pub(crate) fn execute_motion<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    motion: Motion,
    count: usize,
) {
    let count = count.max(1);
    // FindRepeat needs the stored direction.
    let motion = match motion {
        Motion::FindRepeat { reverse } => match ed.vim.last_find {
            Some((ch, forward, till)) => Motion::Find {
                ch,
                forward: if reverse { !forward } else { forward },
                till,
            },
            None => return,
        },
        other => other,
    };
    let pre_pos = ed.cursor();
    let pre_col = pre_pos.1;
    apply_motion_cursor(ed, &motion, count);
    let post_pos = ed.cursor();
    if is_big_jump(&motion) && pre_pos != post_pos {
        ed.push_jump(pre_pos);
    }
    apply_sticky_col(ed, &motion, pre_col);
    // Phase 7b: keep the migration buffer's cursor + viewport in
    // lockstep with the textarea after every motion. Once 7c lands
    // (motions ported onto the buffer's API), this flips: the
    // buffer becomes authoritative and the textarea mirrors it.
    ed.sync_buffer_from_textarea();
}

// ─── Keymap-layer motion controller ────────────────────────────────────────

/// Wrapper around `execute_motion` that also syncs `block_vcol` when in
/// VisualBlock mode. The engine FSM's `step()` already does this (line ~2001);
/// the keymap path (`apply_motion_kind`) must do the same so VisualBlock h/l
/// extend the highlighted region correctly.
///
/// `update_block_vcol` is only a no-op for vertical / non-horizontal motions
/// (Up, Down, FileTop, FileBottom, Search), so passing every motion through is
/// safe — the function's own match arm handles the no-op case.
fn execute_motion_with_block_vcol<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    motion: Motion,
    count: usize,
) {
    let motion_copy = motion.clone();
    execute_motion(ed, motion, count);
    if ed.vim.mode == Mode::VisualBlock {
        update_block_vcol(ed, &motion_copy);
    }
}

/// Execute a `crate::MotionKind` cursor motion. Called by the host's
/// `Editor::apply_motion` controller method — the keymap dispatch path for
/// Phase 3a of kryptic-sh/hjkl#69.
///
/// Maps each variant to the same internal primitives used by the engine FSM
/// so cursor, sticky column, scroll, and sync semantics are identical.
///
/// # Visual-mode post-motion sync audit (2026-05-13)
///
/// After `execute_motion`, two things are conditional on visual mode:
///
/// 1. **VisualBlock `block_vcol` sync** — `update_block_vcol(ed, &motion)` is
///    called when `mode == Mode::VisualBlock`.  This is replicated here via
///    `execute_motion_with_block_vcol` for every motion variant below.
///
/// 2. **`last_find` update** — `Motion::Find` is dispatched through
///    `Pending::Find → apply_find_char` (in hjkl-vim), which writes `last_find`
///    itself.  A post-motion `last_find` write here would be dead code.  The keymap
///    path writes `last_find` in `apply_find_char` (called from
///    `Editor::find_char`), so no gap exists here.
///
/// No VisualLine-specific or Visual-specific post-motion work exists in the
/// FSM: anchors (`visual_anchor`, `visual_line_anchor`, `block_anchor`) are
/// only written on mode-entry or `o`-swap, never on motion.  The `<`/`>`
/// mark update in `step()` fires only on visual→normal transition, not after
/// each motion.  There are **no further sync gaps** beyond the `block_vcol`
/// fix already applied above.
pub(crate) fn apply_motion_kind<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    kind: crate::MotionKind,
    count: usize,
) {
    let count = count.max(1);
    match kind {
        crate::MotionKind::CharLeft => {
            execute_motion_with_block_vcol(ed, Motion::Left, count);
        }
        crate::MotionKind::CharRight => {
            execute_motion_with_block_vcol(ed, Motion::Right, count);
        }
        crate::MotionKind::LineDown => {
            execute_motion_with_block_vcol(ed, Motion::Down, count);
        }
        crate::MotionKind::LineUp => {
            execute_motion_with_block_vcol(ed, Motion::Up, count);
        }
        crate::MotionKind::FirstNonBlankDown => {
            // `+`: move down `count` lines then land on first non-blank.
            // Not a big-jump (no jump-list entry), sticky col set to the
            // landed column (first non-blank). Mirrors scroll_cursor_rows
            // semantics but goes through the fold-aware buffer motion path.
            let folds = crate::buffer_impl::SnapshotFoldProvider::from_buffer(&ed.buffer);
            crate::motions::move_down(&mut ed.buffer, &folds, count, &mut ed.sticky_col);
            crate::motions::move_first_non_blank(&mut ed.buffer);
            ed.push_buffer_cursor_to_textarea();
            ed.sticky_col = Some(buf_cursor_pos(&ed.buffer).col);
            ed.sync_buffer_from_textarea();
        }
        crate::MotionKind::FirstNonBlankUp => {
            // `-`: move up `count` lines then land on first non-blank.
            // Same pattern as FirstNonBlankDown, direction reversed.
            let folds = crate::buffer_impl::SnapshotFoldProvider::from_buffer(&ed.buffer);
            crate::motions::move_up(&mut ed.buffer, &folds, count, &mut ed.sticky_col);
            crate::motions::move_first_non_blank(&mut ed.buffer);
            ed.push_buffer_cursor_to_textarea();
            ed.sticky_col = Some(buf_cursor_pos(&ed.buffer).col);
            ed.sync_buffer_from_textarea();
        }
        crate::MotionKind::WordForward => {
            execute_motion_with_block_vcol(ed, Motion::WordFwd, count);
        }
        crate::MotionKind::BigWordForward => {
            execute_motion_with_block_vcol(ed, Motion::BigWordFwd, count);
        }
        crate::MotionKind::WordBackward => {
            execute_motion_with_block_vcol(ed, Motion::WordBack, count);
        }
        crate::MotionKind::BigWordBackward => {
            execute_motion_with_block_vcol(ed, Motion::BigWordBack, count);
        }
        crate::MotionKind::WordEnd => {
            execute_motion_with_block_vcol(ed, Motion::WordEnd, count);
        }
        crate::MotionKind::BigWordEnd => {
            execute_motion_with_block_vcol(ed, Motion::BigWordEnd, count);
        }
        crate::MotionKind::LineStart => {
            // `0` / `<Home>`: first column of the current line.
            // count is ignored — matches vim `0` semantics.
            execute_motion_with_block_vcol(ed, Motion::LineStart, 1);
        }
        crate::MotionKind::FirstNonBlank => {
            // `^`: first non-blank column on the current line.
            // count is ignored — matches vim `^` semantics.
            execute_motion_with_block_vcol(ed, Motion::FirstNonBlank, 1);
        }
        crate::MotionKind::GotoLine => {
            // `G`: bare `G` → last line; `count G` → jump to line `count`.
            // apply_motion_kind normalises the raw count to count.max(1)
            // above, so count == 1 means "bare G" (last line) and count > 1
            // means "go to line N". execute_motion's FileBottom arm applies
            // the same `count > 1` check before calling move_bottom, so the
            // convention aligns: pass count straight through.
            // FileBottom is vertical — update_block_vcol is a no-op here
            // (preserves vcol), so the helper is safe to use.
            execute_motion_with_block_vcol(ed, Motion::FileBottom, count);
        }
        crate::MotionKind::LineEnd => {
            // `$` / `<End>`: last character on the current line.
            // count is ignored at the keymap-path level (vim `N$` moves
            // down N-1 lines then lands at line-end; not yet wired).
            execute_motion_with_block_vcol(ed, Motion::LineEnd, 1);
        }
        crate::MotionKind::FindRepeat => {
            // `;` — repeat last f/F/t/T in the same direction.
            // execute_motion resolves FindRepeat via ed.vim.last_find;
            // no-op if no prior find exists (None arm returns early).
            execute_motion_with_block_vcol(ed, Motion::FindRepeat { reverse: false }, count);
        }
        crate::MotionKind::FindRepeatReverse => {
            // `,` — repeat last f/F/t/T in the reverse direction.
            // execute_motion resolves FindRepeat via ed.vim.last_find;
            // no-op if no prior find exists (None arm returns early).
            execute_motion_with_block_vcol(ed, Motion::FindRepeat { reverse: true }, count);
        }
        crate::MotionKind::BracketMatch => {
            // `%` — jump to the matching bracket.
            // count is passed through; engine-side matching_bracket handles
            // the no-match case as a no-op (cursor stays). Engine FSM arm
            // for `%` in parse_motion is kept intact for macro-replay.
            execute_motion_with_block_vcol(ed, Motion::MatchBracket, count);
        }
        crate::MotionKind::ViewportTop => {
            // `H` — cursor to top of visible viewport, then count-1 rows down.
            // Engine FSM arm for `H` in parse_motion is kept intact for macro-replay.
            execute_motion_with_block_vcol(ed, Motion::ViewportTop, count);
        }
        crate::MotionKind::ViewportMiddle => {
            // `M` — cursor to middle of visible viewport; count ignored.
            // Engine FSM arm for `M` in parse_motion is kept intact for macro-replay.
            execute_motion_with_block_vcol(ed, Motion::ViewportMiddle, count);
        }
        crate::MotionKind::ViewportBottom => {
            // `L` — cursor to bottom of visible viewport, then count-1 rows up.
            // Engine FSM arm for `L` in parse_motion is kept intact for macro-replay.
            execute_motion_with_block_vcol(ed, Motion::ViewportBottom, count);
        }
        crate::MotionKind::HalfPageDown => {
            // `<C-d>` — half page down, count multiplies the distance.
            // Calls scroll_cursor_rows directly rather than adding a Motion enum
            // variant, keeping engine Motion churn minimal.
            scroll_cursor_rows(ed, viewport_half_rows(ed, count) as isize);
        }
        crate::MotionKind::HalfPageUp => {
            // `<C-u>` — half page up, count multiplies the distance.
            // Direct call mirrors the FSM Ctrl-u arm. No new Motion variant.
            scroll_cursor_rows(ed, -(viewport_half_rows(ed, count) as isize));
        }
        crate::MotionKind::FullPageDown => {
            // `<C-f>` — full page down (2-line overlap), count multiplies.
            // Direct call mirrors the FSM Ctrl-f arm. No new Motion variant.
            scroll_cursor_rows(ed, viewport_full_rows(ed, count) as isize);
        }
        crate::MotionKind::FullPageUp => {
            // `<C-b>` — full page up (2-line overlap), count multiplies.
            // Direct call mirrors the FSM Ctrl-b arm. No new Motion variant.
            scroll_cursor_rows(ed, -(viewport_full_rows(ed, count) as isize));
        }
    }
}

/// Restore the cursor to the sticky column after vertical motions and
/// sync the sticky column to the current column after horizontal ones.
/// `pre_col` is the cursor column captured *before* the motion — used
/// to bootstrap the sticky value on the very first motion.
fn apply_sticky_col<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    motion: &Motion,
    pre_col: usize,
) {
    if is_vertical_motion(motion) {
        let want = ed.sticky_col.unwrap_or(pre_col);
        // Record the desired column so the next vertical motion sees
        // it even if we currently clamped to a shorter row.
        ed.sticky_col = Some(want);
        let (row, _) = ed.cursor();
        let line_len = buf_line_chars(&ed.buffer, row);
        // Clamp to the last char on non-empty lines (vim normal-mode
        // never parks the cursor one past end of line). Empty lines
        // collapse to col 0.
        let max_col = line_len.saturating_sub(1);
        let target = want.min(max_col);
        ed.jump_cursor(row, target);
    } else {
        // Horizontal motion or non-motion: sticky column tracks the
        // new cursor column so the *next* vertical motion aims there.
        ed.sticky_col = Some(ed.cursor().1);
    }
}

fn is_vertical_motion(motion: &Motion) -> bool {
    // Only j / k preserve the sticky column. Everything else (search,
    // gg / G, word jumps, etc.) lands at the match's own column so the
    // sticky value should sync to the new cursor column.
    matches!(
        motion,
        Motion::Up | Motion::Down | Motion::ScreenUp | Motion::ScreenDown
    )
}

fn apply_motion_cursor<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    motion: &Motion,
    count: usize,
) {
    apply_motion_cursor_ctx(ed, motion, count, false)
}

fn apply_motion_cursor_ctx<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    motion: &Motion,
    count: usize,
    as_operator: bool,
) {
    match motion {
        Motion::Left => {
            // `h` — Buffer clamps at col 0 (no wrap), matching vim.
            crate::motions::move_left(&mut ed.buffer, count);
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::Right => {
            // `l` — operator-motion context (`dl`/`cl`/`yl`) is allowed
            // one past the last char so the range includes it; cursor
            // context clamps at the last char.
            if as_operator {
                crate::motions::move_right_to_end(&mut ed.buffer, count);
            } else {
                crate::motions::move_right_in_line(&mut ed.buffer, count);
            }
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::Up => {
            // Final col is set by `apply_sticky_col` below — push the
            // post-move row to the textarea and let sticky tracking
            // finish the work.
            let folds = crate::buffer_impl::SnapshotFoldProvider::from_buffer(&ed.buffer);
            crate::motions::move_up(&mut ed.buffer, &folds, count, &mut ed.sticky_col);
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::Down => {
            let folds = crate::buffer_impl::SnapshotFoldProvider::from_buffer(&ed.buffer);
            crate::motions::move_down(&mut ed.buffer, &folds, count, &mut ed.sticky_col);
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::ScreenUp => {
            let v = *ed.host.viewport();
            let folds = crate::buffer_impl::SnapshotFoldProvider::from_buffer(&ed.buffer);
            crate::motions::move_screen_up(&mut ed.buffer, &folds, &v, count, &mut ed.sticky_col);
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::ScreenDown => {
            let v = *ed.host.viewport();
            let folds = crate::buffer_impl::SnapshotFoldProvider::from_buffer(&ed.buffer);
            crate::motions::move_screen_down(&mut ed.buffer, &folds, &v, count, &mut ed.sticky_col);
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::WordFwd => {
            crate::motions::move_word_fwd(&mut ed.buffer, false, count, &ed.settings.iskeyword);
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::WordBack => {
            crate::motions::move_word_back(&mut ed.buffer, false, count, &ed.settings.iskeyword);
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::WordEnd => {
            crate::motions::move_word_end(&mut ed.buffer, false, count, &ed.settings.iskeyword);
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::BigWordFwd => {
            crate::motions::move_word_fwd(&mut ed.buffer, true, count, &ed.settings.iskeyword);
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::BigWordBack => {
            crate::motions::move_word_back(&mut ed.buffer, true, count, &ed.settings.iskeyword);
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::BigWordEnd => {
            crate::motions::move_word_end(&mut ed.buffer, true, count, &ed.settings.iskeyword);
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::WordEndBack => {
            crate::motions::move_word_end_back(
                &mut ed.buffer,
                false,
                count,
                &ed.settings.iskeyword,
            );
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::BigWordEndBack => {
            crate::motions::move_word_end_back(&mut ed.buffer, true, count, &ed.settings.iskeyword);
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::LineStart => {
            crate::motions::move_line_start(&mut ed.buffer);
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::FirstNonBlank => {
            crate::motions::move_first_non_blank(&mut ed.buffer);
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::LineEnd => {
            // Vim normal-mode `$` lands on the last char, not one past it.
            crate::motions::move_line_end(&mut ed.buffer);
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::FileTop => {
            // `count gg` jumps to line `count` (first non-blank);
            // bare `gg` lands at the top.
            if count > 1 {
                crate::motions::move_bottom(&mut ed.buffer, count);
            } else {
                crate::motions::move_top(&mut ed.buffer);
            }
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::FileBottom => {
            // `count G` jumps to line `count`; bare `G` lands at
            // the buffer bottom (`Buffer::move_bottom(0)`).
            if count > 1 {
                crate::motions::move_bottom(&mut ed.buffer, count);
            } else {
                crate::motions::move_bottom(&mut ed.buffer, 0);
            }
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::Find { ch, forward, till } => {
            for _ in 0..count {
                if !find_char_on_line(ed, *ch, *forward, *till) {
                    break;
                }
            }
        }
        Motion::FindRepeat { .. } => {} // already resolved upstream
        Motion::MatchBracket => {
            let _ = matching_bracket(ed);
        }
        Motion::WordAtCursor {
            forward,
            whole_word,
        } => {
            word_at_cursor_search(ed, *forward, *whole_word, count);
        }
        Motion::SearchNext { reverse } => {
            // Re-push the last query so the buffer's search state is
            // correct even if the host happened to clear it (e.g. while
            // a Visual mode draw was in progress).
            if let Some(pattern) = ed.vim.last_search.clone() {
                ed.push_search_pattern(&pattern);
            }
            if ed.search_state().pattern.is_none() {
                return;
            }
            // `n` repeats the last search in its committed direction;
            // `N` inverts. So a `?` search makes `n` walk backward and
            // `N` walk forward.
            let forward = ed.vim.last_search_forward != *reverse;
            for _ in 0..count.max(1) {
                if forward {
                    ed.search_advance_forward(true);
                } else {
                    ed.search_advance_backward(true);
                }
            }
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::ViewportTop => {
            let v = *ed.host().viewport();
            crate::motions::move_viewport_top(&mut ed.buffer, &v, count.saturating_sub(1));
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::ViewportMiddle => {
            let v = *ed.host().viewport();
            crate::motions::move_viewport_middle(&mut ed.buffer, &v);
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::ViewportBottom => {
            let v = *ed.host().viewport();
            crate::motions::move_viewport_bottom(&mut ed.buffer, &v, count.saturating_sub(1));
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::LastNonBlank => {
            crate::motions::move_last_non_blank(&mut ed.buffer);
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::LineMiddle => {
            let row = ed.cursor().0;
            let line_chars = buf_line_chars(&ed.buffer, row);
            // Vim's `gM`: column = floor(chars / 2). Empty / single-char
            // lines stay at col 0.
            let target = line_chars / 2;
            ed.jump_cursor(row, target);
        }
        Motion::ParagraphPrev => {
            crate::motions::move_paragraph_prev(&mut ed.buffer, count);
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::ParagraphNext => {
            crate::motions::move_paragraph_next(&mut ed.buffer, count);
            ed.push_buffer_cursor_to_textarea();
        }
        Motion::SentencePrev => {
            for _ in 0..count.max(1) {
                if let Some((row, col)) = sentence_boundary(ed, false) {
                    ed.jump_cursor(row, col);
                }
            }
        }
        Motion::SentenceNext => {
            for _ in 0..count.max(1) {
                if let Some((row, col)) = sentence_boundary(ed, true) {
                    ed.jump_cursor(row, col);
                }
            }
        }
    }
}

fn move_first_non_whitespace<H: crate::types::Host>(ed: &mut Editor<hjkl_buffer::Buffer, H>) {
    // Some call sites invoke this right after `dd` / `<<` / `>>` etc
    // mutates the textarea content, so the migration buffer hasn't
    // seen the new lines OR new cursor yet. Mirror the full content
    // across before delegating, then push the result back so the
    // textarea reflects the resolved column too.
    ed.sync_buffer_content_from_textarea();
    crate::motions::move_first_non_blank(&mut ed.buffer);
    ed.push_buffer_cursor_to_textarea();
}

fn find_char_on_line<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    ch: char,
    forward: bool,
    till: bool,
) -> bool {
    let moved = crate::motions::find_char_on_line(&mut ed.buffer, ch, forward, till);
    if moved {
        ed.push_buffer_cursor_to_textarea();
    }
    moved
}

fn matching_bracket<H: crate::types::Host>(ed: &mut Editor<hjkl_buffer::Buffer, H>) -> bool {
    let moved = crate::motions::match_bracket(&mut ed.buffer);
    if moved {
        ed.push_buffer_cursor_to_textarea();
    }
    moved
}

fn word_at_cursor_search<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    forward: bool,
    whole_word: bool,
    count: usize,
) {
    let (row, col) = ed.cursor();
    let line: String = buf_line(&ed.buffer, row).unwrap_or("").to_string();
    let chars: Vec<char> = line.chars().collect();
    if chars.is_empty() {
        return;
    }
    // Expand around cursor to a word boundary.
    let spec = ed.settings().iskeyword.clone();
    let is_word = |c: char| is_keyword_char(c, &spec);
    let mut start = col.min(chars.len().saturating_sub(1));
    while start > 0 && is_word(chars[start - 1]) {
        start -= 1;
    }
    let mut end = start;
    while end < chars.len() && is_word(chars[end]) {
        end += 1;
    }
    if end <= start {
        return;
    }
    let word: String = chars[start..end].iter().collect();
    let escaped = regex_escape(&word);
    let pattern = if whole_word {
        format!(r"\b{escaped}\b")
    } else {
        escaped
    };
    ed.push_search_pattern(&pattern);
    if ed.search_state().pattern.is_none() {
        return;
    }
    // Remember the query so `n` / `N` keep working after the jump.
    ed.vim.last_search = Some(pattern);
    ed.vim.last_search_forward = forward;
    for _ in 0..count.max(1) {
        if forward {
            ed.search_advance_forward(true);
        } else {
            ed.search_advance_backward(true);
        }
    }
    ed.push_buffer_cursor_to_textarea();
}

fn regex_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        if matches!(
            c,
            '.' | '+' | '*' | '?' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | '^' | '$' | '\\'
        ) {
            out.push('\\');
        }
        out.push(c);
    }
    out
}

// ─── Operator application ──────────────────────────────────────────────────

/// Public(crate) entry: apply operator over the motion identified by a raw
/// char key. Called by `Editor::apply_op_motion` (the public controller API)
/// so the hjkl-vim pending-state reducer can dispatch `ApplyOpMotion` without
/// re-entering the FSM.
///
/// Applies standard vim quirks:
/// - `cw` / `cW` → `ce` / `cE`
/// - `FindRepeat` → resolves against `last_find`
/// - Updates `last_find` and `last_change` per existing conventions.
///
/// No-op when `motion_key` does not produce a known motion.
pub(crate) fn apply_op_motion_key<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    op: Operator,
    motion_key: char,
    total_count: usize,
) {
    let input = Input {
        key: Key::Char(motion_key),
        ctrl: false,
        alt: false,
        shift: false,
    };
    let Some(motion) = parse_motion(&input) else {
        return;
    };
    let motion = match motion {
        Motion::FindRepeat { reverse } => match ed.vim.last_find {
            Some((ch, forward, till)) => Motion::Find {
                ch,
                forward: if reverse { !forward } else { forward },
                till,
            },
            None => return,
        },
        // Vim quirk: `cw` / `cW` → `ce` / `cE`.
        Motion::WordFwd if op == Operator::Change => Motion::WordEnd,
        Motion::BigWordFwd if op == Operator::Change => Motion::BigWordEnd,
        m => m,
    };
    apply_op_with_motion(ed, op, &motion, total_count);
    if let Motion::Find { ch, forward, till } = &motion {
        ed.vim.last_find = Some((*ch, *forward, *till));
    }
    if !ed.vim.replaying && op_is_change(op) {
        ed.vim.last_change = Some(LastChange::OpMotion {
            op,
            motion,
            count: total_count,
            inserted: None,
        });
    }
}

/// Public(crate) entry: apply doubled-letter line op (`dd`/`yy`/`cc`/`>>`/`<<`).
/// Called by `Editor::apply_op_double` (the public controller API).
pub(crate) fn apply_op_double<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    op: Operator,
    total_count: usize,
) {
    execute_line_op(ed, op, total_count);
    if !ed.vim.replaying {
        ed.vim.last_change = Some(LastChange::LineOp {
            op,
            count: total_count,
            inserted: None,
        });
    }
}

/// Shared implementation: apply operator over a g-chord motion or case-op
/// linewise form. Called by `Editor::apply_op_g` (the public controller API)
/// so the hjkl-vim reducer can dispatch `ApplyOpG` without re-entering the FSM.
///
/// - If `op` is Uppercase/Lowercase/ToggleCase and `ch` matches the op's char
///   (`U`/`u`/`~`): executes the line op and updates `last_change`.
/// - Otherwise, maps `ch` to a motion (`g`→FileTop, `e`→WordEndBack,
///   `E`→BigWordEndBack, `j`→ScreenDown, `k`→ScreenUp) and applies. Unknown
///   chars are silently ignored (no-op), matching the engine FSM's behaviour.
pub(crate) fn apply_op_g_inner<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    op: Operator,
    ch: char,
    total_count: usize,
) {
    // Case-op linewise form: `gUgU`, `gugu`, `g~g~` — same effect as
    // `gUU` / `guu` / `g~~`.
    if matches!(
        op,
        Operator::Uppercase | Operator::Lowercase | Operator::ToggleCase
    ) {
        let op_char = match op {
            Operator::Uppercase => 'U',
            Operator::Lowercase => 'u',
            Operator::ToggleCase => '~',
            _ => unreachable!(),
        };
        if ch == op_char {
            execute_line_op(ed, op, total_count);
            if !ed.vim.replaying {
                ed.vim.last_change = Some(LastChange::LineOp {
                    op,
                    count: total_count,
                    inserted: None,
                });
            }
            return;
        }
    }
    let motion = match ch {
        'g' => Motion::FileTop,
        'e' => Motion::WordEndBack,
        'E' => Motion::BigWordEndBack,
        'j' => Motion::ScreenDown,
        'k' => Motion::ScreenUp,
        _ => return, // Unknown char — no-op.
    };
    apply_op_with_motion(ed, op, &motion, total_count);
    if !ed.vim.replaying && op_is_change(op) {
        ed.vim.last_change = Some(LastChange::OpMotion {
            op,
            motion,
            count: total_count,
            inserted: None,
        });
    }
}

/// Public(crate) entry point for bare `g<x>`. Applies the g-chord effect
/// given the char `ch` and pre-captured `count`. Called by `Editor::after_g`
/// (the public controller API) so the hjkl-vim pending-state reducer can
/// dispatch `AfterGChord` without re-entering the FSM.
pub(crate) fn apply_after_g<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    ch: char,
    count: usize,
) {
    match ch {
        'g' => {
            // gg — top / jump to line count.
            let pre = ed.cursor();
            if count > 1 {
                ed.jump_cursor(count - 1, 0);
            } else {
                ed.jump_cursor(0, 0);
            }
            move_first_non_whitespace(ed);
            if ed.cursor() != pre {
                ed.push_jump(pre);
            }
        }
        'e' => execute_motion(ed, Motion::WordEndBack, count),
        'E' => execute_motion(ed, Motion::BigWordEndBack, count),
        // `g_` — last non-blank on the line.
        '_' => execute_motion(ed, Motion::LastNonBlank, count),
        // `gM` — middle char column of the current line.
        'M' => execute_motion(ed, Motion::LineMiddle, count),
        // `gv` — re-enter the last visual selection.
        // Phase 6.6a: drive through the public Editor API.
        'v' => ed.reenter_last_visual(),
        // `gj` / `gk` — display-line down / up. Walks one screen
        // segment at a time under `:set wrap`; falls back to `j`/`k`
        // when wrap is off (Buffer::move_screen_* handles the branch).
        'j' => execute_motion(ed, Motion::ScreenDown, count),
        'k' => execute_motion(ed, Motion::ScreenUp, count),
        // Case operators: `gU` / `gu` / `g~`. Enter operator-pending
        // so the next input is treated as the motion / text object /
        // shorthand double (`gUU`, `guu`, `g~~`).
        'U' => {
            ed.vim.pending = Pending::Op {
                op: Operator::Uppercase,
                count1: count,
            };
        }
        'u' => {
            ed.vim.pending = Pending::Op {
                op: Operator::Lowercase,
                count1: count,
            };
        }
        '~' => {
            ed.vim.pending = Pending::Op {
                op: Operator::ToggleCase,
                count1: count,
            };
        }
        'q' => {
            // `gq{motion}` — text reflow operator. Subsequent motion
            // / textobj rides the same operator pipeline.
            ed.vim.pending = Pending::Op {
                op: Operator::Reflow,
                count1: count,
            };
        }
        'J' => {
            // `gJ` — join line below without inserting a space.
            for _ in 0..count.max(1) {
                ed.push_undo();
                join_line_raw(ed);
            }
            if !ed.vim.replaying {
                ed.vim.last_change = Some(LastChange::JoinLine {
                    count: count.max(1),
                });
            }
        }
        'd' => {
            // `gd` — goto definition. hjkl-engine doesn't run an LSP
            // itself; raise an intent the host drains and routes to
            // `sqls`. The cursor stays put here — the host moves it
            // once it has the target location.
            ed.pending_lsp = Some(crate::editor::LspIntent::GotoDefinition);
        }
        // `gi` — go to last-insert position and re-enter insert mode.
        // Matches vim's `:h gi`: moves to the `'^` mark position (the
        // cursor where insert mode was last active, before Esc step-back)
        // and enters insert mode there.
        'i' => {
            if let Some((row, col)) = ed.vim.last_insert_pos {
                ed.jump_cursor(row, col);
            }
            begin_insert(ed, count.max(1), InsertReason::Enter(InsertEntry::I));
        }
        // `g;` / `g,` — walk the change list. `g;` toward older
        // entries, `g,` toward newer.
        ';' => walk_change_list(ed, -1, count.max(1)),
        ',' => walk_change_list(ed, 1, count.max(1)),
        // `g*` / `g#` — like `*` / `#` but match substrings (no `\b`
        // boundary anchors), so the cursor on `foo` finds it inside
        // `foobar` too.
        '*' => execute_motion(
            ed,
            Motion::WordAtCursor {
                forward: true,
                whole_word: false,
            },
            count,
        ),
        '#' => execute_motion(
            ed,
            Motion::WordAtCursor {
                forward: false,
                whole_word: false,
            },
            count,
        ),
        _ => {}
    }
}

/// Public(crate) entry point for bare `z<x>`. Applies the z-chord effect
/// given the char `ch` and pre-captured `count`. Called by `Editor::after_z`
/// (the public controller API) so the hjkl-vim pending-state reducer can
/// dispatch `AfterZChord` without re-entering the engine FSM.
pub(crate) fn apply_after_z<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    ch: char,
    count: usize,
) {
    use crate::editor::CursorScrollTarget;
    let row = ed.cursor().0;
    match ch {
        'z' => {
            ed.scroll_cursor_to(CursorScrollTarget::Center);
            ed.vim.viewport_pinned = true;
        }
        't' => {
            ed.scroll_cursor_to(CursorScrollTarget::Top);
            ed.vim.viewport_pinned = true;
        }
        'b' => {
            ed.scroll_cursor_to(CursorScrollTarget::Bottom);
            ed.vim.viewport_pinned = true;
        }
        // Folds — operate on the fold under the cursor (or the
        // whole buffer for `R` / `M`). Routed through
        // [`Editor::apply_fold_op`] (0.0.38 Patch C-δ.4) so the host
        // can observe / veto each op via [`Editor::take_fold_ops`].
        'o' => {
            ed.apply_fold_op(crate::types::FoldOp::OpenAt(row));
        }
        'c' => {
            ed.apply_fold_op(crate::types::FoldOp::CloseAt(row));
        }
        'a' => {
            ed.apply_fold_op(crate::types::FoldOp::ToggleAt(row));
        }
        'R' => {
            ed.apply_fold_op(crate::types::FoldOp::OpenAll);
        }
        'M' => {
            ed.apply_fold_op(crate::types::FoldOp::CloseAll);
        }
        'E' => {
            ed.apply_fold_op(crate::types::FoldOp::ClearAll);
        }
        'd' => {
            ed.apply_fold_op(crate::types::FoldOp::RemoveAt(row));
        }
        'f' => {
            if matches!(
                ed.vim.mode,
                Mode::Visual | Mode::VisualLine | Mode::VisualBlock
            ) {
                // `zf` over a Visual selection creates a fold spanning
                // anchor → cursor.
                let anchor_row = match ed.vim.mode {
                    Mode::VisualLine => ed.vim.visual_line_anchor,
                    Mode::VisualBlock => ed.vim.block_anchor.0,
                    _ => ed.vim.visual_anchor.0,
                };
                let cur = ed.cursor().0;
                let top = anchor_row.min(cur);
                let bot = anchor_row.max(cur);
                ed.apply_fold_op(crate::types::FoldOp::Add {
                    start_row: top,
                    end_row: bot,
                    closed: true,
                });
                ed.vim.mode = Mode::Normal;
            } else {
                // `zf{motion}` / `zf{textobj}` — route through the
                // operator pipeline. `Operator::Fold` reuses every
                // motion / text-object / `g`-prefix branch the other
                // operators get.
                ed.vim.pending = Pending::Op {
                    op: Operator::Fold,
                    count1: count,
                };
            }
        }
        _ => {}
    }
}

/// Public(crate) entry point for bare `f<x>` / `F<x>` / `t<x>` / `T<x>`.
/// Applies the motion and records `last_find` for `;` / `,` repeat.
/// Called by `Editor::find_char` (the public controller API) so the
/// hjkl-vim pending-state reducer can dispatch `FindChar` without
/// re-entering the FSM.
pub(crate) fn apply_find_char<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    ch: char,
    forward: bool,
    till: bool,
    count: usize,
) {
    execute_motion(ed, Motion::Find { ch, forward, till }, count.max(1));
    ed.vim.last_find = Some((ch, forward, till));
}

/// Public(crate) entry: apply operator over a find motion (`df<x>` etc.).
/// Called by `Editor::apply_op_find` (the public controller API) so the
/// hjkl-vim `PendingState::OpFind` reducer can dispatch `ApplyOpFind` without
/// re-entering the FSM. `handle_op_find_target` now delegates here to avoid
/// logic duplication.
pub(crate) fn apply_op_find_motion<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    op: Operator,
    ch: char,
    forward: bool,
    till: bool,
    total_count: usize,
) {
    let motion = Motion::Find { ch, forward, till };
    apply_op_with_motion(ed, op, &motion, total_count);
    ed.vim.last_find = Some((ch, forward, till));
    if !ed.vim.replaying && op_is_change(op) {
        ed.vim.last_change = Some(LastChange::OpMotion {
            op,
            motion,
            count: total_count,
            inserted: None,
        });
    }
}

/// Shared implementation: map `ch` to `TextObject`, apply the operator, and
/// record `last_change`. Returns `false` when `ch` is not a known text-object
/// kind (caller should treat as a no-op). Called by `Editor::apply_op_text_obj`
/// (the public controller API) so hjkl-vim can dispatch without re-entering the FSM.
///
/// `_total_count` is accepted for API symmetry with `apply_op_find_motion` /
/// `apply_op_motion_key` but is currently unused — text objects don't repeat
/// in vim's current grammar. Kept for future-proofing.
pub(crate) fn apply_op_text_obj_inner<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    op: Operator,
    ch: char,
    inner: bool,
    _total_count: usize,
) -> bool {
    // total_count unused — text objects don't repeat in vim's current grammar.
    // Kept for API symmetry with apply_op_motion / apply_op_find.
    let obj = match ch {
        'w' => TextObject::Word { big: false },
        'W' => TextObject::Word { big: true },
        '"' | '\'' | '`' => TextObject::Quote(ch),
        '(' | ')' | 'b' => TextObject::Bracket('('),
        '[' | ']' => TextObject::Bracket('['),
        '{' | '}' | 'B' => TextObject::Bracket('{'),
        '<' | '>' => TextObject::Bracket('<'),
        'p' => TextObject::Paragraph,
        't' => TextObject::XmlTag,
        's' => TextObject::Sentence,
        _ => return false,
    };
    apply_op_with_text_object(ed, op, obj, inner);
    if !ed.vim.replaying && op_is_change(op) {
        ed.vim.last_change = Some(LastChange::OpTextObj {
            op,
            obj,
            inner,
            inserted: None,
        });
    }
    true
}

/// Move `pos` back by one character, clamped to (0, 0).
pub(crate) fn retreat_one<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
    pos: (usize, usize),
) -> (usize, usize) {
    let (r, c) = pos;
    if c > 0 {
        (r, c - 1)
    } else if r > 0 {
        let prev_len = buf_line_bytes(&ed.buffer, r - 1);
        (r - 1, prev_len)
    } else {
        (0, 0)
    }
}

/// Variant of begin_insert that doesn't push_undo (caller already did).
fn begin_insert_noundo<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    count: usize,
    reason: InsertReason,
) {
    let reason = if ed.vim.replaying {
        InsertReason::ReplayOnly
    } else {
        reason
    };
    let (row, _) = ed.cursor();
    ed.vim.insert_session = Some(InsertSession {
        count,
        row_min: row,
        row_max: row,
        before_lines: buf_lines_to_vec(&ed.buffer),
        reason,
    });
    ed.vim.mode = Mode::Insert;
    // Phase 6.3: keep current_mode in sync for callers that bypass step().
    ed.vim.current_mode = crate::VimMode::Insert;
}

// ─── Operator × Motion application ─────────────────────────────────────────

pub(crate) fn apply_op_with_motion<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    op: Operator,
    motion: &Motion,
    count: usize,
) {
    let start = ed.cursor();
    // Tentatively apply motion to find the endpoint. Operator context
    // so `l` on the last char advances past-last (standard vim
    // exclusive-motion endpoint behaviour), enabling `dl` / `cl` /
    // `yl` to cover the final char.
    apply_motion_cursor_ctx(ed, motion, count, true);
    let end = ed.cursor();
    let kind = motion_kind(motion);
    // Restore cursor before selecting (so Yank leaves cursor at start).
    ed.jump_cursor(start.0, start.1);
    run_operator_over_range(ed, op, start, end, kind);
}

fn apply_op_with_text_object<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    op: Operator,
    obj: TextObject,
    inner: bool,
) {
    let Some((start, end, kind)) = text_object_range(ed, obj, inner) else {
        return;
    };
    ed.jump_cursor(start.0, start.1);
    run_operator_over_range(ed, op, start, end, kind);
}

fn motion_kind(motion: &Motion) -> RangeKind {
    match motion {
        Motion::Up | Motion::Down | Motion::ScreenUp | Motion::ScreenDown => RangeKind::Linewise,
        Motion::FileTop | Motion::FileBottom => RangeKind::Linewise,
        Motion::ViewportTop | Motion::ViewportMiddle | Motion::ViewportBottom => {
            RangeKind::Linewise
        }
        Motion::WordEnd | Motion::BigWordEnd | Motion::WordEndBack | Motion::BigWordEndBack => {
            RangeKind::Inclusive
        }
        Motion::Find { .. } => RangeKind::Inclusive,
        Motion::MatchBracket => RangeKind::Inclusive,
        // `$` now lands on the last char — operator ranges include it.
        Motion::LineEnd => RangeKind::Inclusive,
        _ => RangeKind::Exclusive,
    }
}

fn run_operator_over_range<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    op: Operator,
    start: (usize, usize),
    end: (usize, usize),
    kind: RangeKind,
) {
    let (top, bot) = order(start, end);
    // Charwise empty range (same position) — nothing to act on. For Linewise
    // the range `top == bot` means "operate on this one line" which is
    // perfectly valid (e.g. `Vd` on a single-line VisualLine selection).
    if top == bot && !matches!(kind, RangeKind::Linewise) {
        return;
    }

    match op {
        Operator::Yank => {
            let text = read_vim_range(ed, top, bot, kind);
            if !text.is_empty() {
                ed.record_yank_to_host(text.clone());
                ed.record_yank(text, matches!(kind, RangeKind::Linewise));
            }
            // Vim `:h '[` / `:h ']`: after a yank `[` = first yanked char,
            // `]` = last yanked char. Mode-aware: linewise snaps to line
            // edges; charwise uses the actual inclusive endpoint.
            let rbr = match kind {
                RangeKind::Linewise => {
                    let last_col = buf_line_chars(&ed.buffer, bot.0).saturating_sub(1);
                    (bot.0, last_col)
                }
                RangeKind::Inclusive => (bot.0, bot.1),
                RangeKind::Exclusive => (bot.0, bot.1.saturating_sub(1)),
            };
            ed.set_mark('[', top);
            ed.set_mark(']', rbr);
            buf_set_cursor_rc(&mut ed.buffer, top.0, top.1);
            ed.push_buffer_cursor_to_textarea();
        }
        Operator::Delete => {
            ed.push_undo();
            cut_vim_range(ed, top, bot, kind);
            // After a charwise / inclusive delete the buffer cursor is
            // placed at `start` by the edit path. In Normal mode the
            // cursor max col is `line_len - 1`; clamp it here so e.g.
            // `d$` doesn't leave the cursor one past the new line end.
            if !matches!(kind, RangeKind::Linewise) {
                clamp_cursor_to_normal_mode(ed);
            }
            ed.vim.mode = Mode::Normal;
            // Vim `:h '[` / `:h ']`: after a delete both marks park at
            // the cursor position where the deletion collapsed (the join
            // point). Set after the cut and clamp so the position is final.
            let pos = ed.cursor();
            ed.set_mark('[', pos);
            ed.set_mark(']', pos);
        }
        Operator::Change => {
            // Vim `:h '[`: `[` is set to the start of the changed range
            // before the cut. `]` is deferred to insert-exit (AfterChange
            // path in finish_insert_session) where the cursor sits on the
            // last inserted char.
            ed.vim.change_mark_start = Some(top);
            ed.push_undo();
            cut_vim_range(ed, top, bot, kind);
            begin_insert_noundo(ed, 1, InsertReason::AfterChange);
        }
        Operator::Uppercase | Operator::Lowercase | Operator::ToggleCase => {
            apply_case_op_to_selection(ed, op, top, bot, kind);
        }
        Operator::Indent | Operator::Outdent => {
            // Indent / outdent are always linewise even when triggered
            // by a char-wise motion (e.g. `>w` indents the whole line).
            ed.push_undo();
            if op == Operator::Indent {
                indent_rows(ed, top.0, bot.0, 1);
            } else {
                outdent_rows(ed, top.0, bot.0, 1);
            }
            ed.vim.mode = Mode::Normal;
        }
        Operator::Fold => {
            // Always linewise — fold the spanned rows regardless of the
            // motion's natural kind. Cursor lands on `top.0` to mirror
            // the visual `zf` path.
            if bot.0 >= top.0 {
                ed.apply_fold_op(crate::types::FoldOp::Add {
                    start_row: top.0,
                    end_row: bot.0,
                    closed: true,
                });
            }
            buf_set_cursor_rc(&mut ed.buffer, top.0, top.1);
            ed.push_buffer_cursor_to_textarea();
            ed.vim.mode = Mode::Normal;
        }
        Operator::Reflow => {
            ed.push_undo();
            reflow_rows(ed, top.0, bot.0);
            ed.vim.mode = Mode::Normal;
        }
    }
}

// ─── Phase 4a pub range-mutation bridges ───────────────────────────────────
//
// These are `pub(crate)` entry points called by the five new pub methods on
// `Editor` (`delete_range`, `yank_range`, `change_range`, `indent_range`,
// `case_range`). They set `pending_register` from the caller-supplied char
// before delegating to the existing internal helpers so register semantics
// (unnamed `"`, named `"a`–`"z`, delete ring) are honoured exactly as in the
// FSM path.
//
// Do NOT call `run_operator_over_range` for Indent/Outdent or the three case
// operators — those share the FSM path but have dedicated parameter shapes
// (signed count, Operator-as-CaseOp) that map more cleanly to their own
// helpers.

/// Delete the range `[start, end)` (interpretation determined by `kind`) and
/// stash the deleted text in `register`. `'"'` is the unnamed register.
pub(crate) fn delete_range_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    start: (usize, usize),
    end: (usize, usize),
    kind: RangeKind,
    register: char,
) {
    ed.vim.pending_register = Some(register);
    run_operator_over_range(ed, Operator::Delete, start, end, kind);
}

/// Yank (copy) the range `[start, end)` into `register` without mutating the
/// buffer. `'"'` is the unnamed register.
pub(crate) fn yank_range_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    start: (usize, usize),
    end: (usize, usize),
    kind: RangeKind,
    register: char,
) {
    ed.vim.pending_register = Some(register);
    run_operator_over_range(ed, Operator::Yank, start, end, kind);
}

/// Delete the range `[start, end)` and enter Insert mode (vim `c` operator).
/// The deleted text is stashed in `register`. Mode transitions to Insert on
/// return; the caller must not issue further normal-mode ops until the insert
/// session ends.
pub(crate) fn change_range_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    start: (usize, usize),
    end: (usize, usize),
    kind: RangeKind,
    register: char,
) {
    ed.vim.pending_register = Some(register);
    run_operator_over_range(ed, Operator::Change, start, end, kind);
}

/// Indent (`count > 0`) or outdent (`count < 0`) the row span `[start.0,
/// end.0]`. `shiftwidth` overrides the editor's `settings().shiftwidth` for
/// this call; pass `0` to use the editor setting. The column parts of `start`
/// / `end` are ignored — indent is always linewise.
pub(crate) fn indent_range_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    start: (usize, usize),
    end: (usize, usize),
    count: i32,
    shiftwidth: u32,
) {
    if count == 0 {
        return;
    }
    let (top_row, bot_row) = if start.0 <= end.0 {
        (start.0, end.0)
    } else {
        (end.0, start.0)
    };
    // Temporarily override shiftwidth when the caller provides one.
    let original_sw = ed.settings().shiftwidth;
    if shiftwidth > 0 {
        ed.settings_mut().shiftwidth = shiftwidth as usize;
    }
    ed.push_undo();
    let abs_count = count.unsigned_abs() as usize;
    if count > 0 {
        indent_rows(ed, top_row, bot_row, abs_count);
    } else {
        outdent_rows(ed, top_row, bot_row, abs_count);
    }
    if shiftwidth > 0 {
        ed.settings_mut().shiftwidth = original_sw;
    }
    ed.vim.mode = Mode::Normal;
}

/// Apply a case transformation (`Uppercase` / `Lowercase` / `ToggleCase`) to
/// the range `[start, end)`. Only the three case `Operator` variants are valid;
/// other variants are silently ignored (no-op).
pub(crate) fn case_range_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    start: (usize, usize),
    end: (usize, usize),
    kind: RangeKind,
    op: Operator,
) {
    match op {
        Operator::Uppercase | Operator::Lowercase | Operator::ToggleCase => {}
        _ => return,
    }
    let (top, bot) = order(start, end);
    apply_case_op_to_selection(ed, op, top, bot, kind);
}

// ─── Phase 4e pub block-shape range-mutation bridges ───────────────────────
//
// These are `pub(crate)` entry points called by the four new pub methods on
// `Editor` (`delete_block`, `yank_block`, `change_block`, `indent_block`).
// They set `pending_register` from the caller-supplied char then delegate to
// `apply_block_operator` (after temporarily installing the 4-corner block as
// the engine's virtual VisualBlock selection). The editor's VisualBlock state
// fields (`block_anchor`, `block_vcol`) are overwritten, the op fires, then
// the fields are restored to their pre-call values. This ensures the engine's
// register / undo / mode semantics are exercised without requiring the caller
// to already be in VisualBlock mode.
//
// `indent_block` is a separate helper — it does not use `apply_block_operator`
// because indent/outdent are always linewise for blocks (vim behaviour).

/// Delete a rectangular VisualBlock selection. `top_row`/`bot_row` are
/// inclusive line bounds; `left_col`/`right_col` are inclusive char-column
/// bounds. Short lines that don't reach `right_col` lose only the chars
/// that exist (ragged-edge, matching engine FSM). `register` is honoured;
/// `'"'` selects the unnamed register.
pub(crate) fn delete_block_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    top_row: usize,
    bot_row: usize,
    left_col: usize,
    right_col: usize,
    register: char,
) {
    ed.vim.pending_register = Some(register);
    let saved_anchor = ed.vim.block_anchor;
    let saved_vcol = ed.vim.block_vcol;
    ed.vim.block_anchor = (top_row, left_col);
    ed.vim.block_vcol = right_col;
    // Compute clamped col before the mutable borrow for buf_set_cursor_rc.
    let clamped = right_col.min(buf_line_chars(&ed.buffer, bot_row).saturating_sub(1));
    // Place cursor at bot_row / right_col so block_bounds resolves correctly.
    buf_set_cursor_rc(&mut ed.buffer, bot_row, clamped);
    apply_block_operator(ed, Operator::Delete);
    // Restore — block_anchor/vcol are only meaningful in VisualBlock mode;
    // after the op we're in Normal so restoring is a no-op for the user but
    // keeps state coherent if the caller inspects fields.
    ed.vim.block_anchor = saved_anchor;
    ed.vim.block_vcol = saved_vcol;
}

/// Yank a rectangular VisualBlock selection into `register`.
pub(crate) fn yank_block_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    top_row: usize,
    bot_row: usize,
    left_col: usize,
    right_col: usize,
    register: char,
) {
    ed.vim.pending_register = Some(register);
    let saved_anchor = ed.vim.block_anchor;
    let saved_vcol = ed.vim.block_vcol;
    ed.vim.block_anchor = (top_row, left_col);
    ed.vim.block_vcol = right_col;
    let clamped = right_col.min(buf_line_chars(&ed.buffer, bot_row).saturating_sub(1));
    buf_set_cursor_rc(&mut ed.buffer, bot_row, clamped);
    apply_block_operator(ed, Operator::Yank);
    ed.vim.block_anchor = saved_anchor;
    ed.vim.block_vcol = saved_vcol;
}

/// Delete a rectangular VisualBlock selection and enter Insert mode (`c`).
/// The deleted text is stashed in `register`. Mode is Insert on return.
pub(crate) fn change_block_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    top_row: usize,
    bot_row: usize,
    left_col: usize,
    right_col: usize,
    register: char,
) {
    ed.vim.pending_register = Some(register);
    let saved_anchor = ed.vim.block_anchor;
    let saved_vcol = ed.vim.block_vcol;
    ed.vim.block_anchor = (top_row, left_col);
    ed.vim.block_vcol = right_col;
    let clamped = right_col.min(buf_line_chars(&ed.buffer, bot_row).saturating_sub(1));
    buf_set_cursor_rc(&mut ed.buffer, bot_row, clamped);
    apply_block_operator(ed, Operator::Change);
    ed.vim.block_anchor = saved_anchor;
    ed.vim.block_vcol = saved_vcol;
}

/// Indent (`count > 0`) or outdent (`count < 0`) rows `top_row..=bot_row`.
/// Column bounds are ignored — vim's block indent is always linewise.
/// `count == 0` is a no-op.
pub(crate) fn indent_block_bridge<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    top_row: usize,
    bot_row: usize,
    count: i32,
) {
    if count == 0 {
        return;
    }
    ed.push_undo();
    let abs = count.unsigned_abs() as usize;
    if count > 0 {
        indent_rows(ed, top_row, bot_row, abs);
    } else {
        outdent_rows(ed, top_row, bot_row, abs);
    }
    ed.vim.mode = Mode::Normal;
}

// ─── Phase 4b pub text-object resolution bridges ───────────────────────────
//
// These are `pub(crate)` entry points called by the four new pub methods on
// `Editor` (`text_object_inner_word`, `text_object_around_word`,
// `text_object_inner_big_word`, `text_object_around_big_word`). They delegate
// to `word_text_object` — the existing private resolver — without touching any
// operator, register, or mode state. Pure functions: only `&Editor` required.

/// Resolve the range of `iw` (inner word) at the current cursor position.
/// Returns `None` if no word exists at the cursor.
pub(crate) fn text_object_inner_word_bridge<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
) -> Option<((usize, usize), (usize, usize))> {
    word_text_object(ed, true, false)
}

/// Resolve the range of `aw` (around word) at the current cursor position.
/// Includes trailing whitespace (or leading whitespace if no trailing exists).
pub(crate) fn text_object_around_word_bridge<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
) -> Option<((usize, usize), (usize, usize))> {
    word_text_object(ed, false, false)
}

/// Resolve the range of `iW` (inner WORD) at the current cursor position.
/// A WORD is any run of non-whitespace characters (no punctuation splitting).
pub(crate) fn text_object_inner_big_word_bridge<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
) -> Option<((usize, usize), (usize, usize))> {
    word_text_object(ed, true, true)
}

/// Resolve the range of `aW` (around WORD) at the current cursor position.
/// Includes trailing whitespace (or leading whitespace if no trailing exists).
pub(crate) fn text_object_around_big_word_bridge<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
) -> Option<((usize, usize), (usize, usize))> {
    word_text_object(ed, false, true)
}

// ─── Phase 4c pub text-object resolution bridges (quote + bracket) ──────────
//
// `pub(crate)` entry points called by the four new pub methods on `Editor`
// (`text_object_inner_quote`, `text_object_around_quote`,
// `text_object_inner_bracket`, `text_object_around_bracket`). They delegate to
// `quote_text_object` / `bracket_text_object` — the existing private resolvers
// — without touching any operator, register, or mode state.
//
// `bracket_text_object` returns `Option<(Pos, Pos, RangeKind)>`; the bridges
// strip the `RangeKind` tag so callers see a uniform
// `Option<((usize,usize),(usize,usize))>` shape, consistent with 4b.

/// Resolve the range of `i<quote>` (inner quote) at the current cursor
/// position. `quote` is one of `'"'`, `'\''`, or `` '`' ``. Returns `None`
/// when the cursor's line contains fewer than two occurrences of `quote`.
pub(crate) fn text_object_inner_quote_bridge<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
    quote: char,
) -> Option<((usize, usize), (usize, usize))> {
    quote_text_object(ed, quote, true)
}

/// Resolve the range of `a<quote>` (around quote) at the current cursor
/// position. Includes surrounding whitespace on one side per vim semantics.
pub(crate) fn text_object_around_quote_bridge<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
    quote: char,
) -> Option<((usize, usize), (usize, usize))> {
    quote_text_object(ed, quote, false)
}

/// Resolve the range of `i<bracket>` (inner bracket pair). `open` must be
/// one of `'('`, `'{'`, `'['`, `'<'`; the corresponding close is derived
/// internally. Returns `None` when no enclosing pair is found. The returned
/// range excludes the bracket characters themselves. Multi-line bracket pairs
/// whose content spans more than one line are reported as a charwise range
/// covering the first content character through the last content character
/// (RangeKind metadata is stripped — callers receive start/end only).
pub(crate) fn text_object_inner_bracket_bridge<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
    open: char,
) -> Option<((usize, usize), (usize, usize))> {
    bracket_text_object(ed, open, true).map(|(s, e, _kind)| (s, e))
}

/// Resolve the range of `a<bracket>` (around bracket pair). Includes the
/// bracket characters themselves. `open` must be one of `'('`, `'{'`, `'['`,
/// `'<'`.
pub(crate) fn text_object_around_bracket_bridge<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
    open: char,
) -> Option<((usize, usize), (usize, usize))> {
    bracket_text_object(ed, open, false).map(|(s, e, _kind)| (s, e))
}

// ── Sentence bridges (is / as) ─────────────────────────────────────────────

/// Resolve the range of `is` (inner sentence) at the cursor. Excludes
/// trailing whitespace.
pub(crate) fn text_object_inner_sentence_bridge<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
) -> Option<((usize, usize), (usize, usize))> {
    sentence_text_object(ed, true)
}

/// Resolve the range of `as` (around sentence) at the cursor. Includes
/// trailing whitespace.
pub(crate) fn text_object_around_sentence_bridge<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
) -> Option<((usize, usize), (usize, usize))> {
    sentence_text_object(ed, false)
}

// ── Paragraph bridges (ip / ap) ────────────────────────────────────────────

/// Resolve the range of `ip` (inner paragraph) at the cursor. A paragraph
/// is a block of non-blank lines bounded by blank lines or buffer edges.
pub(crate) fn text_object_inner_paragraph_bridge<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
) -> Option<((usize, usize), (usize, usize))> {
    paragraph_text_object(ed, true)
}

/// Resolve the range of `ap` (around paragraph) at the cursor. Includes one
/// trailing blank line when present.
pub(crate) fn text_object_around_paragraph_bridge<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
) -> Option<((usize, usize), (usize, usize))> {
    paragraph_text_object(ed, false)
}

// ── Tag bridges (it / at) ──────────────────────────────────────────────────

/// Resolve the range of `it` (inner tag) at the cursor. Matches XML/HTML-style
/// `<tag>...</tag>` pairs; returns the range of inner content between the open
/// and close tags.
pub(crate) fn text_object_inner_tag_bridge<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
) -> Option<((usize, usize), (usize, usize))> {
    tag_text_object(ed, true)
}

/// Resolve the range of `at` (around tag) at the cursor. Includes the open
/// and close tag delimiters themselves.
pub(crate) fn text_object_around_tag_bridge<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
) -> Option<((usize, usize), (usize, usize))> {
    tag_text_object(ed, false)
}

/// Greedy word-wrap the rows in `[top, bot]` to `settings.textwidth`.
/// Splits on blank-line boundaries so paragraph structure is
/// preserved. Each paragraph's words are joined with single spaces
/// before re-wrapping.
fn reflow_rows<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    top: usize,
    bot: usize,
) {
    let width = ed.settings().textwidth.max(1);
    let mut lines: Vec<String> = buf_lines_to_vec(&ed.buffer);
    let bot = bot.min(lines.len().saturating_sub(1));
    if top > bot {
        return;
    }
    let original = lines[top..=bot].to_vec();
    let mut wrapped: Vec<String> = Vec::new();
    let mut paragraph: Vec<String> = Vec::new();
    let flush = |para: &mut Vec<String>, out: &mut Vec<String>, width: usize| {
        if para.is_empty() {
            return;
        }
        let words = para.join(" ");
        let mut current = String::new();
        for word in words.split_whitespace() {
            let extra = if current.is_empty() {
                word.chars().count()
            } else {
                current.chars().count() + 1 + word.chars().count()
            };
            if extra > width && !current.is_empty() {
                out.push(std::mem::take(&mut current));
                current.push_str(word);
            } else if current.is_empty() {
                current.push_str(word);
            } else {
                current.push(' ');
                current.push_str(word);
            }
        }
        if !current.is_empty() {
            out.push(current);
        }
        para.clear();
    };
    for line in &original {
        if line.trim().is_empty() {
            flush(&mut paragraph, &mut wrapped, width);
            wrapped.push(String::new());
        } else {
            paragraph.push(line.clone());
        }
    }
    flush(&mut paragraph, &mut wrapped, width);

    // Splice back. push_undo above means `u` reverses.
    let after: Vec<String> = lines.split_off(bot + 1);
    lines.truncate(top);
    lines.extend(wrapped);
    lines.extend(after);
    ed.restore(lines, (top, 0));
    ed.mark_content_dirty();
}

/// Transform the range `[top, bot]` (vim `RangeKind`) in place with
/// the given case operator. Cursor lands on `top` afterward — vim
/// convention for `gU{motion}` / `gu{motion}` / `g~{motion}`.
/// Preserves the textarea yank buffer (vim's case operators don't
/// touch registers).
fn apply_case_op_to_selection<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    op: Operator,
    top: (usize, usize),
    bot: (usize, usize),
    kind: RangeKind,
) {
    use hjkl_buffer::Edit;
    ed.push_undo();
    let saved_yank = ed.yank().to_string();
    let saved_yank_linewise = ed.vim.yank_linewise;
    let selection = cut_vim_range(ed, top, bot, kind);
    let transformed = match op {
        Operator::Uppercase => selection.to_uppercase(),
        Operator::Lowercase => selection.to_lowercase(),
        Operator::ToggleCase => toggle_case_str(&selection),
        _ => unreachable!(),
    };
    if !transformed.is_empty() {
        let cursor = buf_cursor_pos(&ed.buffer);
        ed.mutate_edit(Edit::InsertStr {
            at: cursor,
            text: transformed,
        });
    }
    buf_set_cursor_rc(&mut ed.buffer, top.0, top.1);
    ed.push_buffer_cursor_to_textarea();
    ed.set_yank(saved_yank);
    ed.vim.yank_linewise = saved_yank_linewise;
    ed.vim.mode = Mode::Normal;
}

/// Prepend `count * shiftwidth` spaces to each row in `[top, bot]`.
/// Rows that are empty are skipped (vim leaves blank lines alone when
/// indenting). `shiftwidth` is read from `editor.settings()` so
/// `:set shiftwidth=N` takes effect on the next operation.
fn indent_rows<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    top: usize,
    bot: usize,
    count: usize,
) {
    ed.sync_buffer_content_from_textarea();
    let width = ed.settings().shiftwidth * count.max(1);
    let pad: String = " ".repeat(width);
    let mut lines: Vec<String> = buf_lines_to_vec(&ed.buffer);
    let bot = bot.min(lines.len().saturating_sub(1));
    for line in lines.iter_mut().take(bot + 1).skip(top) {
        if !line.is_empty() {
            line.insert_str(0, &pad);
        }
    }
    // Restore cursor to first non-blank of the top row so the next
    // vertical motion aims sensibly — matches vim's `>>` convention.
    ed.restore(lines, (top, 0));
    move_first_non_whitespace(ed);
}

/// Remove up to `count * shiftwidth` leading spaces (or tabs) from
/// each row in `[top, bot]`. Rows with less leading whitespace have
/// all their indent stripped, not clipped to zero length.
fn outdent_rows<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    top: usize,
    bot: usize,
    count: usize,
) {
    ed.sync_buffer_content_from_textarea();
    let width = ed.settings().shiftwidth * count.max(1);
    let mut lines: Vec<String> = buf_lines_to_vec(&ed.buffer);
    let bot = bot.min(lines.len().saturating_sub(1));
    for line in lines.iter_mut().take(bot + 1).skip(top) {
        let strip: usize = line
            .chars()
            .take(width)
            .take_while(|c| *c == ' ' || *c == '\t')
            .count();
        if strip > 0 {
            let byte_len: usize = line.chars().take(strip).map(|c| c.len_utf8()).sum();
            line.drain(..byte_len);
        }
    }
    ed.restore(lines, (top, 0));
    move_first_non_whitespace(ed);
}

fn toggle_case_str(s: &str) -> String {
    s.chars()
        .map(|c| {
            if c.is_lowercase() {
                c.to_uppercase().next().unwrap_or(c)
            } else if c.is_uppercase() {
                c.to_lowercase().next().unwrap_or(c)
            } else {
                c
            }
        })
        .collect()
}

fn order(a: (usize, usize), b: (usize, usize)) -> ((usize, usize), (usize, usize)) {
    if a <= b { (a, b) } else { (b, a) }
}

/// Clamp the buffer cursor to normal-mode valid position: col may not
/// exceed `line.chars().count().saturating_sub(1)` (or 0 on an empty
/// line). Vim applies this clamp on every return to Normal mode after an
/// operator or Esc-from-insert.
fn clamp_cursor_to_normal_mode<H: crate::types::Host>(ed: &mut Editor<hjkl_buffer::Buffer, H>) {
    let (row, col) = ed.cursor();
    let line_chars = buf_line_chars(&ed.buffer, row);
    let max_col = line_chars.saturating_sub(1);
    if col > max_col {
        buf_set_cursor_rc(&mut ed.buffer, row, max_col);
        ed.push_buffer_cursor_to_textarea();
    }
}

// ─── dd/cc/yy ──────────────────────────────────────────────────────────────

fn execute_line_op<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    op: Operator,
    count: usize,
) {
    let (row, col) = ed.cursor();
    let total = buf_row_count(&ed.buffer);
    let end_row = (row + count.saturating_sub(1)).min(total.saturating_sub(1));

    match op {
        Operator::Yank => {
            // yy must not move the cursor.
            let text = read_vim_range(ed, (row, col), (end_row, 0), RangeKind::Linewise);
            if !text.is_empty() {
                ed.record_yank_to_host(text.clone());
                ed.record_yank(text, true);
            }
            // Vim `:h '[` / `:h ']`: yy/Nyy — linewise yank; `[` =
            // (top_row, 0), `]` = (bot_row, last_col).
            let last_col = buf_line_chars(&ed.buffer, end_row).saturating_sub(1);
            ed.set_mark('[', (row, 0));
            ed.set_mark(']', (end_row, last_col));
            buf_set_cursor_rc(&mut ed.buffer, row, col);
            ed.push_buffer_cursor_to_textarea();
            ed.vim.mode = Mode::Normal;
        }
        Operator::Delete => {
            ed.push_undo();
            let deleted_through_last = end_row + 1 >= total;
            cut_vim_range(ed, (row, col), (end_row, 0), RangeKind::Linewise);
            // Vim's `dd` / `Ndd` leaves the cursor on the *first
            // non-blank* of the line that now occupies `row` — or, if
            // the deletion consumed the last line, the line above it.
            let total_after = buf_row_count(&ed.buffer);
            let raw_target = if deleted_through_last {
                row.saturating_sub(1).min(total_after.saturating_sub(1))
            } else {
                row.min(total_after.saturating_sub(1))
            };
            // Clamp off the trailing phantom empty row that arises from a
            // buffer with a trailing newline (stored as ["...", ""]). If
            // the target row is the trailing empty row and there is a real
            // content row above it, use that instead — matching vim's view
            // that the trailing `\n` is a terminator, not a separator.
            let target_row = if raw_target > 0
                && raw_target + 1 == total_after
                && buf_line(&ed.buffer, raw_target)
                    .map(str::is_empty)
                    .unwrap_or(false)
            {
                raw_target - 1
            } else {
                raw_target
            };
            buf_set_cursor_rc(&mut ed.buffer, target_row, 0);
            ed.push_buffer_cursor_to_textarea();
            move_first_non_whitespace(ed);
            ed.sticky_col = Some(ed.cursor().1);
            ed.vim.mode = Mode::Normal;
            // Vim `:h '[` / `:h ']`: dd/Ndd — both marks park at the
            // post-delete cursor position (the join point).
            let pos = ed.cursor();
            ed.set_mark('[', pos);
            ed.set_mark(']', pos);
        }
        Operator::Change => {
            // `cc` / `3cc`: wipe contents of the covered lines but leave
            // a single blank line so insert-mode opens on it. Done as two
            // edits: drop rows past the first, then clear row `row`.
            use hjkl_buffer::{Edit, MotionKind as BufKind, Position};
            // Vim `:h '[`: stash change start for `]` deferral on insert-exit.
            ed.vim.change_mark_start = Some((row, 0));
            ed.push_undo();
            ed.sync_buffer_content_from_textarea();
            // Read the cut payload first so yank reflects every line.
            let payload = read_vim_range(ed, (row, col), (end_row, 0), RangeKind::Linewise);
            if end_row > row {
                ed.mutate_edit(Edit::DeleteRange {
                    start: Position::new(row + 1, 0),
                    end: Position::new(end_row, 0),
                    kind: BufKind::Line,
                });
            }
            let line_chars = buf_line_chars(&ed.buffer, row);
            if line_chars > 0 {
                ed.mutate_edit(Edit::DeleteRange {
                    start: Position::new(row, 0),
                    end: Position::new(row, line_chars),
                    kind: BufKind::Char,
                });
            }
            if !payload.is_empty() {
                ed.record_yank_to_host(payload.clone());
                ed.record_delete(payload, true);
            }
            buf_set_cursor_rc(&mut ed.buffer, row, 0);
            ed.push_buffer_cursor_to_textarea();
            begin_insert_noundo(ed, 1, InsertReason::AfterChange);
        }
        Operator::Uppercase | Operator::Lowercase | Operator::ToggleCase => {
            // `gUU` / `guu` / `g~~` — linewise case transform over
            // [row, end_row]. Preserve cursor on `row` (first non-blank
            // lines up with vim's behaviour).
            apply_case_op_to_selection(ed, op, (row, col), (end_row, 0), RangeKind::Linewise);
            // After case-op on a linewise range vim puts the cursor on
            // the first non-blank of the starting line.
            move_first_non_whitespace(ed);
        }
        Operator::Indent | Operator::Outdent => {
            // `>>` / `N>>` / `<<` / `N<<` — linewise indent / outdent.
            ed.push_undo();
            if op == Operator::Indent {
                indent_rows(ed, row, end_row, 1);
            } else {
                outdent_rows(ed, row, end_row, 1);
            }
            ed.sticky_col = Some(ed.cursor().1);
            ed.vim.mode = Mode::Normal;
        }
        // No doubled form — `zfzf` is two consecutive `zf` chords.
        Operator::Fold => unreachable!("Fold has no line-op double"),
        Operator::Reflow => {
            // `gqq` / `Ngqq` — reflow `count` rows starting at the cursor.
            ed.push_undo();
            reflow_rows(ed, row, end_row);
            move_first_non_whitespace(ed);
            ed.sticky_col = Some(ed.cursor().1);
            ed.vim.mode = Mode::Normal;
        }
    }
}

// ─── Visual mode operators ─────────────────────────────────────────────────

pub(crate) fn apply_visual_operator<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    op: Operator,
) {
    match ed.vim.mode {
        Mode::VisualLine => {
            let cursor_row = buf_cursor_pos(&ed.buffer).row;
            let top = cursor_row.min(ed.vim.visual_line_anchor);
            let bot = cursor_row.max(ed.vim.visual_line_anchor);
            ed.vim.yank_linewise = true;
            match op {
                Operator::Yank => {
                    let text = read_vim_range(ed, (top, 0), (bot, 0), RangeKind::Linewise);
                    if !text.is_empty() {
                        ed.record_yank_to_host(text.clone());
                        ed.record_yank(text, true);
                    }
                    buf_set_cursor_rc(&mut ed.buffer, top, 0);
                    ed.push_buffer_cursor_to_textarea();
                    ed.vim.mode = Mode::Normal;
                }
                Operator::Delete => {
                    ed.push_undo();
                    cut_vim_range(ed, (top, 0), (bot, 0), RangeKind::Linewise);
                    ed.vim.mode = Mode::Normal;
                }
                Operator::Change => {
                    // Vim `Vc`: wipe the line contents but leave a blank
                    // line in place so insert-mode starts on an empty row.
                    use hjkl_buffer::{Edit, MotionKind as BufKind, Position};
                    ed.push_undo();
                    ed.sync_buffer_content_from_textarea();
                    let payload = read_vim_range(ed, (top, 0), (bot, 0), RangeKind::Linewise);
                    if bot > top {
                        ed.mutate_edit(Edit::DeleteRange {
                            start: Position::new(top + 1, 0),
                            end: Position::new(bot, 0),
                            kind: BufKind::Line,
                        });
                    }
                    let line_chars = buf_line_chars(&ed.buffer, top);
                    if line_chars > 0 {
                        ed.mutate_edit(Edit::DeleteRange {
                            start: Position::new(top, 0),
                            end: Position::new(top, line_chars),
                            kind: BufKind::Char,
                        });
                    }
                    if !payload.is_empty() {
                        ed.record_yank_to_host(payload.clone());
                        ed.record_delete(payload, true);
                    }
                    buf_set_cursor_rc(&mut ed.buffer, top, 0);
                    ed.push_buffer_cursor_to_textarea();
                    begin_insert_noundo(ed, 1, InsertReason::AfterChange);
                }
                Operator::Uppercase | Operator::Lowercase | Operator::ToggleCase => {
                    let bot = buf_cursor_pos(&ed.buffer)
                        .row
                        .max(ed.vim.visual_line_anchor);
                    apply_case_op_to_selection(ed, op, (top, 0), (bot, 0), RangeKind::Linewise);
                    move_first_non_whitespace(ed);
                }
                Operator::Indent | Operator::Outdent => {
                    ed.push_undo();
                    let (cursor_row, _) = ed.cursor();
                    let bot = cursor_row.max(ed.vim.visual_line_anchor);
                    if op == Operator::Indent {
                        indent_rows(ed, top, bot, 1);
                    } else {
                        outdent_rows(ed, top, bot, 1);
                    }
                    ed.vim.mode = Mode::Normal;
                }
                Operator::Reflow => {
                    ed.push_undo();
                    let (cursor_row, _) = ed.cursor();
                    let bot = cursor_row.max(ed.vim.visual_line_anchor);
                    reflow_rows(ed, top, bot);
                    ed.vim.mode = Mode::Normal;
                }
                // Visual `zf` is handled inline in `handle_after_z`,
                // never routed through this dispatcher.
                Operator::Fold => unreachable!("Visual zf takes its own path"),
            }
        }
        Mode::Visual => {
            ed.vim.yank_linewise = false;
            let anchor = ed.vim.visual_anchor;
            let cursor = ed.cursor();
            let (top, bot) = order(anchor, cursor);
            match op {
                Operator::Yank => {
                    let text = read_vim_range(ed, top, bot, RangeKind::Inclusive);
                    if !text.is_empty() {
                        ed.record_yank_to_host(text.clone());
                        ed.record_yank(text, false);
                    }
                    buf_set_cursor_rc(&mut ed.buffer, top.0, top.1);
                    ed.push_buffer_cursor_to_textarea();
                    ed.vim.mode = Mode::Normal;
                }
                Operator::Delete => {
                    ed.push_undo();
                    cut_vim_range(ed, top, bot, RangeKind::Inclusive);
                    ed.vim.mode = Mode::Normal;
                }
                Operator::Change => {
                    ed.push_undo();
                    cut_vim_range(ed, top, bot, RangeKind::Inclusive);
                    begin_insert_noundo(ed, 1, InsertReason::AfterChange);
                }
                Operator::Uppercase | Operator::Lowercase | Operator::ToggleCase => {
                    // Anchor stays where the visual selection started.
                    let anchor = ed.vim.visual_anchor;
                    let cursor = ed.cursor();
                    let (top, bot) = order(anchor, cursor);
                    apply_case_op_to_selection(ed, op, top, bot, RangeKind::Inclusive);
                }
                Operator::Indent | Operator::Outdent => {
                    ed.push_undo();
                    let anchor = ed.vim.visual_anchor;
                    let cursor = ed.cursor();
                    let (top, bot) = order(anchor, cursor);
                    if op == Operator::Indent {
                        indent_rows(ed, top.0, bot.0, 1);
                    } else {
                        outdent_rows(ed, top.0, bot.0, 1);
                    }
                    ed.vim.mode = Mode::Normal;
                }
                Operator::Reflow => {
                    ed.push_undo();
                    let anchor = ed.vim.visual_anchor;
                    let cursor = ed.cursor();
                    let (top, bot) = order(anchor, cursor);
                    reflow_rows(ed, top.0, bot.0);
                    ed.vim.mode = Mode::Normal;
                }
                Operator::Fold => unreachable!("Visual zf takes its own path"),
            }
        }
        Mode::VisualBlock => apply_block_operator(ed, op),
        _ => {}
    }
}

/// Compute `(top_row, bot_row, left_col, right_col)` for the current
/// VisualBlock selection. Columns are inclusive on both ends. Uses the
/// tracked virtual column (updated by h/l, preserved across j/k) so
/// ragged / empty rows don't collapse the block's width.
fn block_bounds<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
) -> (usize, usize, usize, usize) {
    let (ar, ac) = ed.vim.block_anchor;
    let (cr, _) = ed.cursor();
    let cc = ed.vim.block_vcol;
    let top = ar.min(cr);
    let bot = ar.max(cr);
    let left = ac.min(cc);
    let right = ac.max(cc);
    (top, bot, left, right)
}

/// Update the virtual column after a motion in VisualBlock mode.
/// Horizontal motions sync `block_vcol` to the new cursor column;
/// vertical / non-h/l motions leave it alone so the intended column
/// survives clamping to shorter lines.
pub(crate) fn update_block_vcol<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    motion: &Motion,
) {
    match motion {
        Motion::Left
        | Motion::Right
        | Motion::WordFwd
        | Motion::BigWordFwd
        | Motion::WordBack
        | Motion::BigWordBack
        | Motion::WordEnd
        | Motion::BigWordEnd
        | Motion::WordEndBack
        | Motion::BigWordEndBack
        | Motion::LineStart
        | Motion::FirstNonBlank
        | Motion::LineEnd
        | Motion::Find { .. }
        | Motion::FindRepeat { .. }
        | Motion::MatchBracket => {
            ed.vim.block_vcol = ed.cursor().1;
        }
        // Up / Down / FileTop / FileBottom / Search — preserve vcol.
        _ => {}
    }
}

/// Yank / delete / change / replace a rectangular selection. Yanked text
/// is stored as one string per row joined with `\n` so pasting reproduces
/// the block as sequential lines. (Vim's true block-paste reinserts as
/// columns; we render the content with our char-wise paste path.)
fn apply_block_operator<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    op: Operator,
) {
    let (top, bot, left, right) = block_bounds(ed);
    // Snapshot the block text for yank / clipboard.
    let yank = block_yank(ed, top, bot, left, right);

    match op {
        Operator::Yank => {
            if !yank.is_empty() {
                ed.record_yank_to_host(yank.clone());
                ed.record_yank(yank, false);
            }
            ed.vim.mode = Mode::Normal;
            ed.jump_cursor(top, left);
        }
        Operator::Delete => {
            ed.push_undo();
            delete_block_contents(ed, top, bot, left, right);
            if !yank.is_empty() {
                ed.record_yank_to_host(yank.clone());
                ed.record_delete(yank, false);
            }
            ed.vim.mode = Mode::Normal;
            ed.jump_cursor(top, left);
        }
        Operator::Change => {
            ed.push_undo();
            delete_block_contents(ed, top, bot, left, right);
            if !yank.is_empty() {
                ed.record_yank_to_host(yank.clone());
                ed.record_delete(yank, false);
            }
            ed.jump_cursor(top, left);
            begin_insert_noundo(
                ed,
                1,
                InsertReason::BlockChange {
                    top,
                    bot,
                    col: left,
                },
            );
        }
        Operator::Uppercase | Operator::Lowercase | Operator::ToggleCase => {
            ed.push_undo();
            transform_block_case(ed, op, top, bot, left, right);
            ed.vim.mode = Mode::Normal;
            ed.jump_cursor(top, left);
        }
        Operator::Indent | Operator::Outdent => {
            // VisualBlock `>` / `<` falls back to linewise indent over
            // the block's row range — vim does the same (column-wise
            // indent/outdent doesn't make sense).
            ed.push_undo();
            if op == Operator::Indent {
                indent_rows(ed, top, bot, 1);
            } else {
                outdent_rows(ed, top, bot, 1);
            }
            ed.vim.mode = Mode::Normal;
        }
        Operator::Fold => unreachable!("Visual zf takes its own path"),
        Operator::Reflow => {
            // Reflow over the block falls back to linewise reflow over
            // the row range — column slicing for `gq` doesn't make
            // sense.
            ed.push_undo();
            reflow_rows(ed, top, bot);
            ed.vim.mode = Mode::Normal;
        }
    }
}

/// In-place case transform over the rectangular block
/// `(top..=bot, left..=right)`. Rows shorter than `left` are left
/// untouched — vim behaves the same way (ragged blocks).
fn transform_block_case<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    op: Operator,
    top: usize,
    bot: usize,
    left: usize,
    right: usize,
) {
    let mut lines: Vec<String> = buf_lines_to_vec(&ed.buffer);
    for r in top..=bot.min(lines.len().saturating_sub(1)) {
        let chars: Vec<char> = lines[r].chars().collect();
        if left >= chars.len() {
            continue;
        }
        let end = (right + 1).min(chars.len());
        let head: String = chars[..left].iter().collect();
        let mid: String = chars[left..end].iter().collect();
        let tail: String = chars[end..].iter().collect();
        let transformed = match op {
            Operator::Uppercase => mid.to_uppercase(),
            Operator::Lowercase => mid.to_lowercase(),
            Operator::ToggleCase => toggle_case_str(&mid),
            _ => mid,
        };
        lines[r] = format!("{head}{transformed}{tail}");
    }
    let saved_yank = ed.yank().to_string();
    let saved_linewise = ed.vim.yank_linewise;
    ed.restore(lines, (top, left));
    ed.set_yank(saved_yank);
    ed.vim.yank_linewise = saved_linewise;
}

fn block_yank<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
    top: usize,
    bot: usize,
    left: usize,
    right: usize,
) -> String {
    let lines = buf_lines_to_vec(&ed.buffer);
    let mut rows: Vec<String> = Vec::new();
    for r in top..=bot {
        let line = match lines.get(r) {
            Some(l) => l,
            None => break,
        };
        let chars: Vec<char> = line.chars().collect();
        let end = (right + 1).min(chars.len());
        if left >= chars.len() {
            rows.push(String::new());
        } else {
            rows.push(chars[left..end].iter().collect());
        }
    }
    rows.join("\n")
}

fn delete_block_contents<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    top: usize,
    bot: usize,
    left: usize,
    right: usize,
) {
    use hjkl_buffer::{Edit, MotionKind, Position};
    ed.sync_buffer_content_from_textarea();
    let last_row = bot.min(buf_row_count(&ed.buffer).saturating_sub(1));
    if last_row < top {
        return;
    }
    ed.mutate_edit(Edit::DeleteRange {
        start: Position::new(top, left),
        end: Position::new(last_row, right),
        kind: MotionKind::Block,
    });
    ed.push_buffer_cursor_to_textarea();
}

/// Replace each character cell in the block with `ch`.
pub(crate) fn block_replace<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    ch: char,
) {
    let (top, bot, left, right) = block_bounds(ed);
    ed.push_undo();
    ed.sync_buffer_content_from_textarea();
    let mut lines: Vec<String> = buf_lines_to_vec(&ed.buffer);
    for r in top..=bot.min(lines.len().saturating_sub(1)) {
        let chars: Vec<char> = lines[r].chars().collect();
        if left >= chars.len() {
            continue;
        }
        let end = (right + 1).min(chars.len());
        let before: String = chars[..left].iter().collect();
        let middle: String = std::iter::repeat_n(ch, end - left).collect();
        let after: String = chars[end..].iter().collect();
        lines[r] = format!("{before}{middle}{after}");
    }
    reset_textarea_lines(ed, lines);
    ed.vim.mode = Mode::Normal;
    ed.jump_cursor(top, left);
}

/// Replace buffer content with `lines` while preserving the cursor.
/// Used by indent / outdent / block_replace to wholesale rewrite
/// rows without going through the per-edit funnel.
fn reset_textarea_lines<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    lines: Vec<String>,
) {
    let cursor = ed.cursor();
    crate::types::BufferEdit::replace_all(&mut ed.buffer, &lines.join("\n"));
    buf_set_cursor_rc(&mut ed.buffer, cursor.0, cursor.1);
    ed.mark_content_dirty();
}

// ─── Visual-line helpers ───────────────────────────────────────────────────

// ─── Text-object range computation ─────────────────────────────────────────

/// Cursor position as `(row, col)`.
type Pos = (usize, usize);

/// Returns `(start, end, kind)` where `end` is *exclusive* (one past the
/// last character to act on). `kind` is `Linewise` for line-oriented text
/// objects like paragraphs and `Exclusive` otherwise.
pub(crate) fn text_object_range<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
    obj: TextObject,
    inner: bool,
) -> Option<(Pos, Pos, RangeKind)> {
    match obj {
        TextObject::Word { big } => {
            word_text_object(ed, inner, big).map(|(s, e)| (s, e, RangeKind::Exclusive))
        }
        TextObject::Quote(q) => {
            quote_text_object(ed, q, inner).map(|(s, e)| (s, e, RangeKind::Exclusive))
        }
        TextObject::Bracket(open) => bracket_text_object(ed, open, inner),
        TextObject::Paragraph => {
            paragraph_text_object(ed, inner).map(|(s, e)| (s, e, RangeKind::Linewise))
        }
        TextObject::XmlTag => tag_text_object(ed, inner).map(|(s, e)| (s, e, RangeKind::Exclusive)),
        TextObject::Sentence => {
            sentence_text_object(ed, inner).map(|(s, e)| (s, e, RangeKind::Exclusive))
        }
    }
}

/// `(` / `)` — walk to the next sentence boundary in `forward` direction.
/// Returns `(row, col)` of the boundary's first non-whitespace cell, or
/// `None` when already at the buffer's edge in that direction.
fn sentence_boundary<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
    forward: bool,
) -> Option<(usize, usize)> {
    let lines = buf_lines_to_vec(&ed.buffer);
    if lines.is_empty() {
        return None;
    }
    let pos_to_idx = |pos: (usize, usize)| -> usize {
        let mut idx = 0;
        for line in lines.iter().take(pos.0) {
            idx += line.chars().count() + 1;
        }
        idx + pos.1
    };
    let idx_to_pos = |mut idx: usize| -> (usize, usize) {
        for (r, line) in lines.iter().enumerate() {
            let len = line.chars().count();
            if idx <= len {
                return (r, idx);
            }
            idx -= len + 1;
        }
        let last = lines.len().saturating_sub(1);
        (last, lines[last].chars().count())
    };
    let mut chars: Vec<char> = Vec::new();
    for (r, line) in lines.iter().enumerate() {
        chars.extend(line.chars());
        if r + 1 < lines.len() {
            chars.push('\n');
        }
    }
    if chars.is_empty() {
        return None;
    }
    let total = chars.len();
    let cursor_idx = pos_to_idx(ed.cursor()).min(total - 1);
    let is_terminator = |c: char| matches!(c, '.' | '?' | '!');

    if forward {
        // Walk forward looking for a terminator run followed by
        // whitespace; land on the first non-whitespace cell after.
        let mut i = cursor_idx + 1;
        while i < total {
            if is_terminator(chars[i]) {
                while i + 1 < total && is_terminator(chars[i + 1]) {
                    i += 1;
                }
                if i + 1 >= total {
                    return None;
                }
                if chars[i + 1].is_whitespace() {
                    let mut j = i + 1;
                    while j < total && chars[j].is_whitespace() {
                        j += 1;
                    }
                    if j >= total {
                        return None;
                    }
                    return Some(idx_to_pos(j));
                }
            }
            i += 1;
        }
        None
    } else {
        // Walk backward to find the start of the current sentence (if
        // we're already at the start, jump to the previous sentence's
        // start instead).
        let find_start = |from: usize| -> Option<usize> {
            let mut start = from;
            while start > 0 {
                let prev = chars[start - 1];
                if prev.is_whitespace() {
                    let mut k = start - 1;
                    while k > 0 && chars[k - 1].is_whitespace() {
                        k -= 1;
                    }
                    if k > 0 && is_terminator(chars[k - 1]) {
                        break;
                    }
                }
                start -= 1;
            }
            while start < total && chars[start].is_whitespace() {
                start += 1;
            }
            (start < total).then_some(start)
        };
        let current_start = find_start(cursor_idx)?;
        if current_start < cursor_idx {
            return Some(idx_to_pos(current_start));
        }
        // Already at the sentence start — step over the boundary into
        // the previous sentence and find its start.
        let mut k = current_start;
        while k > 0 && chars[k - 1].is_whitespace() {
            k -= 1;
        }
        if k == 0 {
            return None;
        }
        let prev_start = find_start(k - 1)?;
        Some(idx_to_pos(prev_start))
    }
}

/// `is` / `as` — sentence: text up to and including the next sentence
/// terminator (`.`, `?`, `!`). Vim treats `.`/`?`/`!` followed by
/// whitespace (or end-of-line) as a boundary; runs of consecutive
/// terminators stay attached to the same sentence. `as` extends to
/// include trailing whitespace; `is` does not.
fn sentence_text_object<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
    inner: bool,
) -> Option<((usize, usize), (usize, usize))> {
    let lines = buf_lines_to_vec(&ed.buffer);
    if lines.is_empty() {
        return None;
    }
    // Flatten the buffer so a sentence can span lines (vim's behaviour).
    // Newlines count as whitespace for boundary detection.
    let pos_to_idx = |pos: (usize, usize)| -> usize {
        let mut idx = 0;
        for line in lines.iter().take(pos.0) {
            idx += line.chars().count() + 1;
        }
        idx + pos.1
    };
    let idx_to_pos = |mut idx: usize| -> (usize, usize) {
        for (r, line) in lines.iter().enumerate() {
            let len = line.chars().count();
            if idx <= len {
                return (r, idx);
            }
            idx -= len + 1;
        }
        let last = lines.len().saturating_sub(1);
        (last, lines[last].chars().count())
    };
    let mut chars: Vec<char> = Vec::new();
    for (r, line) in lines.iter().enumerate() {
        chars.extend(line.chars());
        if r + 1 < lines.len() {
            chars.push('\n');
        }
    }
    if chars.is_empty() {
        return None;
    }

    let cursor_idx = pos_to_idx(ed.cursor()).min(chars.len() - 1);
    let is_terminator = |c: char| matches!(c, '.' | '?' | '!');

    // Walk backward from cursor to find the start of the current
    // sentence. A boundary is: whitespace immediately after a run of
    // terminators (or start-of-buffer).
    let mut start = cursor_idx;
    while start > 0 {
        let prev = chars[start - 1];
        if prev.is_whitespace() {
            // Check if the whitespace follows a terminator — if so,
            // we've crossed a sentence boundary; the sentence begins
            // at the first non-whitespace cell *after* this run.
            let mut k = start - 1;
            while k > 0 && chars[k - 1].is_whitespace() {
                k -= 1;
            }
            if k > 0 && is_terminator(chars[k - 1]) {
                break;
            }
        }
        start -= 1;
    }
    // Skip leading whitespace (vim doesn't include it in the
    // sentence body).
    while start < chars.len() && chars[start].is_whitespace() {
        start += 1;
    }
    if start >= chars.len() {
        return None;
    }

    // Walk forward to the sentence end (last terminator before the
    // next whitespace boundary).
    let mut end = start;
    while end < chars.len() {
        if is_terminator(chars[end]) {
            // Consume any consecutive terminators (e.g. `?!`).
            while end + 1 < chars.len() && is_terminator(chars[end + 1]) {
                end += 1;
            }
            // If followed by whitespace or end-of-buffer, that's the
            // boundary.
            if end + 1 >= chars.len() || chars[end + 1].is_whitespace() {
                break;
            }
        }
        end += 1;
    }
    // Inclusive end → exclusive end_idx.
    let end_idx = (end + 1).min(chars.len());

    let final_end = if inner {
        end_idx
    } else {
        // `as`: include trailing whitespace (but stop before the next
        // newline so we don't gobble a paragraph break — vim keeps
        // sentences within a paragraph for the trailing-ws extension).
        let mut e = end_idx;
        while e < chars.len() && chars[e].is_whitespace() && chars[e] != '\n' {
            e += 1;
        }
        e
    };

    Some((idx_to_pos(start), idx_to_pos(final_end)))
}

/// `it` / `at` — XML tag pair text object. Builds a flat char index of
/// the buffer, walks `<...>` tokens to pair tags via a stack, and
/// returns the innermost pair containing the cursor.
fn tag_text_object<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
    inner: bool,
) -> Option<((usize, usize), (usize, usize))> {
    let lines = buf_lines_to_vec(&ed.buffer);
    if lines.is_empty() {
        return None;
    }
    // Flatten char positions so we can compare cursor against tag
    // ranges without per-row arithmetic. `\n` between lines counts as
    // a single char.
    let pos_to_idx = |pos: (usize, usize)| -> usize {
        let mut idx = 0;
        for line in lines.iter().take(pos.0) {
            idx += line.chars().count() + 1;
        }
        idx + pos.1
    };
    let idx_to_pos = |mut idx: usize| -> (usize, usize) {
        for (r, line) in lines.iter().enumerate() {
            let len = line.chars().count();
            if idx <= len {
                return (r, idx);
            }
            idx -= len + 1;
        }
        let last = lines.len().saturating_sub(1);
        (last, lines[last].chars().count())
    };
    let mut chars: Vec<char> = Vec::new();
    for (r, line) in lines.iter().enumerate() {
        chars.extend(line.chars());
        if r + 1 < lines.len() {
            chars.push('\n');
        }
    }
    let cursor_idx = pos_to_idx(ed.cursor());

    // Walk `<...>` tokens. Track open tags on a stack; on a matching
    // close pop and consider the pair a candidate when the cursor lies
    // inside its content range. Innermost wins (replace whenever a
    // tighter range turns up). Also track the first complete pair that
    // starts at or after the cursor so we can fall back to a forward
    // scan (targets.vim-style) when the cursor isn't inside any tag.
    let mut stack: Vec<(usize, usize, String)> = Vec::new(); // (open_start, content_start, name)
    let mut innermost: Option<(usize, usize, usize, usize)> = None;
    let mut next_after: Option<(usize, usize, usize, usize)> = None;
    let mut i = 0;
    while i < chars.len() {
        if chars[i] != '<' {
            i += 1;
            continue;
        }
        let mut j = i + 1;
        while j < chars.len() && chars[j] != '>' {
            j += 1;
        }
        if j >= chars.len() {
            break;
        }
        let inside: String = chars[i + 1..j].iter().collect();
        let close_end = j + 1;
        let trimmed = inside.trim();
        if trimmed.starts_with('!') || trimmed.starts_with('?') {
            i = close_end;
            continue;
        }
        if let Some(rest) = trimmed.strip_prefix('/') {
            let name = rest.split_whitespace().next().unwrap_or("").to_string();
            if !name.is_empty()
                && let Some(stack_idx) = stack.iter().rposition(|(_, _, n)| *n == name)
            {
                let (open_start, content_start, _) = stack[stack_idx].clone();
                stack.truncate(stack_idx);
                let content_end = i;
                let candidate = (open_start, content_start, content_end, close_end);
                if cursor_idx >= content_start && cursor_idx <= content_end {
                    innermost = match innermost {
                        Some((_, cs, ce, _)) if cs <= content_start && content_end <= ce => {
                            Some(candidate)
                        }
                        None => Some(candidate),
                        existing => existing,
                    };
                } else if open_start >= cursor_idx && next_after.is_none() {
                    next_after = Some(candidate);
                }
            }
        } else if !trimmed.ends_with('/') {
            let name: String = trimmed
                .split(|c: char| c.is_whitespace() || c == '/')
                .next()
                .unwrap_or("")
                .to_string();
            if !name.is_empty() {
                stack.push((i, close_end, name));
            }
        }
        i = close_end;
    }

    let (open_start, content_start, content_end, close_end) = innermost.or(next_after)?;
    if inner {
        Some((idx_to_pos(content_start), idx_to_pos(content_end)))
    } else {
        Some((idx_to_pos(open_start), idx_to_pos(close_end)))
    }
}

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

// `is_keyword_char` lives in hjkl-buffer (used by word motions);
// engine re-uses it via `hjkl_buffer::is_keyword_char` so there's
// one parser, one default, one bug surface.
pub(crate) use hjkl_buffer::is_keyword_char;

fn word_text_object<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
    inner: bool,
    big: bool,
) -> Option<((usize, usize), (usize, usize))> {
    let (row, col) = ed.cursor();
    let line = buf_line(&ed.buffer, row)?;
    let chars: Vec<char> = line.chars().collect();
    if chars.is_empty() {
        return None;
    }
    let at = col.min(chars.len().saturating_sub(1));
    let classify = |c: char| -> u8 {
        if c.is_whitespace() {
            0
        } else if big || is_wordchar(c) {
            1
        } else {
            2
        }
    };
    let cls = classify(chars[at]);
    let mut start = at;
    while start > 0 && classify(chars[start - 1]) == cls {
        start -= 1;
    }
    let mut end = at;
    while end + 1 < chars.len() && classify(chars[end + 1]) == cls {
        end += 1;
    }
    // Byte-offset helpers.
    let char_byte = |i: usize| {
        if i >= chars.len() {
            line.len()
        } else {
            line.char_indices().nth(i).map(|(b, _)| b).unwrap_or(0)
        }
    };
    let mut start_col = char_byte(start);
    // Exclusive end: byte index of char AFTER the last-included char.
    let mut end_col = char_byte(end + 1);
    if !inner {
        // `aw` — include trailing whitespace; if there's no trailing ws, absorb leading ws.
        let mut t = end + 1;
        let mut included_trailing = false;
        while t < chars.len() && chars[t].is_whitespace() {
            included_trailing = true;
            t += 1;
        }
        if included_trailing {
            end_col = char_byte(t);
        } else {
            let mut s = start;
            while s > 0 && chars[s - 1].is_whitespace() {
                s -= 1;
            }
            start_col = char_byte(s);
        }
    }
    Some(((row, start_col), (row, end_col)))
}

fn quote_text_object<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
    q: char,
    inner: bool,
) -> Option<((usize, usize), (usize, usize))> {
    let (row, col) = ed.cursor();
    let line = buf_line(&ed.buffer, row)?;
    let bytes = line.as_bytes();
    let q_byte = q as u8;
    // Find opening and closing quote on the same line.
    let mut positions: Vec<usize> = Vec::new();
    for (i, &b) in bytes.iter().enumerate() {
        if b == q_byte {
            positions.push(i);
        }
    }
    if positions.len() < 2 {
        return None;
    }
    let mut open_idx: Option<usize> = None;
    let mut close_idx: Option<usize> = None;
    for pair in positions.chunks(2) {
        if pair.len() < 2 {
            break;
        }
        if col >= pair[0] && col <= pair[1] {
            open_idx = Some(pair[0]);
            close_idx = Some(pair[1]);
            break;
        }
        if col < pair[0] {
            open_idx = Some(pair[0]);
            close_idx = Some(pair[1]);
            break;
        }
    }
    let open = open_idx?;
    let close = close_idx?;
    // End columns are *exclusive* — one past the last character to act on.
    if inner {
        if close <= open + 1 {
            return None;
        }
        Some(((row, open + 1), (row, close)))
    } else {
        // `da<q>` — "around" includes the surrounding whitespace on one
        // side: trailing whitespace if any exists after the closing quote;
        // otherwise leading whitespace before the opening quote. This
        // matches vim's `:help text-objects` behaviour and avoids leaving
        // a double-space when the quoted span sits mid-sentence.
        let after_close = close + 1; // byte index after closing quote
        if after_close < bytes.len() && bytes[after_close].is_ascii_whitespace() {
            // Eat trailing whitespace run.
            let mut end = after_close;
            while end < bytes.len() && bytes[end].is_ascii_whitespace() {
                end += 1;
            }
            Some(((row, open), (row, end)))
        } else if open > 0 && bytes[open - 1].is_ascii_whitespace() {
            // Eat leading whitespace run.
            let mut start = open;
            while start > 0 && bytes[start - 1].is_ascii_whitespace() {
                start -= 1;
            }
            Some(((row, start), (row, close + 1)))
        } else {
            Some(((row, open), (row, close + 1)))
        }
    }
}

fn bracket_text_object<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
    open: char,
    inner: bool,
) -> Option<(Pos, Pos, RangeKind)> {
    let close = match open {
        '(' => ')',
        '[' => ']',
        '{' => '}',
        '<' => '>',
        _ => return None,
    };
    let (row, col) = ed.cursor();
    let lines = buf_lines_to_vec(&ed.buffer);
    let lines = lines.as_slice();
    // Walk backward from cursor to find unbalanced opening. When the
    // cursor isn't inside any pair, fall back to scanning forward for
    // the next opening bracket (targets.vim-style: `ci(` works when
    // cursor is before the `(` on the same line or below).
    let open_pos = find_open_bracket(lines, row, col, open, close)
        .or_else(|| find_next_open(lines, row, col, open))?;
    let close_pos = find_close_bracket(lines, open_pos.0, open_pos.1 + 1, open, close)?;
    // End positions are *exclusive*.
    if inner {
        // Multi-line `iB` / `i{` etc: vim deletes the full lines between
        // the braces (linewise), preserving the `{` and `}` lines
        // themselves and the newlines that directly abut them. E.g.:
        //   {\n    body\n}\n  →  {\n}\n    (cursor on `}` line)
        // Single-line `i{` falls back to charwise exclusive.
        if close_pos.0 > open_pos.0 + 1 {
            // There is at least one line strictly between open and close.
            let inner_row_start = open_pos.0 + 1;
            let inner_row_end = close_pos.0 - 1;
            let end_col = lines
                .get(inner_row_end)
                .map(|l| l.chars().count())
                .unwrap_or(0);
            return Some((
                (inner_row_start, 0),
                (inner_row_end, end_col),
                RangeKind::Linewise,
            ));
        }
        let inner_start = advance_pos(lines, open_pos);
        if inner_start.0 > close_pos.0
            || (inner_start.0 == close_pos.0 && inner_start.1 >= close_pos.1)
        {
            return None;
        }
        Some((inner_start, close_pos, RangeKind::Exclusive))
    } else {
        Some((
            open_pos,
            advance_pos(lines, close_pos),
            RangeKind::Exclusive,
        ))
    }
}

fn find_open_bracket(
    lines: &[String],
    row: usize,
    col: usize,
    open: char,
    close: char,
) -> Option<(usize, usize)> {
    let mut depth: i32 = 0;
    let mut r = row;
    let mut c = col as isize;
    loop {
        let cur = &lines[r];
        let chars: Vec<char> = cur.chars().collect();
        // Clamp `c` to the line length: callers may seed `col` past
        // EOL on virtual-cursor lines (e.g., insert mode after `o`)
        // so direct indexing would panic on empty / short lines.
        if (c as usize) >= chars.len() {
            c = chars.len() as isize - 1;
        }
        while c >= 0 {
            let ch = chars[c as usize];
            if ch == close {
                depth += 1;
            } else if ch == open {
                if depth == 0 {
                    return Some((r, c as usize));
                }
                depth -= 1;
            }
            c -= 1;
        }
        if r == 0 {
            return None;
        }
        r -= 1;
        c = lines[r].chars().count() as isize - 1;
    }
}

fn find_close_bracket(
    lines: &[String],
    row: usize,
    start_col: usize,
    open: char,
    close: char,
) -> Option<(usize, usize)> {
    let mut depth: i32 = 0;
    let mut r = row;
    let mut c = start_col;
    loop {
        let cur = &lines[r];
        let chars: Vec<char> = cur.chars().collect();
        while c < chars.len() {
            let ch = chars[c];
            if ch == open {
                depth += 1;
            } else if ch == close {
                if depth == 0 {
                    return Some((r, c));
                }
                depth -= 1;
            }
            c += 1;
        }
        if r + 1 >= lines.len() {
            return None;
        }
        r += 1;
        c = 0;
    }
}

/// Forward scan from `(row, col)` for the next occurrence of `open`.
/// Multi-line. Used by bracket text objects to support targets.vim-style
/// "search forward when not currently inside a pair" behaviour.
fn find_next_open(lines: &[String], row: usize, col: usize, open: char) -> Option<(usize, usize)> {
    let mut r = row;
    let mut c = col;
    while r < lines.len() {
        let chars: Vec<char> = lines[r].chars().collect();
        while c < chars.len() {
            if chars[c] == open {
                return Some((r, c));
            }
            c += 1;
        }
        r += 1;
        c = 0;
    }
    None
}

fn advance_pos(lines: &[String], pos: (usize, usize)) -> (usize, usize) {
    let (r, c) = pos;
    let line_len = lines[r].chars().count();
    if c < line_len {
        (r, c + 1)
    } else if r + 1 < lines.len() {
        (r + 1, 0)
    } else {
        pos
    }
}

fn paragraph_text_object<H: crate::types::Host>(
    ed: &Editor<hjkl_buffer::Buffer, H>,
    inner: bool,
) -> Option<((usize, usize), (usize, usize))> {
    let (row, _) = ed.cursor();
    let lines = buf_lines_to_vec(&ed.buffer);
    if lines.is_empty() {
        return None;
    }
    // A paragraph is a run of non-blank lines.
    let is_blank = |r: usize| lines.get(r).map(|s| s.trim().is_empty()).unwrap_or(true);
    if is_blank(row) {
        return None;
    }
    let mut top = row;
    while top > 0 && !is_blank(top - 1) {
        top -= 1;
    }
    let mut bot = row;
    while bot + 1 < lines.len() && !is_blank(bot + 1) {
        bot += 1;
    }
    // For `ap`, include one trailing blank line if present.
    if !inner && bot + 1 < lines.len() && is_blank(bot + 1) {
        bot += 1;
    }
    let end_col = lines[bot].chars().count();
    Some(((top, 0), (bot, end_col)))
}

// ─── Individual commands ───────────────────────────────────────────────────

/// Read the text in a vim-shaped range without mutating. Used by
/// `Operator::Yank` so we can pipe the same range translation as
/// [`cut_vim_range`] but skip the delete + inverse extraction.
fn read_vim_range<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    start: (usize, usize),
    end: (usize, usize),
    kind: RangeKind,
) -> String {
    let (top, bot) = order(start, end);
    ed.sync_buffer_content_from_textarea();
    let lines = buf_lines_to_vec(&ed.buffer);
    match kind {
        RangeKind::Linewise => {
            let lo = top.0;
            let hi = bot.0.min(lines.len().saturating_sub(1));
            let mut text = lines[lo..=hi].join("\n");
            text.push('\n');
            text
        }
        RangeKind::Inclusive | RangeKind::Exclusive => {
            let inclusive = matches!(kind, RangeKind::Inclusive);
            // Walk row-by-row collecting chars in `[top, end_exclusive)`.
            let mut out = String::new();
            for row in top.0..=bot.0 {
                let line = lines.get(row).map(String::as_str).unwrap_or("");
                let lo = if row == top.0 { top.1 } else { 0 };
                let hi_unclamped = if row == bot.0 {
                    if inclusive { bot.1 + 1 } else { bot.1 }
                } else {
                    line.chars().count() + 1
                };
                let row_chars: Vec<char> = line.chars().collect();
                let hi = hi_unclamped.min(row_chars.len());
                if lo < hi {
                    out.push_str(&row_chars[lo..hi].iter().collect::<String>());
                }
                if row < bot.0 {
                    out.push('\n');
                }
            }
            out
        }
    }
}

/// Cut a vim-shaped range through the Buffer edit funnel and return
/// the deleted text. Translates vim's `RangeKind`
/// (Linewise/Inclusive/Exclusive) into the buffer's
/// `hjkl_buffer::MotionKind` (Line/Char) and applies the right end-
/// position adjustment so inclusive motions actually include the bot
/// cell. Pushes the cut text into both `last_yank` and the textarea
/// yank buffer (still observed by `p`/`P` until the paste path is
/// ported), and updates `yank_linewise` for linewise cuts.
fn cut_vim_range<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    start: (usize, usize),
    end: (usize, usize),
    kind: RangeKind,
) -> String {
    use hjkl_buffer::{Edit, MotionKind as BufKind, Position};
    let (top, bot) = order(start, end);
    ed.sync_buffer_content_from_textarea();
    let (buf_start, buf_end, buf_kind) = match kind {
        RangeKind::Linewise => (
            Position::new(top.0, 0),
            Position::new(bot.0, 0),
            BufKind::Line,
        ),
        RangeKind::Inclusive => {
            let line_chars = buf_line_chars(&ed.buffer, bot.0);
            // Advance one cell past `bot` so the buffer's exclusive
            // `cut_chars` actually drops the inclusive endpoint. Wrap
            // to the next row when bot already sits on the last char.
            let next = if bot.1 < line_chars {
                Position::new(bot.0, bot.1 + 1)
            } else if bot.0 + 1 < buf_row_count(&ed.buffer) {
                Position::new(bot.0 + 1, 0)
            } else {
                Position::new(bot.0, line_chars)
            };
            (Position::new(top.0, top.1), next, BufKind::Char)
        }
        RangeKind::Exclusive => (
            Position::new(top.0, top.1),
            Position::new(bot.0, bot.1),
            BufKind::Char,
        ),
    };
    let inverse = ed.mutate_edit(Edit::DeleteRange {
        start: buf_start,
        end: buf_end,
        kind: buf_kind,
    });
    let text = match inverse {
        Edit::InsertStr { text, .. } => text,
        _ => String::new(),
    };
    if !text.is_empty() {
        ed.record_yank_to_host(text.clone());
        ed.record_delete(text.clone(), matches!(kind, RangeKind::Linewise));
    }
    ed.push_buffer_cursor_to_textarea();
    text
}

/// `D` / `C` — delete from cursor to end of line through the edit
/// funnel. Mirrors the deleted text into both `ed.last_yank` and the
/// textarea's yank buffer (still observed by `p`/`P` until the paste
/// path is ported). Cursor lands at the deletion start so the caller
/// can decide whether to step it left (`D`) or open insert mode (`C`).
fn delete_to_eol<H: crate::types::Host>(ed: &mut Editor<hjkl_buffer::Buffer, H>) {
    use hjkl_buffer::{Edit, MotionKind, Position};
    ed.sync_buffer_content_from_textarea();
    let cursor = buf_cursor_pos(&ed.buffer);
    let line_chars = buf_line_chars(&ed.buffer, cursor.row);
    if cursor.col >= line_chars {
        return;
    }
    let inverse = ed.mutate_edit(Edit::DeleteRange {
        start: cursor,
        end: Position::new(cursor.row, line_chars),
        kind: MotionKind::Char,
    });
    if let Edit::InsertStr { text, .. } = inverse
        && !text.is_empty()
    {
        ed.record_yank_to_host(text.clone());
        ed.vim.yank_linewise = false;
        ed.set_yank(text);
    }
    buf_set_cursor_pos(&mut ed.buffer, cursor);
    ed.push_buffer_cursor_to_textarea();
}

fn do_char_delete<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    forward: bool,
    count: usize,
) {
    use hjkl_buffer::{Edit, MotionKind, Position};
    ed.push_undo();
    ed.sync_buffer_content_from_textarea();
    // Collect deleted chars so we can write them to the unnamed register
    // (vim's `x`/`X` populate `"` so that `xp` round-trips the char).
    let mut deleted = String::new();
    for _ in 0..count {
        let cursor = buf_cursor_pos(&ed.buffer);
        let line_chars = buf_line_chars(&ed.buffer, cursor.row);
        if forward {
            // `x` — delete the char under the cursor. Vim no-ops on
            // an empty line; the buffer would drop a row otherwise.
            if cursor.col >= line_chars {
                continue;
            }
            let inverse = ed.mutate_edit(Edit::DeleteRange {
                start: cursor,
                end: Position::new(cursor.row, cursor.col + 1),
                kind: MotionKind::Char,
            });
            if let Edit::InsertStr { text, .. } = inverse {
                deleted.push_str(&text);
            }
        } else {
            // `X` — delete the char before the cursor.
            if cursor.col == 0 {
                continue;
            }
            let inverse = ed.mutate_edit(Edit::DeleteRange {
                start: Position::new(cursor.row, cursor.col - 1),
                end: cursor,
                kind: MotionKind::Char,
            });
            if let Edit::InsertStr { text, .. } = inverse {
                // X deletes backwards; prepend so the register text
                // matches reading order (first deleted char first).
                deleted = text + &deleted;
            }
        }
    }
    if !deleted.is_empty() {
        ed.record_yank_to_host(deleted.clone());
        ed.record_delete(deleted, false);
    }
    ed.push_buffer_cursor_to_textarea();
}

/// Vim `Ctrl-a` / `Ctrl-x` — find the next decimal number at or after the
/// cursor on the current line, add `delta`, leave the cursor on the last
/// digit of the result. No-op if the line has no digits to the right.
pub(crate) fn adjust_number<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    delta: i64,
) -> bool {
    use hjkl_buffer::{Edit, MotionKind, Position};
    ed.sync_buffer_content_from_textarea();
    let cursor = buf_cursor_pos(&ed.buffer);
    let row = cursor.row;
    let chars: Vec<char> = match buf_line(&ed.buffer, row) {
        Some(l) => l.chars().collect(),
        None => return false,
    };
    let Some(digit_start) = (cursor.col..chars.len()).find(|&i| chars[i].is_ascii_digit()) else {
        return false;
    };
    let span_start = if digit_start > 0 && chars[digit_start - 1] == '-' {
        digit_start - 1
    } else {
        digit_start
    };
    let mut span_end = digit_start;
    while span_end < chars.len() && chars[span_end].is_ascii_digit() {
        span_end += 1;
    }
    let s: String = chars[span_start..span_end].iter().collect();
    let Ok(n) = s.parse::<i64>() else {
        return false;
    };
    let new_s = n.saturating_add(delta).to_string();

    ed.push_undo();
    let span_start_pos = Position::new(row, span_start);
    let span_end_pos = Position::new(row, span_end);
    ed.mutate_edit(Edit::DeleteRange {
        start: span_start_pos,
        end: span_end_pos,
        kind: MotionKind::Char,
    });
    ed.mutate_edit(Edit::InsertStr {
        at: span_start_pos,
        text: new_s.clone(),
    });
    let new_len = new_s.chars().count();
    buf_set_cursor_rc(&mut ed.buffer, row, span_start + new_len.saturating_sub(1));
    ed.push_buffer_cursor_to_textarea();
    true
}

pub(crate) fn replace_char<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    ch: char,
    count: usize,
) {
    use hjkl_buffer::{Edit, MotionKind, Position};
    ed.push_undo();
    ed.sync_buffer_content_from_textarea();
    for _ in 0..count {
        let cursor = buf_cursor_pos(&ed.buffer);
        let line_chars = buf_line_chars(&ed.buffer, cursor.row);
        if cursor.col >= line_chars {
            break;
        }
        ed.mutate_edit(Edit::DeleteRange {
            start: cursor,
            end: Position::new(cursor.row, cursor.col + 1),
            kind: MotionKind::Char,
        });
        ed.mutate_edit(Edit::InsertChar { at: cursor, ch });
    }
    // Vim leaves the cursor on the last replaced char.
    crate::motions::move_left(&mut ed.buffer, 1);
    ed.push_buffer_cursor_to_textarea();
}

fn toggle_case_at_cursor<H: crate::types::Host>(ed: &mut Editor<hjkl_buffer::Buffer, H>) {
    use hjkl_buffer::{Edit, MotionKind, Position};
    ed.sync_buffer_content_from_textarea();
    let cursor = buf_cursor_pos(&ed.buffer);
    let Some(c) = buf_line(&ed.buffer, cursor.row).and_then(|l| l.chars().nth(cursor.col)) else {
        return;
    };
    let toggled = if c.is_uppercase() {
        c.to_lowercase().next().unwrap_or(c)
    } else {
        c.to_uppercase().next().unwrap_or(c)
    };
    ed.mutate_edit(Edit::DeleteRange {
        start: cursor,
        end: Position::new(cursor.row, cursor.col + 1),
        kind: MotionKind::Char,
    });
    ed.mutate_edit(Edit::InsertChar {
        at: cursor,
        ch: toggled,
    });
}

fn join_line<H: crate::types::Host>(ed: &mut Editor<hjkl_buffer::Buffer, H>) {
    use hjkl_buffer::{Edit, Position};
    ed.sync_buffer_content_from_textarea();
    let row = buf_cursor_pos(&ed.buffer).row;
    if row + 1 >= buf_row_count(&ed.buffer) {
        return;
    }
    let cur_line = buf_line(&ed.buffer, row).unwrap_or("").to_string();
    let next_raw = buf_line(&ed.buffer, row + 1).unwrap_or("").to_string();
    let next_trimmed = next_raw.trim_start();
    let cur_chars = cur_line.chars().count();
    let next_chars = next_raw.chars().count();
    // `J` inserts a single space iff both sides are non-empty after
    // stripping the next line's leading whitespace.
    let separator = if !cur_line.is_empty() && !next_trimmed.is_empty() {
        " "
    } else {
        ""
    };
    let joined = format!("{cur_line}{separator}{next_trimmed}");
    ed.mutate_edit(Edit::Replace {
        start: Position::new(row, 0),
        end: Position::new(row + 1, next_chars),
        with: joined,
    });
    // Vim parks the cursor on the inserted space — or at the join
    // point when no space went in (which is the same column either
    // way, since the space sits exactly at `cur_chars`).
    buf_set_cursor_rc(&mut ed.buffer, row, cur_chars);
    ed.push_buffer_cursor_to_textarea();
}

/// `gJ` — join the next line onto the current one without inserting a
/// separating space or stripping leading whitespace.
fn join_line_raw<H: crate::types::Host>(ed: &mut Editor<hjkl_buffer::Buffer, H>) {
    use hjkl_buffer::Edit;
    ed.sync_buffer_content_from_textarea();
    let row = buf_cursor_pos(&ed.buffer).row;
    if row + 1 >= buf_row_count(&ed.buffer) {
        return;
    }
    let join_col = buf_line_chars(&ed.buffer, row);
    ed.mutate_edit(Edit::JoinLines {
        row,
        count: 1,
        with_space: false,
    });
    // Vim leaves the cursor at the join point (end of original line).
    buf_set_cursor_rc(&mut ed.buffer, row, join_col);
    ed.push_buffer_cursor_to_textarea();
}

fn do_paste<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    before: bool,
    count: usize,
) {
    use hjkl_buffer::{Edit, Position};
    ed.push_undo();
    // Resolve the source register: `"reg` prefix (consumed) or the
    // unnamed register otherwise. Read text + linewise from the
    // selected slot rather than the global `vim.yank_linewise` so
    // pasting from `"0` after a delete still uses the yank's layout.
    let selector = ed.vim.pending_register.take();
    let (yank, linewise) = match selector.and_then(|c| ed.registers().read(c)) {
        Some(slot) => (slot.text.clone(), slot.linewise),
        // Read both fields from the unnamed slot rather than mixing the
        // slot's text with `vim.yank_linewise`. The cached vim flag is
        // per-editor, so a register imported from another editor (e.g.
        // cross-buffer yank/paste) carried the wrong linewise without
        // this — pasting a linewise yank inserted at the char cursor.
        None => {
            let s = &ed.registers().unnamed;
            (s.text.clone(), s.linewise)
        }
    };
    // Vim `:h '[` / `:h ']`: after paste `[` = first inserted char of
    // the final paste, `]` = last inserted char of the final paste.
    // We track (lo, hi) across iterations; the last value wins.
    let mut paste_mark: Option<((usize, usize), (usize, usize))> = None;
    for _ in 0..count {
        ed.sync_buffer_content_from_textarea();
        let yank = yank.clone();
        if yank.is_empty() {
            continue;
        }
        if linewise {
            // Linewise paste: insert payload as fresh row(s) above
            // (`P`) or below (`p`) the cursor's row. Cursor lands on
            // the first non-blank of the first pasted line.
            let text = yank.trim_matches('\n').to_string();
            let row = buf_cursor_pos(&ed.buffer).row;
            let target_row = if before {
                ed.mutate_edit(Edit::InsertStr {
                    at: Position::new(row, 0),
                    text: format!("{text}\n"),
                });
                row
            } else {
                let line_chars = buf_line_chars(&ed.buffer, row);
                ed.mutate_edit(Edit::InsertStr {
                    at: Position::new(row, line_chars),
                    text: format!("\n{text}"),
                });
                row + 1
            };
            buf_set_cursor_rc(&mut ed.buffer, target_row, 0);
            crate::motions::move_first_non_blank(&mut ed.buffer);
            ed.push_buffer_cursor_to_textarea();
            // Linewise: `[` = (target_row, 0), `]` = (bot_row, last_col).
            let payload_lines = text.lines().count().max(1);
            let bot_row = target_row + payload_lines - 1;
            let bot_last_col = buf_line_chars(&ed.buffer, bot_row).saturating_sub(1);
            paste_mark = Some(((target_row, 0), (bot_row, bot_last_col)));
        } else {
            // Charwise paste. `P` inserts at cursor (shifting cell
            // right); `p` inserts after cursor (advance one cell
            // first, clamped to the end of the line).
            let cursor = buf_cursor_pos(&ed.buffer);
            let at = if before {
                cursor
            } else {
                let line_chars = buf_line_chars(&ed.buffer, cursor.row);
                Position::new(cursor.row, (cursor.col + 1).min(line_chars))
            };
            ed.mutate_edit(Edit::InsertStr {
                at,
                text: yank.clone(),
            });
            // Vim parks the cursor on the last char of the pasted
            // text (do_insert_str leaves it one past the end).
            crate::motions::move_left(&mut ed.buffer, 1);
            ed.push_buffer_cursor_to_textarea();
            // Charwise: `[` = insert start, `]` = cursor (last pasted char).
            let lo = (at.row, at.col);
            let hi = ed.cursor();
            paste_mark = Some((lo, hi));
        }
    }
    if let Some((lo, hi)) = paste_mark {
        ed.set_mark('[', lo);
        ed.set_mark(']', hi);
    }
    // Any paste re-anchors the sticky column to the new cursor position.
    ed.sticky_col = Some(buf_cursor_pos(&ed.buffer).col);
}

pub(crate) fn do_undo<H: crate::types::Host>(ed: &mut Editor<hjkl_buffer::Buffer, H>) {
    if let Some((lines, cursor)) = ed.undo_stack.pop() {
        let current = ed.snapshot();
        ed.redo_stack.push(current);
        ed.restore(lines, cursor);
    }
    ed.vim.mode = Mode::Normal;
    // The restored cursor came from a snapshot taken in insert mode
    // (before the insert started) and may be past the last valid
    // normal-mode column. Clamp it now, same as Esc-from-insert does.
    clamp_cursor_to_normal_mode(ed);
}

pub(crate) fn do_redo<H: crate::types::Host>(ed: &mut Editor<hjkl_buffer::Buffer, H>) {
    if let Some((lines, cursor)) = ed.redo_stack.pop() {
        let current = ed.snapshot();
        ed.undo_stack.push(current);
        ed.cap_undo();
        ed.restore(lines, cursor);
    }
    ed.vim.mode = Mode::Normal;
}

// ─── Dot repeat ────────────────────────────────────────────────────────────

/// Replay-side helper: insert `text` at the cursor through the
/// edit funnel, then leave insert mode (the original change ended
/// with Esc, so the dot-repeat must end the same way — including
/// the cursor step-back vim does on Esc-from-insert).
fn replay_insert_and_finish<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    text: &str,
) {
    use hjkl_buffer::{Edit, Position};
    let cursor = ed.cursor();
    ed.mutate_edit(Edit::InsertStr {
        at: Position::new(cursor.0, cursor.1),
        text: text.to_string(),
    });
    if ed.vim.insert_session.take().is_some() {
        if ed.cursor().1 > 0 {
            crate::motions::move_left(&mut ed.buffer, 1);
            ed.push_buffer_cursor_to_textarea();
        }
        ed.vim.mode = Mode::Normal;
    }
}

pub(crate) fn replay_last_change<H: crate::types::Host>(
    ed: &mut Editor<hjkl_buffer::Buffer, H>,
    outer_count: usize,
) {
    let Some(change) = ed.vim.last_change.clone() else {
        return;
    };
    ed.vim.replaying = true;
    let scale = if outer_count > 0 { outer_count } else { 1 };
    match change {
        LastChange::OpMotion {
            op,
            motion,
            count,
            inserted,
        } => {
            let total = count.max(1) * scale;
            apply_op_with_motion(ed, op, &motion, total);
            if let Some(text) = inserted {
                replay_insert_and_finish(ed, &text);
            }
        }
        LastChange::OpTextObj {
            op,
            obj,
            inner,
            inserted,
        } => {
            apply_op_with_text_object(ed, op, obj, inner);
            if let Some(text) = inserted {
                replay_insert_and_finish(ed, &text);
            }
        }
        LastChange::LineOp {
            op,
            count,
            inserted,
        } => {
            let total = count.max(1) * scale;
            execute_line_op(ed, op, total);
            if let Some(text) = inserted {
                replay_insert_and_finish(ed, &text);
            }
        }
        LastChange::CharDel { forward, count } => {
            do_char_delete(ed, forward, count * scale);
        }
        LastChange::ReplaceChar { ch, count } => {
            replace_char(ed, ch, count * scale);
        }
        LastChange::ToggleCase { count } => {
            for _ in 0..count * scale {
                ed.push_undo();
                toggle_case_at_cursor(ed);
            }
        }
        LastChange::JoinLine { count } => {
            for _ in 0..count * scale {
                ed.push_undo();
                join_line(ed);
            }
        }
        LastChange::Paste { before, count } => {
            do_paste(ed, before, count * scale);
        }
        LastChange::DeleteToEol { inserted } => {
            use hjkl_buffer::{Edit, Position};
            ed.push_undo();
            delete_to_eol(ed);
            if let Some(text) = inserted {
                let cursor = ed.cursor();
                ed.mutate_edit(Edit::InsertStr {
                    at: Position::new(cursor.0, cursor.1),
                    text,
                });
            }
        }
        LastChange::OpenLine { above, inserted } => {
            use hjkl_buffer::{Edit, Position};
            ed.push_undo();
            ed.sync_buffer_content_from_textarea();
            let row = buf_cursor_pos(&ed.buffer).row;
            if above {
                ed.mutate_edit(Edit::InsertStr {
                    at: Position::new(row, 0),
                    text: "\n".to_string(),
                });
                let folds = crate::buffer_impl::SnapshotFoldProvider::from_buffer(&ed.buffer);
                crate::motions::move_up(&mut ed.buffer, &folds, 1, &mut ed.sticky_col);
            } else {
                let line_chars = buf_line_chars(&ed.buffer, row);
                ed.mutate_edit(Edit::InsertStr {
                    at: Position::new(row, line_chars),
                    text: "\n".to_string(),
                });
            }
            ed.push_buffer_cursor_to_textarea();
            let cursor = ed.cursor();
            ed.mutate_edit(Edit::InsertStr {
                at: Position::new(cursor.0, cursor.1),
                text: inserted,
            });
        }
        LastChange::InsertAt {
            entry,
            inserted,
            count,
        } => {
            use hjkl_buffer::{Edit, Position};
            ed.push_undo();
            match entry {
                InsertEntry::I => {}
                InsertEntry::ShiftI => move_first_non_whitespace(ed),
                InsertEntry::A => {
                    crate::motions::move_right_to_end(&mut ed.buffer, 1);
                    ed.push_buffer_cursor_to_textarea();
                }
                InsertEntry::ShiftA => {
                    crate::motions::move_line_end(&mut ed.buffer);
                    crate::motions::move_right_to_end(&mut ed.buffer, 1);
                    ed.push_buffer_cursor_to_textarea();
                }
            }
            for _ in 0..count.max(1) {
                let cursor = ed.cursor();
                ed.mutate_edit(Edit::InsertStr {
                    at: Position::new(cursor.0, cursor.1),
                    text: inserted.clone(),
                });
            }
        }
    }
    ed.vim.replaying = false;
}

// ─── Extracting inserted text for replay ───────────────────────────────────

fn extract_inserted(before: &str, after: &str) -> String {
    let before_chars: Vec<char> = before.chars().collect();
    let after_chars: Vec<char> = after.chars().collect();
    if after_chars.len() <= before_chars.len() {
        return String::new();
    }
    let prefix = before_chars
        .iter()
        .zip(after_chars.iter())
        .take_while(|(a, b)| a == b)
        .count();
    let max_suffix = before_chars.len() - prefix;
    let suffix = before_chars
        .iter()
        .rev()
        .zip(after_chars.iter().rev())
        .take(max_suffix)
        .take_while(|(a, b)| a == b)
        .count();
    after_chars[prefix..after_chars.len() - suffix]
        .iter()
        .collect()
}

// ─── Tests ────────────────────────────────────────────────────────────────