edamame 0.1.1

A fast TUI Markdown editor and viewer
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
//! The vim reducer: one key in, one [`VimOutcome`] out.
//!
//! `vim_feed` is the input-layer half of the two-layer split (mirroring
//! `MouseDispatcher`): it decides *what* the user asked for and applies
//! the simple cursor / mode transitions directly.  Heavier resolution
//! (motion ranges, operators, text objects) moves into
//! `editor::vim_ops` in later checkpoints.
//!
//! CP2 surface: the core motions `w e b W E B 0 ^ $ gg G` (resolved via
//! `vim_ops::motion`), the Insert entries `i a I A o O`, and `v`/`V`
//! entry into Visual / Visual-Line.
//!
//! CP3 makes counts drive motions (`3j`, `5l`) and adds the
//! operator+motion reducer: `d`/`c`/`y` enter OperatorPending and a
//! following motion (or a doubled operator, `dd`/`yy`/`cc`) resolves an
//! [`OpRange`] that `vim_ops::execute_operator` applies as a single
//! delta.  The single-key edits `x X D C Y` reuse that same operator
//! machinery, and `p`/`P` paste the unnamed register (`vim_ops::paste`).
//! Counts combine across `[count]op[count]motion` (e.g. `2d3w` → 6
//! words).  In Normal a bare key is swallowed (it must never type);
//! Insert defers to the existing editing pipeline via
//! [`VimOutcome::Passthrough`].
//!
//! CP5 adds the character-find motions `f F t T` (each waits one key for
//! its target, then records it so `;` / `,` can replay / reverse it),
//! the paragraph motions `{ }`, and the matching-pair motion `%`.  All
//! work as plain motions, as operator targets (`df(`, `d}`, `d%`), and as
//! Visual-selection extensions.
//!
//! CP7 adds the text objects `iw aw iW aW`, the quote pairs `i"/a" i'/a'
//! i\`/a\``, and the bracket pairs `i(/a( i[/a[ i{/a{`.  An `i`/`a` behind
//! an operator (or in Visual) arms a pending object; the next key resolves
//! it via `vim_ops::resolve_text_object_range` and either runs the operator
//! (`diw`, `ci(`) or sets the Visual selection (`viw`).

use std::ops::Range;
use std::path::PathBuf;

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use crate::config::Action;
use crate::document::{prev_grapheme_offset, EditDelta, Selection};
use crate::editor::vim_ops::{
    cell_scope, clear_substitute_preview, clear_table_cell, delete_table_row, doubled_line_range,
    end_incsearch, execute_operator, execute_substitute, first_non_blank, indent_lines,
    indent_list_item, insert_table_rows, join_lines, line_end_offset, lines_touch_a_table,
    op_range_breaks_a_table, open_list_continue, open_table_row, parse_ex, paste,
    range_breaks_a_table, renumber_list_at_cursor, replace_char, replace_char_range,
    replace_range_with, resolve_find_repeat, resolve_scoped_motion, resolve_scoped_op_range,
    resolve_text_object_range, scope_offset, set_case_range, table_paste_plan, toggle_case,
    toggle_case_range, update_incsearch, update_substitute_preview, vertical_line_range,
    visual_cell_step, visual_charwise_range, visual_endpoint_in_cell, visual_line_bounds,
    visual_line_char_range, word_under_cursor_at, CellLimit, ExCommand, FindKind, Motion, OpRange,
    OpResult, Operator, TableBreak, TableOpOutcome, TablePaste, TextObject,
};
use crate::editor::{edit_ops, EditorState, Mode};
use crate::input::mode_handler::default::{is_ctrl_backspace, is_ctrl_delete};

use super::cmdline::{self, CmdLineStep};
use super::state::{
    CmdLineKind, CmdLineState, PendingOp, VimRegister, VimState, VimSubMode, COUNT_CAP,
};

/// What `vim_feed` decided about a key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VimOutcome {
    /// A multi-key sequence is still accumulating — keep the pending
    /// count / operator state.
    Pending,
    /// The key was fully handled (a mutation applied, or a deliberate
    /// no-op).  The caller redraws and stops.
    Consumed,
    /// Not a vim key (e.g. a `Ctrl-*` chord) — fall through to the
    /// default keymap handler.
    Passthrough,
    /// An App-level effect the reducer can't perform itself (it holds
    /// `&mut EditorState`, not `&mut App`): start a search for `query`
    /// in the given direction.  Emitted by `/` `?` (query from the
    /// command line) and `*` `#` (word under the cursor).  The App runs
    /// `enter_vim_search`.  `n`/`N` need no outcome — they move over
    /// `EditorState::search` directly.
    EnterSearch { forward: bool, query: String },
    /// `:w` — write the buffer via the existing `Action::Save`, so the
    /// flash / autosave bookkeeping comes for free.
    Save,
    /// `:q` (`save_first == false`) / `:wq` (`true`) — quit via the
    /// existing dirty-guarded `Action::Quit`, saving first for `:wq` (so
    /// the buffer is clean before the quit guard runs).
    Quit { save_first: bool },
    /// `:saveas` / a bare `:w` on a path-less buffer — write the buffer to
    /// a new path and *adopt* it (subsequent saves target the new path).
    /// `path == Some` saves directly (the user named the destination on
    /// the command line); `path == None` opens the Save As modal so the
    /// user can choose one.  `then_quit` carries the `:wq` / `:x` intent:
    /// quit once the write succeeds.  `force` (a trailing `!`, e.g.
    /// `:saveas!`) skips the overwrite-confirmation prompt for a named
    /// destination.
    SaveAs {
        path: Option<PathBuf>,
        then_quit: bool,
        force: bool,
    },
    /// `:w <path>` / `:wq <path>` — write a snapshot to `path` *without*
    /// changing the buffer's own path (real-vim `:w {file}` semantics: the
    /// user keeps editing the current file).  `then_quit` carries the
    /// `:wq` intent; `force` (`:w!`) skips the overwrite-confirmation
    /// prompt.
    SaveCopy {
        path: PathBuf,
        then_quit: bool,
        force: bool,
    },
    /// A status / error message from an ex command (a `:s` result, a parse
    /// or regex error) for the App to flash on the hint line.  The
    /// substitution itself already ran against `EditorState`; only the
    /// user-facing message bubbles up (the reducer can't flash — that's an
    /// App concern).
    Flash(String),
}

/// Feed one key press to the vim state machine.
pub fn vim_feed(
    vim: &mut VimState,
    editor: &mut EditorState,
    key: KeyEvent,
    viewport_height: usize,
    viewport_width: usize,
) -> VimOutcome {
    // An active command line (`/` `?`, and `:` in CP9) captures every key
    // until the user submits (Enter) or cancels (Esc / Backspace past the
    // start), so it is checked before any sub-mode dispatch.
    if vim.cmdline.is_some() {
        return feed_cmdline(vim, editor, key, viewport_height, viewport_width);
    }
    match vim.sub_mode {
        VimSubMode::Insert => feed_insert(vim, editor, key, viewport_height, viewport_width),
        VimSubMode::Visual | VimSubMode::VisualLine => {
            feed_visual(vim, editor, key, viewport_height, viewport_width)
        }
        // Normal and OperatorPending share the same entry: `feed_normal`
        // branches on `pending_op` to route the operator-pending keys.
        _ => feed_normal(vim, editor, key, viewport_height, viewport_width),
    }
}

// ── Insert ──────────────────────────────────────────────────────────────────

/// In Insert mode `vim_feed` owns only `Esc`; every printable char,
/// `Backspace`, `Enter`, etc. passes through to the unchanged editing
/// pipeline.  So Insert reuses the entire existing editor verbatim.
fn feed_insert(
    vim: &mut VimState,
    editor: &mut EditorState,
    key: KeyEvent,
    vh: usize,
    vw: usize,
) -> VimOutcome {
    match key.code {
        KeyCode::Esc => {
            vim.sub_mode = VimSubMode::Normal;
            vim.reset_pending();
            // Vim moves the cursor one char left on leaving Insert, but
            // never back across a line boundary.
            let (_, col) = editor.cursor.line_col(&editor.buffer);
            if col > 0 {
                editor.cursor.move_left(&editor.buffer);
                after_move(editor, vh, vw);
            }
            VimOutcome::Consumed
        }
        _ => VimOutcome::Passthrough,
    }
}

// ── Command line (`/` `?` `:`) ──────────────────────────────────────────────────

/// Drive the active command line.  Editing keys redraw in place; `Enter`
/// submits and `Esc` (or a backspace past the start) cancels.  A submitted
/// `/` / `?` line becomes a [`VimOutcome::EnterSearch`]; a submitted `:` line
/// is parsed and run by [`submit_ex`]; an empty submit just closes the prompt.
fn feed_cmdline(
    vim: &mut VimState,
    editor: &mut EditorState,
    key: KeyEvent,
    vh: usize,
    vw: usize,
) -> VimOutcome {
    if vim.cmdline.is_none() {
        return VimOutcome::Passthrough;
    }
    // Up/Down recall the per-session command history (oldest commands on Up,
    // back toward the live draft on Down) before the text-field sees the key.
    // Reading the history (a distinct `VimState` field) alongside the mutable
    // `cmdline` borrow relies on disjoint-field borrows, so both are taken by
    // direct field access rather than through a helper.
    if matches!(key.code, KeyCode::Up | KeyCode::Down) {
        let kind = vim.cmdline.as_ref().expect("cmdline is Some").kind;
        let history = match kind {
            CmdLineKind::Ex => &vim.ex_history,
            CmdLineKind::SearchForward | CmdLineKind::SearchBackward => &vim.search_history,
        };
        let cl = vim.cmdline.as_mut().expect("cmdline is Some");
        let input_before = cl.input.clone();
        if key.code == KeyCode::Up {
            cmdline::history_prev(cl, history);
        } else {
            cmdline::history_next(cl, history);
        }
        // History recall rewrites the whole line — re-derive the live
        // preview from it, exactly as for a typed edit below.
        cmdline_live_update(vim, editor, &input_before, vh, vw);
        return VimOutcome::Consumed;
    }
    let cl = vim.cmdline.as_mut().expect("cmdline is Some");
    let kind = cl.kind;
    let input_before = cl.input.clone();
    match cmdline::feed_key(cl, key) {
        CmdLineStep::Editing => {
            cmdline_live_update(vim, editor, &input_before, vh, vw);
            VimOutcome::Consumed
        }
        CmdLineStep::Cancel => {
            vim.cmdline = None;
            match kind {
                CmdLineKind::Ex => {
                    // Esc reverts the previewed text and restores the
                    // pre-preview cursor and scroll.
                    clear_substitute_preview(editor, /*restore_view=*/ true);
                }
                CmdLineKind::SearchForward | CmdLineKind::SearchBackward => {
                    // Esc drops the live search, restoring the pre-prompt
                    // view and any prior hlsearch session.
                    end_incsearch(editor, &mut vim.incsearch);
                }
            }
            VimOutcome::Consumed
        }
        CmdLineStep::Submit(input) => {
            vim.cmdline = None;
            match kind {
                CmdLineKind::Ex => {
                    // Revert the preview BEFORE `submit_ex` so
                    // `execute_substitute` runs against the pristine buffer —
                    // one undo step and the same flash text as a
                    // preview-less submit.  No scroll restore: the execute
                    // path places the cursor (and the view stays where the
                    // preview scrolled it, which is where the edit landed).
                    clear_substitute_preview(editor, /*restore_view=*/ false);
                }
                CmdLineKind::SearchForward | CmdLineKind::SearchBackward => {
                    // Restore the pre-prompt view (and prior session) BEFORE
                    // the `EnterSearch` outcome runs — the App resolves the
                    // cursor-relative focus against the original cursor, so
                    // the submit stays byte-identical to a preview-less one.
                    end_incsearch(editor, &mut vim.incsearch);
                }
            }
            // Record every non-empty submitted line (valid or not, as vim does)
            // so Up can recall it next time the prompt opens.
            if !input.is_empty() {
                vim.record_command(kind, &input);
            }
            match kind {
                // An empty `/` / `?` query closes the prompt with no search.
                CmdLineKind::SearchForward if !input.is_empty() => VimOutcome::EnterSearch {
                    forward: true,
                    query: input,
                },
                CmdLineKind::SearchBackward if !input.is_empty() => VimOutcome::EnterSearch {
                    forward: false,
                    query: input,
                },
                CmdLineKind::Ex => submit_ex(editor, &input, vim.last_visual_range, vh, vw),
                _ => VimOutcome::Consumed,
            }
        }
    }
}

/// Re-derive the open command line's live preview after its text changed:
/// the `:s` substitution preview for a `:` line, the incsearch session for
/// a `/` / `?` line.  A no-op when `before` matches the current input —
/// keys that leave the line unchanged (cursor moves, ignored chords) must
/// skip the recompute, which for a large `:%s` preview costs two full
/// reparses plus a regex scan.  Shared by the typing, history-recall, and
/// bracketed-paste paths so they can't diverge.
pub fn cmdline_live_update(
    vim: &mut VimState,
    editor: &mut EditorState,
    before: &str,
    vh: usize,
    vw: usize,
) {
    let (kind, input) = match vim.cmdline.as_ref() {
        Some(cl) if cl.input != before => (cl.kind, cl.input.clone()),
        _ => return,
    };
    match kind {
        CmdLineKind::Ex => update_substitute_preview(editor, &input, vim.last_visual_range, vh, vw),
        CmdLineKind::SearchForward => {
            update_incsearch(editor, &mut vim.incsearch, &input, true, vh, vw)
        }
        CmdLineKind::SearchBackward => {
            update_incsearch(editor, &mut vim.incsearch, &input, false, vh, vw)
        }
    }
}

/// Parse and run a submitted `:` ex command.  `:w`/`:q`/`:wq` bubble up as
/// App-level outcomes (the App runs the matching `Action`, so the dirty-quit
/// confirm and save flash fire exactly as for the `Ctrl-*` chords); `:s`/`:%s`
/// execute here against the editor (a single-undo regex substitution) and
/// report their result as a `Flash`.  A parse / regex error flashes too; an
/// empty `:` line is a silent no-op.
fn submit_ex(
    editor: &mut EditorState,
    input: &str,
    visual_range: Option<(usize, usize)>,
    vh: usize,
    vw: usize,
) -> VimOutcome {
    if input.trim().is_empty() {
        return VimOutcome::Consumed;
    }
    match parse_ex(input) {
        // A bare `:w` writes to the current path, or — for a never-saved
        // buffer — prompts for one via the Save As modal.
        Ok(ExCommand::Write) => {
            if editor.buffer.path().is_some() {
                VimOutcome::Save
            } else {
                VimOutcome::SaveAs {
                    path: None,
                    then_quit: false,
                    force: false,
                }
            }
        }
        // `:w <path>` — write a copy to the named path, keep the current
        // file.  A trailing `!` forces past the overwrite prompt.
        Ok(ExCommand::WriteCopy { path, force }) => VimOutcome::SaveCopy {
            path: PathBuf::from(path),
            then_quit: false,
            force,
        },
        // `:saveas <path>` — re-point the buffer at the named path.
        Ok(ExCommand::WriteAs { path, force }) => VimOutcome::SaveAs {
            path: Some(PathBuf::from(path)),
            then_quit: false,
            force,
        },
        // `:saveas` with no argument always prompts (the modal does its
        // own overwrite check, so no force is threaded here).
        Ok(ExCommand::SaveAsPrompt) => VimOutcome::SaveAs {
            path: None,
            then_quit: false,
            force: false,
        },
        Ok(ExCommand::Quit) => VimOutcome::Quit { save_first: false },
        Ok(ExCommand::WriteQuit) => {
            if editor.buffer.path().is_some() {
                VimOutcome::Quit { save_first: true }
            } else {
                // No path yet — prompt, then quit once it's written.
                VimOutcome::SaveAs {
                    path: None,
                    then_quit: true,
                    force: false,
                }
            }
        }
        // `:wq <path>` — write a copy, then quit (copy semantics like `:w`).
        Ok(ExCommand::WriteQuitCopy { path, force }) => VimOutcome::SaveCopy {
            path: PathBuf::from(path),
            then_quit: true,
            force,
        },
        // `:x` writes only when the buffer is dirty, then quits — the
        // canonical vim behavior (`:wq` always writes).  A dirty,
        // path-less buffer prompts for a path before quitting.
        Ok(ExCommand::WriteQuitIfModified) => {
            if !editor.dirty {
                VimOutcome::Quit { save_first: false }
            } else if editor.buffer.path().is_some() {
                VimOutcome::Quit { save_first: true }
            } else {
                VimOutcome::SaveAs {
                    path: None,
                    then_quit: true,
                    force: false,
                }
            }
        }
        // `:42` / `:$` — the same jump `42G` makes, resolved through the
        // scoped wrapper like every other motion in this file (the clamp is
        // a no-op for a line jump, which is deliberately unscoped).
        Ok(ExCommand::GoToLine(n)) => {
            let dest = resolve_scoped_motion(editor, Motion::GoToLine(n), 1, CellLimit::Append);
            move_to_offset(editor, dest, vh, vw, /*visual=*/ false);
            VimOutcome::Consumed
        }
        Ok(ExCommand::Substitute(sub)) => match execute_substitute(editor, &sub, visual_range) {
            Ok(0) => VimOutcome::Flash(format!("Pattern not found: {}", sub.pattern)),
            Ok(n) => {
                after_edit(editor, vh, vw);
                let plural = if n == 1 { "" } else { "s" };
                VimOutcome::Flash(format!("{n} substitution{plural}"))
            }
            Err(e) => VimOutcome::Flash(e.to_string()),
        },
        Err(e) => VimOutcome::Flash(e.to_string()),
    }
}

// ── Normal ────────────────────────────────────────────────────────────────────

fn feed_normal(
    vim: &mut VimState,
    editor: &mut EditorState,
    key: KeyEvent,
    vh: usize,
    vw: usize,
) -> VimOutcome {
    // `r{c}`: the previous key was `r`; this key is the replacement.  A
    // plain printable char replaces; anything else (Esc, an arrow, a
    // `Ctrl-*` chord) cancels the pending replace with no edit.
    if vim.pending_replace {
        return feed_replace_char(vim, editor, key, vh, vw);
    }
    // A pending `f`/`F`/`t`/`T` (possibly behind an operator, e.g. `df`)
    // is awaiting its target char; resolve it before anything else.
    if let Some(kind) = vim.pending_find {
        return feed_find_char(vim, editor, kind, key, vh, vw, /*visual=*/ false);
    }
    // A pending text object — `i`/`a` was pressed behind an operator (`di`,
    // `ca`) and this key is the object char (`w`, `(`, `"`, …).
    if let Some(inner) = vim.pending_text_object {
        return feed_text_object(vim, editor, inner, key, vh, vw, /*visual=*/ false);
    }
    // `Ctrl-Backspace` / `Ctrl-Delete` are the default keymap's word-delete
    // chords (`DeleteWordBack` / `DeleteWordForward`).  Normal must never
    // mutate the buffer, so intercept them ahead of the passthrough
    // fallthrough (which would route them to those actions) and treat them
    // as the plain `Backspace` / `Delete` cursor motions — Ctrl-H is
    // move-left in real vim too.
    if is_ctrl_backspace(&key) || is_ctrl_delete(&key) {
        vim.sub_mode = VimSubMode::Normal;
        let dir = if is_ctrl_delete(&key) { 'l' } else { 'h' };
        for _ in 0..count_of(vim) {
            feed_hjkl(editor, dir, vh, vw, /*charwise_visual=*/ false);
        }
        vim.reset_pending();
        return VimOutcome::Consumed;
    }
    if is_passthrough_chord(&key) {
        // The chord fires its app action via the default handler; a
        // half-typed operator / count must not linger behind it (`d`
        // then `Ctrl-S` would otherwise treat the next key as a delete
        // target).  Cancel any in-progress parse and drop OperatorPending
        // back to Normal before falling through.
        if vim.sub_mode == VimSubMode::OperatorPending {
            vim.sub_mode = VimSubMode::Normal;
        }
        vim.reset_pending();
        return VimOutcome::Passthrough;
    }
    match key.code {
        KeyCode::Esc => {
            // Esc cancels any in-progress operator / count and leaves
            // OperatorPending back in Normal.  It also dismisses an active
            // search's highlights (vim's `:noh`), keeping the cursor and
            // scroll where they are — only a *navigate* search reaches here
            // (a capturing replace flow defers to `DefaultHandler`, so vim
            // never sees its `Esc`).  `exit_search` leaves the user on the
            // match they navigated to (search is a motion — no scroll-back).
            // Finally it drops any lingering selection (e.g. one left by a
            // mouse drag) — both the buffer and its paint, mirroring `Esc`
            // in Visual — so Normal never sits on a stale highlight.
            vim.sub_mode = VimSubMode::Normal;
            vim.reset_pending();
            editor.exit_search();
            editor.selection = None;
            VimOutcome::Consumed
        }
        KeyCode::Char(c) => feed_command_char(vim, editor, c, vh, vw, /*visual=*/ false),
        // `Tab` / `Shift-Tab` walk the active search matches, exactly like
        // `n` / `N`, so a vim navigate search is navigable however it was
        // started (`/`, `?`, `Ctrl-F`, or the palette).  With no search
        // active they are inert — never `InsertTab` (Normal must not edit).
        KeyCode::Tab if editor.search.is_some() => {
            search_repeat(editor, /*forward=*/ true, count_of(vim), vh, vw);
            vim.reset_pending();
            VimOutcome::Consumed
        }
        KeyCode::BackTab if editor.search.is_some() => {
            search_repeat(editor, /*forward=*/ false, count_of(vim), vh, vw);
            vim.reset_pending();
            VimOutcome::Consumed
        }
        // `Tab` inside a table advances to the next cell, mirroring
        // `Shift-Tab` → `TablePrevCell` (which already passes through and is
        // a no-op outside a table).  Passing through lets the default keymap
        // map `Tab` → `InsertTab`, whose in-table branch calls
        // `table_next_cell`.  Outside a table `InsertTab` would insert
        // spaces, so Tab stays inert there (Normal must not edit).
        KeyCode::Tab if editor.cursor_in_table() => {
            vim.reset_pending();
            VimOutcome::Passthrough
        }
        // Editing keys never mutate the buffer in Normal (vim's rule): the
        // global keymap would turn these into `DeleteCharBack` / `Newline`
        // / `InsertTab`, so they must be consumed here.  `Backspace` moves
        // left, `Delete` moves right, `Enter` drops to the next line's
        // first non-blank; `Tab` (no search) is inert.  Any in-progress
        // operator / count is cancelled.
        KeyCode::Backspace | KeyCode::Delete | KeyCode::Enter | KeyCode::Tab => {
            vim.sub_mode = VimSubMode::Normal;
            let n = count_of(vim);
            match key.code {
                KeyCode::Backspace => {
                    for _ in 0..n {
                        feed_hjkl(editor, 'h', vh, vw, /*charwise_visual=*/ false);
                    }
                }
                KeyCode::Delete => {
                    for _ in 0..n {
                        feed_hjkl(editor, 'l', vh, vw, /*charwise_visual=*/ false);
                    }
                }
                KeyCode::Enter => {
                    for _ in 0..n {
                        feed_hjkl(editor, 'j', vh, vw, /*charwise_visual=*/ false);
                    }
                    move_first_non_blank(editor);
                    after_move(editor, vh, vw);
                }
                _ => {} // Tab with no search: inert.
            }
            vim.reset_pending();
            VimOutcome::Consumed
        }
        // Other non-character keys (arrows, Home/End, PageUp/Down, …) keep
        // their default bindings so navigation still works in Normal.
        _ => VimOutcome::Passthrough,
    }
}

// ── Visual / Visual-Line ──────────────────────────────────────────────────────

/// Visual handling: motions extend the shared `selection`; `Esc` leaves
/// Visual back to Normal and clears the selection.  CP6 wires the Visual
/// commands — the operators `d`/`x`/`y`/`c`/`s`/`>`/`<`/`~`/`J`, `o` (swap
/// ends), and the `v`↔`V` toggle — intercepted ahead of the shared
/// motion path so motions still extend the selection while a command key
/// acts on it.  `Ctrl-*` chords still pass through, so `Ctrl-C` copies the
/// highlighted span via the existing clipboard action (VisualLine copy/cut
/// is widened to whole lines at the App dispatch layer).
fn feed_visual(
    vim: &mut VimState,
    editor: &mut EditorState,
    key: KeyEvent,
    vh: usize,
    vw: usize,
) -> VimOutcome {
    // A pending Visual `r{c}` is awaiting its replacement char.
    if vim.pending_replace {
        return feed_visual_replace_char(vim, editor, key, vh, vw);
    }
    // A pending `f`/`F`/`t`/`T` is awaiting its target char (this only ever
    // extends the selection — Visual operators act on the existing span).
    if let Some(kind) = vim.pending_find {
        return feed_find_char(vim, editor, kind, key, vh, vw, /*visual=*/ true);
    }
    // A pending text object — `i`/`a` was pressed and this key is the object
    // char; in Visual it sets the selection to the object's range.
    if let Some(inner) = vim.pending_text_object {
        return feed_text_object(vim, editor, inner, key, vh, vw, /*visual=*/ true);
    }
    // Ctrl-Backspace / Ctrl-Delete would otherwise pass through to the
    // default keymap's word-delete actions and edit through the selection.
    // Visual must not mutate, so treat them as the left / right movers that
    // extend the selection, exactly like plain Backspace / Delete below.
    if is_ctrl_backspace(&key) || is_ctrl_delete(&key) {
        let dir = if is_ctrl_delete(&key) { 'l' } else { 'h' };
        feed_hjkl(editor, dir, vh, vw, is_charwise_visual(vim));
        extend_selection(editor);
        vim.reset_pending();
        return VimOutcome::Consumed;
    }
    if is_passthrough_chord(&key) {
        return VimOutcome::Passthrough;
    }
    match key.code {
        KeyCode::Esc => {
            exit_visual(vim, editor);
            VimOutcome::Consumed
        }
        KeyCode::Char(c) => match feed_visual_command(vim, editor, c, vh, vw) {
            // A Visual command (operator / swap / toggle) acted on the
            // selection; otherwise fall through to the shared motion / count
            // / find / `gg` path so motions extend the selection.
            Some(out) => out,
            None => feed_command_char(vim, editor, c, vh, vw, /*visual=*/ true),
        },
        // Arrow keys mirror `h j k l` in Visual: extend the selection
        // rather than passing through to the default handler (which would
        // move the cursor *and* clear the selection).  `Backspace` /
        // `Delete` / `Enter` join them as left / right / down movers so
        // they extend the selection instead of editing through it.
        KeyCode::Left
        | KeyCode::Right
        | KeyCode::Up
        | KeyCode::Down
        | KeyCode::Backspace
        | KeyCode::Delete
        | KeyCode::Enter => {
            let dir = match key.code {
                KeyCode::Left | KeyCode::Backspace => 'h',
                KeyCode::Right | KeyCode::Delete => 'l',
                KeyCode::Up => 'k',
                _ => 'j', // Down, Enter
            };
            feed_hjkl(editor, dir, vh, vw, is_charwise_visual(vim));
            extend_selection(editor);
            vim.reset_pending();
            VimOutcome::Consumed
        }
        // `Tab` / `Shift-Tab` are inert in Visual — never `InsertTab`,
        // which would replace the selection.
        KeyCode::Tab | KeyCode::BackTab => {
            vim.reset_pending();
            VimOutcome::Consumed
        }
        _ => VimOutcome::Passthrough,
    }
}

/// Leave Visual / Visual-Line, dropping the selection.
fn exit_visual(vim: &mut VimState, editor: &mut EditorState) {
    vim.sub_mode = VimSubMode::Normal;
    vim.visual_anchor = None;
    vim.reset_pending();
    editor.selection = None;
}

/// Visual-mode command keys: the operators, `o` (swap ends), and the
/// `v`/`V` toggle.  Returns `Some(outcome)` when `c` is a Visual command;
/// `None` lets the shared motion / count / find / `gg` path handle it (so
/// motions still extend the selection and counts accumulate).
fn feed_visual_command(
    vim: &mut VimState,
    editor: &mut EditorState,
    c: char,
    vh: usize,
    vw: usize,
) -> Option<VimOutcome> {
    // The line-oriented Visual commands reach the same rows Normal's `J` /
    // `>>` / `<<` do, so they refuse on the same grounds — guarding only the
    // Normal forms would leave the corruption one keystroke away.  The
    // question is asked of the *selection*, not the cursor: a selection
    // anchored in a table whose cursor has since moved out still reshapes
    // the rows it covers.
    if matches!(c, 'J' | '>' | '<') && visual_selection_touches_a_table(editor) {
        leave_visual_to_normal(vim, editor, vh, vw);
        return Some(VimOutcome::Flash(TABLE_STRUCTURAL_REFUSAL.to_owned()));
    }
    match c {
        'd' | 'x' => return Some(run_visual_operator(vim, editor, Operator::Delete, vh, vw)),
        'y' => return Some(run_visual_operator(vim, editor, Operator::Yank, vh, vw)),
        'c' | 's' => return Some(run_visual_operator(vim, editor, Operator::Change, vh, vw)),
        '>' => run_visual_indent(vim, editor, /*right=*/ true, vh, vw),
        '<' => run_visual_indent(vim, editor, /*right=*/ false, vh, vw),
        '~' => run_visual_toggle_case(vim, editor, vh, vw),
        // `u` / `U`: force the selection to lower / upper case (in Visual,
        // `u` is *not* undo — that's a Normal-only key).
        'u' => run_visual_set_case(vim, editor, /*upper=*/ false, vh, vw),
        'U' => run_visual_set_case(vim, editor, /*upper=*/ true, vh, vw),
        'J' => run_visual_join(vim, editor, vh, vw),
        // `p` / `P`: replace the selection with the unnamed register.
        'p' | 'P' => return Some(run_visual_paste(vim, editor, vh, vw)),
        // `r{c}`: arm the replace and wait for the target char (resolved by
        // `feed_visual_replace_char`).  Stays in Visual until then.
        'r' => {
            vim.pending_replace = true;
            return Some(VimOutcome::Pending);
        }
        // `i` / `a`: arm a text object (`viw`, `va(`); the next key (the
        // object char) sets the selection via `feed_text_object`.
        'i' | 'a' => {
            vim.pending_text_object = Some(c == 'i');
            return Some(VimOutcome::Pending);
        }
        // `:`: open the ex command line pre-filled with the `'<,'>` range
        // spanning the selection's lines (vim's Visual-mode `:`).  The range
        // is captured now — the concrete bounds a `:'<,'>s` runs over — then
        // Visual exits (the highlight goes, matching vim; the marks persist on
        // `last_visual_range`).  Editing / submission is driven by
        // `feed_cmdline`, exactly as for a Normal-mode `:`.
        ':' => {
            if let Some(sel) = editor.selection {
                vim.last_visual_range = Some(visual_line_bounds(&sel, &editor.buffer));
            }
            exit_visual(vim, editor);
            vim.cmdline = Some(CmdLineState::with_input(
                CmdLineKind::Ex,
                "'<,'>".to_owned(),
            ));
            return Some(VimOutcome::Pending);
        }
        'o' => swap_visual_ends(vim, editor, vh, vw),
        // `v` / `V`: pressing the *current* mode's key exits to Normal; the
        // other key switches between charwise and linewise, keeping the
        // anchor and selection (a lossless toggle — `selection` is never
        // snapped).
        'v' => toggle_visual_mode(vim, editor, /*line=*/ false),
        'V' => toggle_visual_mode(vim, editor, /*line=*/ true),
        _ => return None,
    }
    Some(VimOutcome::Consumed)
}

/// Run `f` with the active Visual selection.  If the selection is somehow
/// absent (it never should be while in a Visual sub-mode), bail to Normal via
/// `exit_visual` instead — so every Visual command that needs the span shares
/// one early-exit rather than repeating it.  `Selection` is `Copy`, so the
/// closure receives it by value alongside fresh `&mut` borrows.
fn with_selection(
    vim: &mut VimState,
    editor: &mut EditorState,
    f: impl FnOnce(&mut VimState, &mut EditorState, Selection),
) {
    let Some(sel) = editor.selection else {
        exit_visual(vim, editor);
        return;
    };
    f(vim, editor, sel);
}

/// Run a `d`/`y`/`c` operator over the current Visual selection, then leave
/// Visual.  Both spans come from the shared `vim_ops::visual` helpers — the
/// inclusive charwise span or the whole-line expansion — so the edit matches
/// the highlight exactly (see §2.6).  VisualLine yanks linewise.  `c`/`s`
/// enter Insert; everything else returns to Normal.
fn run_visual_operator(
    vim: &mut VimState,
    editor: &mut EditorState,
    op: Operator,
    vh: usize,
    vw: usize,
) -> VimOutcome {
    let mut outcome = VimOutcome::Consumed;
    with_selection(vim, editor, |vim, editor, sel| {
        let range = visual_op_range(vim, editor, &sel);
        // The Visual twin of `run_operator`'s guard: a VisualLine span over
        // a header row, or a charwise drag across two cells, reaches the
        // same corruption the Normal-mode commands are held back from.
        if let Some(reason) = mutating_table_break(editor, op, &range) {
            leave_visual_to_normal(vim, editor, vh, vw);
            outcome = VimOutcome::Flash(reason.message().to_owned());
            return;
        }
        let res = execute_operator(editor, op, range);
        vim.visual_anchor = None;
        editor.selection = None;
        fold_op_result(vim, editor, res, vh, vw);
    });
    outcome
}

/// The range a Visual operator would run over: whole lines in VisualLine,
/// the inclusive charwise span otherwise.
fn visual_op_range(vim: &VimState, editor: &EditorState, sel: &Selection) -> OpRange {
    if vim.sub_mode == VimSubMode::VisualLine {
        let (first, last) = visual_line_bounds(sel, &editor.buffer);
        OpRange::Lines { first, last }
    } else {
        OpRange::Chars(visual_charwise_range(sel, &editor.buffer))
    }
}

/// Does the active Visual selection overlap a table?  Asked by the
/// commands that reshape lines in place (`J`, `>`, `<`), which have no
/// range to hand [`mutating_table_break`].  Falls back to the cursor when
/// there is somehow no selection.
fn visual_selection_touches_a_table(editor: &EditorState) -> bool {
    match editor.selection {
        Some(sel) => {
            let (first, last) = visual_line_bounds(&sel, &editor.buffer);
            lines_touch_a_table(editor, first, last)
        }
        None => editor.cursor_in_table(),
    }
}

/// `>` / `<` in Visual: indent / outdent every line the selection touches
/// (linewise even from charwise Visual, matching vim), then leave Visual.
/// Indent never fills the register (it reuses the `>>` / `<<` path).
fn run_visual_indent(
    vim: &mut VimState,
    editor: &mut EditorState,
    right: bool,
    vh: usize,
    vw: usize,
) {
    with_selection(vim, editor, |vim, editor, sel| {
        let (first, last) = visual_line_bounds(&sel, &editor.buffer);
        ensure_editing(editor);
        indent_lines(editor, first, last, right, crate::constants::INDENT_WIDTH);
        leave_visual_to_normal(vim, editor, vh, vw);
    });
}

/// The char range a Visual *range edit* (`~`/`u`/`U`/`r`/`p`) operates on:
/// the inclusive charwise span (`visual_charwise_range`), or the
/// line-expanded whole-line range in VisualLine (`visual_line_char_range`) —
/// the same shared helpers the render overlay and the operators use, so the
/// edit always matches the highlight.
fn visual_edit_range(vim: &VimState, editor: &EditorState, sel: &Selection) -> Range<usize> {
    if vim.sub_mode == VimSubMode::VisualLine {
        visual_line_char_range(sel, &editor.buffer)
    } else {
        visual_charwise_range(sel, &editor.buffer)
    }
}

/// `~` in Visual: toggle the case of the selection — the charwise span, or
/// the line-expanded range in VisualLine — as one delta, then leave Visual.
fn run_visual_toggle_case(vim: &mut VimState, editor: &mut EditorState, vh: usize, vw: usize) {
    with_selection(vim, editor, |vim, editor, sel| {
        let range = visual_edit_range(vim, editor, &sel);
        ensure_editing(editor);
        toggle_case_range(editor, range.start, range.end);
        leave_visual_to_normal(vim, editor, vh, vw);
    });
}

/// `u` / `U` in Visual: force the selection to lower (`upper == false`) or
/// upper case as one delta, then leave Visual.  Operates on the charwise
/// span or the line-expanded range, exactly like `~`.
fn run_visual_set_case(
    vim: &mut VimState,
    editor: &mut EditorState,
    upper: bool,
    vh: usize,
    vw: usize,
) {
    with_selection(vim, editor, |vim, editor, sel| {
        let range = visual_edit_range(vim, editor, &sel);
        ensure_editing(editor);
        set_case_range(editor, range.start, range.end, upper);
        leave_visual_to_normal(vim, editor, vh, vw);
    });
}

/// `p` / `P` in Visual: replace the selection with the unnamed register as a
/// single delta, then leave Visual.  The register is left **unchanged** — a
/// deliberate departure from vim's default (which clobbers the register with
/// the deleted text), so the same yank can be pasted over several selections
/// in turn (the widely-preferred behavior).  Charwise Visual replaces the raw
/// span; VisualLine replaces the whole lines.  A charwise register dropped
/// over whole lines gets a trailing newline so it keeps its own line.  An
/// empty register is a no-op that still leaves Visual.
fn run_visual_paste(
    vim: &mut VimState,
    editor: &mut EditorState,
    vh: usize,
    vw: usize,
) -> VimOutcome {
    let mut outcome = VimOutcome::Consumed;
    with_selection(vim, editor, |vim, editor, sel| {
        if vim.register.text.is_empty() {
            leave_visual_to_normal(vim, editor, vh, vw);
            return;
        }
        let line_mode = vim.sub_mode == VimSubMode::VisualLine;
        let range = visual_edit_range(vim, editor, &sel);
        // VisualLine replaces whole lines (range ends in '\n'); a charwise
        // register has no trailing newline, so add one to keep it on its own line.
        let text = if line_mode && !vim.register.linewise {
            format!("{}\n", vim.register.text)
        } else {
            vim.register.text.clone()
        };
        // Replacing a selection is a delete plus an insert, so it has to
        // clear both halves of the guard: the range must be safe to remove,
        // and the payload must be safe to drop in its place.  The question is
        // asked of `text` and the *selection's* shape, not of the register's
        // own — the two disagree in both directions here, and each mismatch
        // broke the table: a linewise row register dropped into a charwise
        // in-cell selection carries a `|` and a newline into the middle of a
        // cell, and a charwise register over a VisualLine row replaces that
        // row with a line that isn't a table row at all.
        if let Some(message) = paste_over_range_refusal(editor, &range, &text, line_mode) {
            leave_visual_to_normal(vim, editor, vh, vw);
            outcome = VimOutcome::Flash(message);
            return;
        }
        ensure_editing(editor);
        replace_range_with(editor, range.start, range.end, &text);
        leave_visual_to_normal(vim, editor, vh, vw);
    });
    outcome
}

/// The refusal for dropping `text` over `range`, or `None` when both the
/// removal and the insertion are safe.
///
/// `linewise` describes the *payload as it will land* — the selection's own
/// shape, not the register's — because `run_visual_paste` has already
/// reconciled the two by the time it asks.  Passing the register's flag
/// instead lets each mismatch through: a linewise register keeps its `|` and
/// its newline when it is spliced into a charwise selection, and a charwise
/// register grows a newline when it replaces a whole line.
fn paste_over_range_refusal(
    editor: &EditorState,
    range: &Range<usize>,
    text: &str,
    linewise: bool,
) -> Option<String> {
    let rope = editor.buffer.rope();
    let len = rope.len_chars();
    let start = rope.char_to_byte(range.start.min(len));
    let end = rope.char_to_byte(range.end.min(len));
    if let Some(reason) = range_breaks_a_table(editor, start, end) {
        return Some(reason.message().to_owned());
    }
    match table_paste_plan(editor, text, linewise, /*after=*/ true) {
        TablePaste::Refused => Some(TABLE_PASTE_REFUSAL.to_owned()),
        _ => None,
    }
}

/// Resolve a pending Visual `r{c}`: replace every char in the selection (the
/// charwise span or the line-expanded range) with the printable key `c`, then
/// leave Visual.  A non-char key or a `Ctrl-*` chord cancels with no edit and
/// keeps the Visual selection (vim's behavior).
fn feed_visual_replace_char(
    vim: &mut VimState,
    editor: &mut EditorState,
    key: KeyEvent,
    vh: usize,
    vw: usize,
) -> VimOutcome {
    match key.code {
        KeyCode::Char(c) if !is_passthrough_chord(&key) => {
            if let Some(sel) = editor.selection {
                let range = visual_edit_range(vim, editor, &sel);
                // Same-length or not, this overwrites every char in the
                // span — including the `|` delimiters of any row it
                // crosses.
                if let Some(reason) =
                    op_range_breaks_a_table(editor, &OpRange::Chars(range.start..range.end))
                {
                    leave_visual_to_normal(vim, editor, vh, vw);
                    return VimOutcome::Flash(reason.message().to_owned());
                }
                ensure_editing(editor);
                replace_char_range(editor, range.start, range.end, c);
            }
            leave_visual_to_normal(vim, editor, vh, vw);
        }
        // Cancel the pending replace but stay in Visual with the selection.
        _ => vim.pending_replace = false,
    }
    VimOutcome::Consumed
}

/// `J` in Visual: join every line the selection touches into one (a
/// single-line selection joins with the line below, matching vim), then
/// leave Visual.
fn run_visual_join(vim: &mut VimState, editor: &mut EditorState, vh: usize, vw: usize) {
    with_selection(vim, editor, |vim, editor, sel| {
        let (first, last) = visual_line_bounds(&sel, &editor.buffer);
        ensure_editing(editor);
        editor.cursor.offset = editor.buffer.line_to_char(first);
        editor.cursor.preferred_col = editor.cursor.cell_col(&editor.buffer);
        // `join_lines(count)` performs `max(2, count) - 1` joins, so a
        // single-line span (`last == first`) still joins one line below.
        let count = (last - first + 1) as u32;
        join_lines(editor, count);
        leave_visual_to_normal(vim, editor, vh, vw);
    });
}

/// `o` in Visual: swap the anchor and active ends so a following motion
/// grows the other side.  Stays in Visual.
fn swap_visual_ends(vim: &mut VimState, editor: &mut EditorState, vh: usize, vw: usize) {
    if let Some(sel) = editor.selection.as_mut() {
        std::mem::swap(&mut sel.anchor, &mut sel.active);
        let active = sel.active;
        vim.visual_anchor = Some(sel.anchor);
        editor.cursor.offset = active.min(editor.buffer.len_chars());
        editor.cursor.preferred_col = editor.cursor.cell_col(&editor.buffer);
        after_move(editor, vh, vw);
    }
    vim.reset_pending();
}

/// `v` / `V` while already in Visual: toggle between charwise and linewise,
/// or exit to Normal when the pressed key matches the current mode.  The
/// anchor and selection survive a switch (the line expansion is recomputed
/// on demand, so nothing is lost).
///
/// `V`→`v` is the second door into charwise Visual, so it owes the same
/// append-slot pull-back `enter_visual` performs — and owes it on *both*
/// ends, since a linewise span's anchor and cursor are independent (`V`,
/// `$`, `v` parks the cursor on the slot; add an `o` and it is the anchor
/// instead).  A linewise span covers whole lines however its ends sit, so
/// the `v`→`V` direction needs nothing.
fn toggle_visual_mode(vim: &mut VimState, editor: &mut EditorState, line: bool) {
    let target = if line {
        VimSubMode::VisualLine
    } else {
        VimSubMode::Visual
    };
    if vim.sub_mode == target {
        exit_visual(vim, editor);
    } else {
        vim.sub_mode = target;
        if !line {
            pull_cursor_into_cell(editor);
            pull_anchor_into_cell(vim, editor);
            // The span the operators read is `EditorState::selection`, and
            // its active end still holds the pre-pull cursor.
            extend_selection(editor);
        }
        vim.reset_pending();
    }
}

/// Drop the Visual selection and return to Normal after a Visual edit that
/// does not enter Insert (`>`/`<`/`~`/`J`).
fn leave_visual_to_normal(vim: &mut VimState, editor: &mut EditorState, vh: usize, vw: usize) {
    vim.visual_anchor = None;
    editor.selection = None;
    vim.reset_pending();
    vim.sub_mode = VimSubMode::Normal;
    after_edit(editor, vh, vw);
}

// ── Shared command dispatch ────────────────────────────────────────────────────

/// Handle one `Char` key in Normal, OperatorPending, or Visual.  When
/// `visual` is set, a motion *extends* the selection (updating its active
/// end) instead of clearing it, and the Insert-entry / Visual-entry /
/// operator keys are inert (those belong to Normal).
fn feed_command_char(
    vim: &mut VimState,
    editor: &mut EditorState,
    c: char,
    vh: usize,
    vw: usize,
    visual: bool,
) -> VimOutcome {
    // `gg`: the first `g` is pending; the second resolves DocStart (or,
    // mid-operator, the linewise `dgg` span).  Resolved *before* count
    // accumulation so a stray `g` followed by a digit can't leave
    // `pending_g` set while the digit grows the count.
    if vim.pending_g {
        vim.pending_g = false;
        if c == 'g' {
            // `5gg` is `5G`: the count reached `vim.count` before the first
            // `g`, so it is a line number by the time we get here.
            let motion = line_jump(Motion::DocStart, operand_count(vim));
            if let Some(operator) = vim.pending_op.and_then(operator_kind) {
                let range = resolve_scoped_op_range(editor, motion, 1);
                return run_operator(vim, editor, operator, range, vh, vw);
            }
            apply_motion(
                editor,
                motion,
                count_of(vim),
                vh,
                vw,
                visual,
                cell_limit(vim),
            );
        }
        // Unknown `g`-command (or `gg` resolved above): clear the parse and
        // drop OperatorPending back to Normal.  Visual keeps its sub-mode.
        if !visual {
            vim.sub_mode = VimSubMode::Normal;
        }
        vim.reset_pending();
        return VimOutcome::Consumed;
    }

    // Operator-pending: an operator (`d`/`c`/`y`) is awaiting its motion.
    if let Some(op) = vim.pending_op {
        return feed_operator_pending(vim, editor, op, c, vh, vw);
    }

    // Count accumulation.  A leading `0` (no count yet) is the line-start
    // motion; a `0` *after* any `1`–`9` is the digit zero.
    if is_count_digit(c, vim.count) {
        vim.count = Some(accumulate(vim.count, c));
        return VimOutcome::Pending;
    }

    if c == 'g' {
        vim.pending_g = true;
        return VimOutcome::Pending;
    }

    // Operators enter OperatorPending (Normal only — Visual operators are
    // CP6).
    if !visual {
        if let Some(op) = operator_for(c) {
            vim.pending_op = Some(op);
            vim.sub_mode = VimSubMode::OperatorPending;
            return VimOutcome::Pending;
        }
    }

    let count = count_of(vim);

    // `f`/`F`/`t`/`T`: arm a pending find and wait for the target char
    // (kept count intact so `3fx` finds the third `x`).
    if let Some(kind) = find_kind_for(c) {
        vim.pending_find = Some(kind);
        return VimOutcome::Pending;
    }

    // `;` / `,`: replay (or reverse) the last find.  `resolve_find_repeat`
    // skips an adjacent match for a `t`/`T` repeat so `;` never gets stuck
    // one char before the same target.
    if c == ';' || c == ',' {
        if let Some((kind, target)) = vim.last_find {
            let kind = if c == ',' { reverse_find(kind) } else { kind };
            let dest =
                resolve_find_repeat(&editor.buffer, editor.cursor.offset, target, kind, count);
            // `resolve_find_repeat` is its own resolver, so the cell clamp
            // has to be applied here rather than inheriting it from
            // `resolve_scoped_motion` — same policy, same classifier.
            let dest = scope_offset(
                editor,
                Motion::FindChar(target, kind),
                dest,
                cell_limit(vim),
            );
            move_to_offset(editor, dest, vh, vw, visual);
        }
        vim.reset_pending();
        return VimOutcome::Consumed;
    }

    // Pure motions resolved by `vim_ops::motion`.  `G` alone among them
    // reinterprets the count as a line number (`line_jump`).
    if let Some(motion) = motion_for(c) {
        let motion = line_jump(motion, operand_count(vim));
        apply_motion(editor, motion, count, vh, vw, visual, cell_limit(vim));
        vim.reset_pending();
        return VimOutcome::Consumed;
    }

    // `h j k l` keep their bespoke table-aware handling (they mutate the
    // editor and manage the viewport themselves), so they're not part of
    // the offset-only `resolve_motion` set.  The count repeats the step.
    if matches!(c, 'h' | 'l' | 'j' | 'k') {
        if !visual {
            clear_selection(editor);
        }
        let charwise_visual = is_charwise_visual(vim);
        for _ in 0..count {
            feed_hjkl(editor, c, vh, vw, charwise_visual);
        }
        if visual {
            extend_selection(editor);
        }
        vim.reset_pending();
        return VimOutcome::Consumed;
    }

    // Single-key edits and Insert / Visual entries act only from Normal.
    if !visual {
        match c {
            // `x`/`X`/`D`/`C`/`Y` are spelled in terms of the operator
            // machinery so they share the single-delta / register path.
            'x' => {
                let range = resolve_scoped_op_range(editor, Motion::Right, count);
                return run_operator(vim, editor, Operator::Delete, range, vh, vw);
            }
            'X' => {
                let range = resolve_scoped_op_range(editor, Motion::Left, count);
                return run_operator(vim, editor, Operator::Delete, range, vh, vw);
            }
            'D' => {
                let range = resolve_scoped_op_range(editor, Motion::LineEnd, count);
                return run_operator(vim, editor, Operator::Delete, range, vh, vw);
            }
            'C' => {
                let range = resolve_scoped_op_range(editor, Motion::LineEnd, count);
                return run_operator(vim, editor, Operator::Change, range, vh, vw);
            }
            'Y' => {
                let range = doubled_line_range(&editor.buffer, editor.cursor.offset, count);
                return run_operator(vim, editor, Operator::Yank, range, vh, vw);
            }
            'p' => {
                let outcome = paste_register(vim, editor, count, /*after=*/ true, vh, vw);
                vim.reset_pending();
                return outcome;
            }
            'P' => {
                let outcome = paste_register(vim, editor, count, /*after=*/ false, vh, vw);
                vim.reset_pending();
                return outcome;
            }
            // `r{c}`: arm the replace and wait for the next key; keep the
            // accumulated count (`3rx` replaces three chars).
            'r' => {
                vim.pending_replace = true;
                return VimOutcome::Pending;
            }
            '~' => {
                toggle_case(editor, count);
                after_edit(editor, vh, vw);
                vim.reset_pending();
            }
            'J' => {
                // Joining two table rows produces one malformed line — and
                // so does joining the line above a table onto its header,
                // which is why the span reaches past the cursor's own line.
                // It reaches exactly as far as `join_lines` does and no
                // further: `J` and `2J` both make one join, `3J` two, so the
                // last line consumed is `max(count, 2) - 1` below the cursor.
                let line = editor.buffer.char_to_line(editor.cursor.offset);
                let last = line + count.max(2) as usize - 1;
                if lines_touch_a_table(editor, line, last) {
                    vim.reset_pending();
                    return VimOutcome::Flash(TABLE_STRUCTURAL_REFUSAL.to_owned());
                }
                join_lines(editor, count);
                after_edit(editor, vh, vw);
                vim.reset_pending();
            }
            // `u`: undo, reusing the existing history path (so dirty / list
            // bookkeeping match a normal undo).  `count` repeats it (`3u`).
            'u' => {
                for _ in 0..count {
                    edit_ops::apply(editor, Action::Undo, vh, vw);
                }
                vim.reset_pending();
            }
            'i' => {
                enter_insert(vim, editor);
                vim.reset_pending();
            }
            'a' => {
                // Append after the cursor, but never across the newline: at
                // end-of-line the insertion point is already past the last
                // char, so stepping right would land on the next line.
                let line = editor.buffer.char_to_line(editor.cursor.offset);
                if editor.cursor.offset < line_end_offset(&editor.buffer, line) {
                    editor.cursor.move_right(&editor.buffer);
                }
                enter_insert(vim, editor);
                after_move(editor, vh, vw);
                vim.reset_pending();
            }
            // `I` / `A` insert at the start / end of the *cell* inside a
            // table — the row's `|` delimiters aren't content, so the line
            // start and line end are never useful insertion points there.
            'I' => {
                match cell_scope(editor) {
                    Some(scope) => editor.place_cursor(scope.start),
                    None => move_first_non_blank(editor),
                }
                enter_insert(vim, editor);
                after_move(editor, vh, vw);
                vim.reset_pending();
            }
            'A' => {
                match cell_scope(editor) {
                    Some(scope) => editor.place_cursor(scope.end),
                    None => editor.cursor.move_line_end(&editor.buffer),
                }
                enter_insert(vim, editor);
                after_move(editor, vh, vw);
                vim.reset_pending();
            }
            'o' => {
                open_line(vim, editor, /*below=*/ true, vh, vw);
                vim.reset_pending();
            }
            'O' => {
                open_line(vim, editor, /*below=*/ false, vh, vw);
                vim.reset_pending();
            }
            'v' => {
                enter_visual(vim, editor, /*line=*/ false);
                vim.reset_pending();
            }
            'V' => {
                enter_visual(vim, editor, /*line=*/ true);
                vim.reset_pending();
            }
            // `/` `?`: open the command-line search prompt.  The next keys
            // are captured by `feed_cmdline` until Enter / Esc.
            '/' => {
                start_cmdline(vim, CmdLineKind::SearchForward);
                return VimOutcome::Pending;
            }
            '?' => {
                start_cmdline(vim, CmdLineKind::SearchBackward);
                return VimOutcome::Pending;
            }
            // `:`: open the ex command line (`:w`/`:q`/`:wq`/`:s`/`:%s`),
            // captured by `feed_cmdline` until Enter / Esc.
            ':' => {
                start_cmdline(vim, CmdLineKind::Ex);
                return VimOutcome::Pending;
            }
            // `n` / `N`: advance / retreat over the active search matches
            // (a no-op when no search is active).  Honors the count (`3n`).
            'n' => {
                search_repeat(editor, /*forward=*/ true, count, vh, vw);
                vim.reset_pending();
            }
            'N' => {
                search_repeat(editor, /*forward=*/ false, count, vh, vw);
                vim.reset_pending();
            }
            // `*` / `#`: search the word under the cursor forward / backward.
            // Emits `EnterSearch` (the App runs the search); a no-op when the
            // line has no keyword at/after the cursor.
            '*' => {
                let outcome = search_word_outcome(editor, /*forward=*/ true);
                vim.reset_pending();
                return outcome;
            }
            '#' => {
                let outcome = search_word_outcome(editor, /*forward=*/ false);
                vim.reset_pending();
                return outcome;
            }
            // Any other bare key is swallowed — a Normal-mode key must
            // never fall through to `InsertChar`.
            _ => vim.reset_pending(),
        }
    } else {
        vim.reset_pending();
    }

    VimOutcome::Consumed
}

/// Operator-pending dispatch: an operator `op` is set and we're reading
/// its target.  Handles the inter-operator count (`d2w`), the `dgg`
/// pending `g`, doubled operators (`dd`/`yy`/`cc`), vertical linewise
/// targets (`dj`/`dk`), and the charwise motion targets.  An unrecognized
/// key cancels the operator (vim's behavior).
fn feed_operator_pending(
    vim: &mut VimState,
    editor: &mut EditorState,
    op: PendingOp,
    c: char,
    vh: usize,
    vw: usize,
) -> VimOutcome {
    // Count between the operator and its motion (`d2w`).
    if is_count_digit(c, vim.motion_count) {
        vim.motion_count = Some(accumulate(vim.motion_count, c));
        return VimOutcome::Pending;
    }

    // Indent operators (`>>` / `<<`) are linewise and never touch the
    // register, so they take their own path rather than `execute_operator`.
    if matches!(op, PendingOp::IndentRight | PendingOp::IndentLeft) {
        return feed_indent_pending(vim, editor, op, c, vh, vw);
    }

    // `dgg`: first `g` is pending, resolved on the next key by
    // `feed_command_char`'s `pending_g` arm (which sees `pending_op`).
    if c == 'g' {
        vim.pending_g = true;
        return VimOutcome::Pending;
    }

    // Only `Delete`/`Change`/`Yank` reach here — the indent operators
    // returned above via `feed_indent_pending`, so `operator_kind` is `Some`.
    let operator = operator_kind(op).expect("indent operators handled before this point");

    // `[count1] op [count2] motion` multiplies the two counts.
    let count = vim
        .count
        .unwrap_or(1)
        .saturating_mul(vim.motion_count.unwrap_or(1))
        .clamp(1, COUNT_CAP);

    // Doubled operator (`dd`/`yy`/`cc`) → linewise over `count` lines.
    if operator_for(c) == Some(op) {
        // In a table the linewise unit is the row (`dd`) or the cell
        // (`cc`), not the raw source line — see `table_doubled_operator`.
        // `yy` and a counted `Ndd` keep the plain linewise behavior, which
        // is safe because `run_operator` refuses a span that would break the
        // table: the structural interpretation is a convenience, not the
        // protection.
        if count == 1 {
            if let Some(out) = table_doubled_operator(vim, editor, operator, vh, vw) {
                return out;
            }
        }
        let range = doubled_line_range(&editor.buffer, editor.cursor.offset, count);
        return run_operator(vim, editor, operator, range, vh, vw);
    }

    // Vertical linewise targets (`dj` / `dk`).
    if c == 'j' || c == 'k' {
        let range = vertical_line_range(&editor.buffer, editor.cursor.offset, count, c == 'j');
        return run_operator(vim, editor, operator, range, vh, vw);
    }

    // `df(` / `dt(` / …: arm a pending find; the next key (the target
    // char) resolves the range and runs the operator via `feed_find_char`.
    if let Some(kind) = find_kind_for(c) {
        vim.pending_find = Some(kind);
        return VimOutcome::Pending;
    }

    // Charwise / `gg`-`G` motion targets.
    if let Some(motion) = operator_motion_for(c) {
        let motion = line_jump(motion, operand_count(vim));
        let motion = change_word_to_word_end(operator, motion, editor);
        let range = resolve_scoped_op_range(editor, motion, count);
        return run_operator(vim, editor, operator, range, vh, vw);
    }

    // Text objects (`diw`, `ci(`, …): `i`/`a` arm the object and wait for the
    // object char, resolved by `feed_text_object` (checked at the top of
    // `feed_normal`, since `sub_mode` is still OperatorPending here).
    if c == 'i' || c == 'a' {
        vim.pending_text_object = Some(c == 'i');
        return VimOutcome::Pending;
    }

    // Any other key cancels the operator (vim's behavior).
    vim.sub_mode = VimSubMode::Normal;
    vim.reset_pending();
    VimOutcome::Consumed
}

/// Flashed when a line-oriented command would corrupt a table's structure.
/// `J` would merge two rows into one broken line and `>>` / `<<` would
/// indent a row out of the table; both are silent corruption today, so they
/// refuse and say why rather than doing nothing.
const TABLE_STRUCTURAL_REFUSAL: &str = "Not available in a table";

/// Flashed when a paste would land text in a table that breaks its shape —
/// a register of prose lines dropped between two rows, or a charwise
/// register carrying its own `|`.
const TABLE_PASTE_REFUSAL: &str = "Can't paste that into a table";

/// A doubled operator (`dd` / `cc` / `yy`) with the cursor inside a table.
/// `Some` when the table interpretation applies; `None` falls through to
/// the ordinary linewise path (outside a table, in Raw mode, and for `yy`).
///
/// `dd` removes the whole row structurally and `cc` clears the cell —
/// both reusing `fold_op_result`, so the register, the single-delta undo
/// grouping, and the Insert transition come from the one existing
/// implementation rather than a table-specific copy.
fn table_doubled_operator(
    vim: &mut VimState,
    editor: &mut EditorState,
    operator: Operator,
    vh: usize,
    vw: usize,
) -> Option<VimOutcome> {
    let outcome = match operator {
        Operator::Delete => delete_table_row(editor, vh, vw),
        Operator::Change => clear_table_cell(editor),
        // `yy` yanks the raw row text, unchanged — it mutates nothing, so
        // there is no structure to protect.
        Operator::Yank => return None,
    };
    match outcome {
        TableOpOutcome::Applied(res) => {
            fold_op_result(vim, editor, res, vh, vw);
            Some(VimOutcome::Consumed)
        }
        TableOpOutcome::Refused(reason) => {
            vim.sub_mode = VimSubMode::Normal;
            vim.reset_pending();
            Some(VimOutcome::Flash(reason.message().to_owned()))
        }
        TableOpOutcome::NotATable => None,
    }
}

/// Apply `op` over `range`, fold the yanked text into the register, then
/// move to Insert (for `c`) or back to Normal, and re-clamp the viewport.
///
/// Returns the outcome so the table refusal can reach the flash line: this
/// and [`run_visual_operator`] are the two funnels every vim range mutation
/// passes through, which is why the structural guard lives here rather than
/// at the dozen call sites that build a range.
fn run_operator(
    vim: &mut VimState,
    editor: &mut EditorState,
    op: Operator,
    range: OpRange,
    vh: usize,
    vw: usize,
) -> VimOutcome {
    if let Some(reason) = mutating_table_break(editor, op, &range) {
        vim.sub_mode = VimSubMode::Normal;
        vim.reset_pending();
        return VimOutcome::Flash(reason.message().to_owned());
    }
    let res = execute_operator(editor, op, range);
    fold_op_result(vim, editor, res, vh, vw);
    VimOutcome::Consumed
}

/// The structural refusal for `op` over `range`, or `None` to proceed.
/// `Yank` never mutates, so it is never refused — `yy` on a header row is
/// just a copy.
fn mutating_table_break(editor: &EditorState, op: Operator, range: &OpRange) -> Option<TableBreak> {
    if op == Operator::Yank {
        return None;
    }
    op_range_breaks_a_table(editor, range)
}

/// Fold an [`execute_operator`] result back into `VimState`: store the
/// register (unless the operator covered nothing — a no-op leaves it alone),
/// clear the in-progress parse, transition to Insert (for `c`) or Normal, and
/// refresh the editor.  Shared by the Normal-mode `run_operator` and the
/// Visual `run_visual_operator` so the two can't drift apart.  The Visual
/// caller drops the selection / anchor before calling this.
fn fold_op_result(
    vim: &mut VimState,
    editor: &mut EditorState,
    res: OpResult,
    vh: usize,
    vw: usize,
) {
    // A linewise edit (`dd`, `dj`, `Vd`, …) can leave an ordered list's
    // numbering disturbed; renumber it so the sequence stays monotonic,
    // matching the non-vim delete path.  A no-op for yanks / `cc` / non-lists.
    if res.linewise {
        renumber_list_at_cursor(editor);
    }
    if !res.register_text.is_empty() {
        vim.register = VimRegister {
            text: res.register_text,
            linewise: res.linewise,
        };
    }
    vim.reset_pending();
    if res.enter_insert {
        ensure_editing(editor);
        vim.sub_mode = VimSubMode::Insert;
    } else {
        vim.sub_mode = VimSubMode::Normal;
    }
    after_edit(editor, vh, vw);
}

/// Paste the unnamed register with the effective `count`.
fn paste_register(
    vim: &mut VimState,
    editor: &mut EditorState,
    count: u32,
    after: bool,
    vh: usize,
    vw: usize,
) -> VimOutcome {
    if vim.register.text.is_empty() {
        return VimOutcome::Consumed;
    }
    // Inside a table the ordinary linewise landing spot — "the line after
    // the cursor's" — sits above the alignment row when the cursor is on
    // the header, so `dd` on a data row then `p` up top would wedge a data
    // row into the table's declaration.  `table_paste_plan` picks a legal
    // row boundary instead, and refuses a register that isn't rows at all.
    match table_paste_plan(editor, &vim.register.text, vim.register.linewise, after) {
        TablePaste::Refused => return VimOutcome::Flash(TABLE_PASTE_REFUSAL.to_owned()),
        TablePaste::RowsAt(at) => {
            ensure_editing(editor);
            let text = vim.register.text.repeat(count.max(1) as usize);
            insert_table_rows(editor, at, &text);
            after_edit(editor, vh, vw);
            return VimOutcome::Consumed;
        }
        TablePaste::NotATable => {}
    }
    ensure_editing(editor);
    paste(
        editor,
        &vim.register.text,
        vim.register.linewise,
        count,
        after,
    );
    after_edit(editor, vh, vw);
    VimOutcome::Consumed
}

/// Operator-pending dispatch for the indent operators (`>`/`<`).  CP4 wires
/// the doubled forms `>>` / `<<` (over `count` lines); any other following
/// key cancels (operator+motion indent like `>j` is out of CP4 scope, and
/// Visual `>`/`<` arrive in CP6).
fn feed_indent_pending(
    vim: &mut VimState,
    editor: &mut EditorState,
    op: PendingOp,
    c: char,
    vh: usize,
    vw: usize,
) -> VimOutcome {
    let right = op == PendingOp::IndentRight;
    // Doubled operator (`>>` / `<<`): indent `count` lines from the cursor,
    // multiplying the leading and inter-operator counts like other operators.
    if operator_for(c) == Some(op) {
        let count = vim
            .count
            .unwrap_or(1)
            .saturating_mul(vim.motion_count.unwrap_or(1))
            .clamp(1, COUNT_CAP);
        // Indenting a table row pushes it out of the table block — asked of
        // every line the count covers, not just the cursor's.
        let line = editor.buffer.char_to_line(editor.cursor.offset);
        if lines_touch_a_table(editor, line, line + count as usize - 1) {
            vim.sub_mode = VimSubMode::Normal;
            vim.reset_pending();
            return VimOutcome::Flash(TABLE_STRUCTURAL_REFUSAL.to_owned());
        }
        ensure_editing(editor);
        // A bare `>>` / `<<` (count 1) on a list item indents it
        // structurally (nests / un-nests, renumbering ordered runs); a
        // counted `N>>`, a non-list line, or Raw mode falls back to the
        // plain space-based indent over the line span.
        if count == 1 && indent_list_item(editor, right) {
            after_edit(editor, vh, vw);
        } else if let OpRange::Lines { first, last } =
            doubled_line_range(&editor.buffer, editor.cursor.offset, count)
        {
            indent_lines(editor, first, last, right, crate::constants::INDENT_WIDTH);
            after_edit(editor, vh, vw);
        }
    }
    // Doubled or not, the sequence is finished: back to Normal, parse cleared.
    vim.sub_mode = VimSubMode::Normal;
    vim.reset_pending();
    VimOutcome::Consumed
}

/// Cancel a pending sub-state (`r{c}`, an `f`/`t` find, or an `i`/`a` text
/// object) because `key` is not the input it was awaiting.  A `Ctrl-*` chord
/// still fires its app action (`Passthrough`, mirroring the bare-operator
/// chord path in `feed_normal`); every other cancelling key (`Esc`, an arrow,
/// a stray letter) is swallowed (`Consumed`).  Either way the in-progress
/// operator / count is dropped and `OperatorPending` falls back to Normal so
/// the next key starts a clean command.  In Visual the selection is left
/// intact (`sub_mode` is `Visual`, never `OperatorPending`, so it is untouched).
fn cancel_pending(vim: &mut VimState, key: &KeyEvent) -> VimOutcome {
    if vim.sub_mode == VimSubMode::OperatorPending {
        vim.sub_mode = VimSubMode::Normal;
    }
    vim.reset_pending();
    if is_passthrough_chord(key) {
        VimOutcome::Passthrough
    } else {
        VimOutcome::Consumed
    }
}

/// Resolve a pending `r{c}`: replace `count` chars with the printable key
/// `c`.  Esc / arrows cancel with no edit; a `Ctrl-*` chord cancels and
/// passes through so its app action still fires (see [`cancel_pending`]).
fn feed_replace_char(
    vim: &mut VimState,
    editor: &mut EditorState,
    key: KeyEvent,
    vh: usize,
    vw: usize,
) -> VimOutcome {
    match key.code {
        KeyCode::Char(c) if !is_passthrough_chord(&key) => {
            let count = count_of(vim);
            // The Normal twin of `feed_visual_replace_char`'s guard: `3rx`
            // overwrites three chars in place, and a count that runs past the
            // cell's content writes over the row's `|`.  The span is asked
            // for unclamped — `replace_char` refuses to run at all when it
            // overflows the line, and outside a table an overlong span was
            // already a silent no-op, so only the in-table case changes.
            let span = editor.cursor.offset..editor.cursor.offset + count as usize;
            if let Some(reason) = op_range_breaks_a_table(editor, &OpRange::Chars(span)) {
                vim.reset_pending();
                return VimOutcome::Flash(reason.message().to_owned());
            }
            ensure_editing(editor);
            replace_char(editor, c, count);
            after_edit(editor, vh, vw);
            vim.reset_pending();
            VimOutcome::Consumed
        }
        _ => cancel_pending(vim, &key),
    }
}

/// Resolve a pending `f`/`F`/`t`/`T`: the previous key armed the find and
/// `key` carries the target char.  Records the find for `;` / `,`, then
/// either runs the pending operator over the find range (`df(`) or moves
/// the cursor / extends the Visual selection.  A non-char key cancels with no
/// edit; a `Ctrl-*` chord cancels and passes through (see [`cancel_pending`]).
fn feed_find_char(
    vim: &mut VimState,
    editor: &mut EditorState,
    kind: FindKind,
    key: KeyEvent,
    vh: usize,
    vw: usize,
    visual: bool,
) -> VimOutcome {
    let target = match key.code {
        KeyCode::Char(c) if !is_passthrough_chord(&key) => c,
        _ => return cancel_pending(vim, &key),
    };
    vim.last_find = Some((kind, target));
    let motion = Motion::FindChar(target, kind);

    // Operator target (`df(`): multiply the leading and inter-motion counts
    // exactly like the other operator motions.  A find can only be armed
    // behind a Delete/Change/Yank (indent ops route through
    // `feed_indent_pending`, which never arms a find), so `operator_kind` is
    // always `Some` when `pending_op` is set here.
    if let Some(operator) = vim.pending_op.and_then(operator_kind) {
        let count = vim
            .count
            .unwrap_or(1)
            .saturating_mul(vim.motion_count.unwrap_or(1))
            .clamp(1, COUNT_CAP);
        let range = resolve_scoped_op_range(editor, motion, count);
        return run_operator(vim, editor, operator, range, vh, vw);
    }

    // Plain motion: a Normal cursor move or a Visual selection extend.  Per
    // the invariant above the operator branch always fires when `pending_op`
    // is set, so we should never still be OperatorPending here — but fail
    // safe back to Normal rather than linger in a half-consumed operator if
    // that ever changes (e.g. a future operator without an `operator_kind`).
    if vim.sub_mode == VimSubMode::OperatorPending {
        vim.sub_mode = VimSubMode::Normal;
    }
    apply_motion(
        editor,
        motion,
        count_of(vim),
        vh,
        vw,
        visual,
        cell_limit(vim),
    );
    vim.reset_pending();
    VimOutcome::Consumed
}

/// Resolve a pending text object: the previous key was `i` / `a` and `key`
/// carries the object char (`w`, `(`, `"`, …).  In Normal it runs the
/// pending operator over the object's char range (`diw`, `ci(`); in Visual
/// it sets the selection to the object.  A non-object key cancels with no
/// edit; a `Ctrl-*` chord cancels and passes through so its app action still
/// fires (see [`cancel_pending`]).  Either cancel drops OperatorPending back
/// to Normal and leaves any Visual selection intact.
fn feed_text_object(
    vim: &mut VimState,
    editor: &mut EditorState,
    inner: bool,
    key: KeyEvent,
    vh: usize,
    vw: usize,
    visual: bool,
) -> VimOutcome {
    let obj = match key.code {
        KeyCode::Char(c) if !is_passthrough_chord(&key) => text_object_for(c, inner),
        _ => None,
    };
    let Some(obj) = obj else {
        // Not a text-object char (a chord, a non-char key, or a char that
        // names no object like `dij`): cancel, passing a chord through.
        return cancel_pending(vim, &key);
    };
    let range = resolve_text_object_range(obj, editor.cursor.offset, &editor.buffer);

    if visual {
        // Set the selection to the object's span (vim's `viw` etc.).  A
        // missing object leaves the selection as-is; an empty inner object
        // collapses the selection to a point.
        if let Some(r) = range {
            select_text_object(vim, editor, r, vh, vw);
        }
        vim.reset_pending();
        return VimOutcome::Consumed;
    }

    // Operator target (`diw`, `ci(`, `yi"`).  An empty inner range (e.g.
    // `ci(` on `()`) is handled by `execute_operator`: Delete/Yank no-op,
    // Change still enters Insert at the spot.  A missing object cancels.
    if let Some(operator) = vim.pending_op.and_then(operator_kind) {
        if let Some(r) = range {
            return run_operator(vim, editor, operator, OpRange::Chars(r), vh, vw);
        } else {
            vim.sub_mode = VimSubMode::Normal;
            vim.reset_pending();
        }
        return VimOutcome::Consumed;
    }

    // Defensive: a text object with no pending operator in Normal should be
    // unreachable (it's only armed behind an operator), but fail safe.
    if vim.sub_mode == VimSubMode::OperatorPending {
        vim.sub_mode = VimSubMode::Normal;
    }
    vim.reset_pending();
    VimOutcome::Consumed
}

/// Install a Visual selection covering the half-open `range` of a text
/// object, parking the cursor on the object's **last** character (vim's
/// landing spot for `viw`).  Charwise Visual is inclusive of the char under
/// the cursor (`visual_charwise_range`), so `active` is the exclusive `end`
/// stepped back one grapheme — the derived span then reproduces `range`
/// exactly.  An empty object leaves the cursor at `start`.
fn select_text_object(
    vim: &mut VimState,
    editor: &mut EditorState,
    range: Range<usize>,
    vh: usize,
    vw: usize,
) {
    ensure_editing(editor);
    let len = editor.buffer.len_chars();
    let start = range.start.min(len);
    let end = range.end.min(len);
    let active = if end > start {
        prev_grapheme_offset(&editor.buffer, end)
    } else {
        start
    };
    vim.visual_anchor = Some(start);
    editor.selection = Some(Selection {
        anchor: start,
        active,
    });
    editor.cursor.offset = active;
    editor.cursor.preferred_col = editor.cursor.cell_col(&editor.buffer);
    after_move(editor, vh, vw);
}

/// Map an object char (after an `i`/`a` prefix) to a [`TextObject`], or
/// `None`.  Both bracket directions resolve to the same pair, and `b`/`B`
/// are vim's aliases for the paren / brace pairs.
fn text_object_for(c: char, inner: bool) -> Option<TextObject> {
    Some(match c {
        'w' => TextObject::Word { inner, big: false },
        'W' => TextObject::Word { inner, big: true },
        '"' => TextObject::Quote { inner, quote: '"' },
        '\'' => TextObject::Quote { inner, quote: '\'' },
        '`' => TextObject::Quote { inner, quote: '`' },
        '(' | ')' | 'b' => TextObject::Pair {
            inner,
            open: '(',
            close: ')',
        },
        '[' | ']' => TextObject::Pair {
            inner,
            open: '[',
            close: ']',
        },
        '{' | '}' | 'B' => TextObject::Pair {
            inner,
            open: '{',
            close: '}',
        },
        _ => return None,
    })
}

/// Map a key to one of the offset-only Normal/Visual motions, or `None`.
fn motion_for(c: char) -> Option<Motion> {
    Some(match c {
        'w' => Motion::WordForward,
        'e' => Motion::WordEnd,
        'b' => Motion::WordBackward,
        'W' => Motion::BigWordForward,
        'E' => Motion::BigWordEnd,
        'B' => Motion::BigWordBackward,
        '0' => Motion::LineStart,
        '^' => Motion::LineFirstNonBlank,
        '$' => Motion::LineEnd,
        'G' => Motion::DocEnd,
        '{' => Motion::ParagraphBackward,
        '}' => Motion::ParagraphForward,
        '%' => Motion::MatchingPair,
        _ => return None,
    })
}

/// Map a key to a motion usable as an operator target.  Adds `h`/`l`
/// (charwise `Left`/`Right`) to the plain `motion_for` set; `j`/`k` and
/// `gg` are handled separately (they're linewise).
fn operator_motion_for(c: char) -> Option<Motion> {
    match c {
        'h' => Some(Motion::Left),
        'l' => Some(Motion::Right),
        _ => motion_for(c),
    }
}

/// Map `f`/`F`/`t`/`T` to its [`FindKind`], or `None`.
fn find_kind_for(c: char) -> Option<FindKind> {
    Some(match c {
        'f' => FindKind::Forward,
        'F' => FindKind::Backward,
        't' => FindKind::ForwardTill,
        'T' => FindKind::BackwardTill,
        _ => return None,
    })
}

/// The reversed find direction, for `,` (replay the last find the other
/// way): `f`↔`F`, `t`↔`T`.
fn reverse_find(kind: FindKind) -> FindKind {
    match kind {
        FindKind::Forward => FindKind::Backward,
        FindKind::Backward => FindKind::Forward,
        FindKind::ForwardTill => FindKind::BackwardTill,
        FindKind::BackwardTill => FindKind::ForwardTill,
    }
}

/// Map an operator key to its `PendingOp`, or `None`.
fn operator_for(c: char) -> Option<PendingOp> {
    match c {
        'd' => Some(PendingOp::Delete),
        'c' => Some(PendingOp::Change),
        'y' => Some(PendingOp::Yank),
        '>' => Some(PendingOp::IndentRight),
        '<' => Some(PendingOp::IndentLeft),
        _ => None,
    }
}

/// Translate a `PendingOp` to the editor-layer [`Operator`], or `None` for
/// the not-yet-wired indent operators (CP4).
fn operator_kind(op: PendingOp) -> Option<Operator> {
    match op {
        PendingOp::Delete => Some(Operator::Delete),
        PendingOp::Change => Some(Operator::Change),
        PendingOp::Yank => Some(Operator::Yank),
        PendingOp::IndentRight | PendingOp::IndentLeft => None,
    }
}

/// vim's `cw`/`cW` special case: when the cursor is on a non-blank, change
/// behaves like "change to the end of the current word" — it does not
/// swallow the trailing whitespace.  This is *not* the same as `ce`/`cE`:
/// `e` always advances past the cursor, so when the cursor is already on a
/// word's last char (always true for single-char words) `ce` would jump to
/// the *next* word's end and over-change.  `CurrentWordEnd` /
/// `CurrentBigWordEnd` stop at the end of the word the cursor is in.
fn change_word_to_word_end(op: Operator, motion: Motion, editor: &EditorState) -> Motion {
    if op != Operator::Change {
        return motion;
    }
    let cursor = editor.cursor.offset;
    let on_blank =
        cursor < editor.buffer.len_chars() && editor.buffer.rope().char(cursor).is_whitespace();
    if on_blank {
        return motion;
    }
    match motion {
        Motion::WordForward => Motion::CurrentWordEnd,
        Motion::BigWordForward => Motion::CurrentBigWordEnd,
        _ => motion,
    }
}

/// Whether `c` is a count digit given the current accumulator: any digit,
/// except a leading `0` (which is the line-start motion).
fn is_count_digit(c: char, acc: Option<u32>) -> bool {
    c.is_ascii_digit() && !(c == '0' && acc.is_none())
}

/// Append digit `c` to a count accumulator, saturating at `u32::MAX`.
///
/// Deliberately *not* capped at [`COUNT_CAP`]: a count is not always a
/// repetition.  `{count}G` reads it as a line number, and clamping here
/// would put line 10 000 out of reach of the keyboard in a document that
/// has one (`:10000` accepts the full `u32`, so the two forms would
/// disagree).  The cap belongs to the consumers that turn a count into
/// work — see [`COUNT_CAP`].
fn accumulate(acc: Option<u32>, c: char) -> u32 {
    let digit = c.to_digit(10).unwrap_or(0);
    acc.unwrap_or(0).saturating_mul(10).saturating_add(digit)
}

/// The effective leading count for a plain motion (defaults to 1), capped
/// at [`COUNT_CAP`].
///
/// This is the funnel every repetition consumer reads through, so the cap
/// applied here is what keeps `999999999j` from hanging the UI.  The other
/// two readers of `vim.count` are the `[count1] op [count2]` products
/// (which clamp themselves) and [`operand_count`] (which must not clamp —
/// it feeds a line number, not a repeat).
fn count_of(vim: &VimState) -> u32 {
    vim.count.unwrap_or(1).clamp(1, COUNT_CAP)
}

/// Fold a typed count into `gg` / `G`, which read it as a *line number*
/// rather than a repeat count (`5G` → line 5).
///
/// This has to happen here, at the key layer, rather than inside
/// `resolve_motion`: a bare `G` means the *last* line while `1G` means the
/// first, and by the time the resolver sees a `count: u32` the two are
/// indistinguishable — `count_of` has already defaulted the absent count
/// to 1.  `Option<u32>` is the distinction, so the motion carries the
/// answer.  Every other motion passes through untouched.
fn line_jump(motion: Motion, count: Option<u32>) -> Motion {
    match (motion, count) {
        (Motion::DocStart | Motion::DocEnd, Some(n)) => Motion::GoToLine(n),
        _ => motion,
    }
}

/// The count a line jump should read as its line number, or `None` when the
/// user typed no count at all.  Both accumulators count, and they multiply
/// exactly as they do for every other counted operator target (`d3G` and
/// `2d3G` alike name a line), so this mirrors `feed_operator_pending`'s
/// product rather than inventing a second rule.
///
/// Uncapped, unlike every other count reader: the product is a *line
/// number*, and `goto_line_index` already clamps it to the last content
/// line, so a saturating `u32::MAX` lands exactly where `:$` does.  No
/// iteration is driven by this value — see [`COUNT_CAP`].
fn operand_count(vim: &VimState) -> Option<u32> {
    if vim.count.is_none() && vim.motion_count.is_none() {
        return None;
    }
    Some(
        vim.count
            .unwrap_or(1)
            .saturating_mul(vim.motion_count.unwrap_or(1))
            .max(1),
    )
}

/// Is the charwise Visual span — the one that covers the character under
/// the cursor — currently live?  The single predicate behind both halves of
/// the table-cell tightening ([`cell_limit`] and `feed_hjkl`'s in-cell
/// step), so the two can't drift apart.
fn is_charwise_visual(vim: &VimState) -> bool {
    vim.sub_mode == VimSubMode::Visual
}

/// How far into a table cell's trailing edge a cursor move may go: one
/// grapheme short of the append slot in charwise Visual, whose span would
/// otherwise highlight the padding space before the `|` and then eat it on
/// the edit (see `CellLimit::LastChar` — the guard permits that one, which
/// is exactly why the clamp has to prevent it).  VisualLine needs no
/// tightening — its span is whole lines however the cursor sits.
fn cell_limit(vim: &VimState) -> CellLimit {
    if is_charwise_visual(vim) {
        CellLimit::LastChar
    } else {
        CellLimit::Append
    }
}

/// Resolve `motion` to a target offset, move the cursor there with the
/// given `count`, and — in Visual — extend the selection.
fn apply_motion(
    editor: &mut EditorState,
    motion: Motion,
    count: u32,
    vh: usize,
    vw: usize,
    visual: bool,
    limit: CellLimit,
) {
    let target = resolve_scoped_motion(editor, motion, count, limit);
    move_to_offset(editor, target, vh, vw, visual);
}

/// Move the cursor to an already-resolved `target` offset and run the
/// shared post-move bookkeeping; in Visual, extend the selection to the new
/// position instead of clearing it.  Shared by `apply_motion` and the
/// `;`/`,` find-repeat path (which resolves its own target).
fn move_to_offset(editor: &mut EditorState, target: usize, vh: usize, vw: usize, visual: bool) {
    ensure_editing(editor);
    if !visual {
        clear_selection(editor);
    }
    editor.cursor.offset = target.min(editor.buffer.len_chars());
    editor.cursor.preferred_col = editor.cursor.cell_col(&editor.buffer);
    after_move(editor, vh, vw);
    if visual {
        extend_selection(editor);
    }
}

/// The `h j k l` cursor moves, including the rendered-table chrome skip.
///
/// `charwise_visual` tightens the horizontal pair: a charwise Visual span
/// covers the char under the cursor, so hopping to the next cell would
/// highlight the `|` between them and promise an edit the structural guard
/// refuses.  There the step stays inside the cell (`visual_cell_step`).
fn feed_hjkl(editor: &mut EditorState, c: char, vh: usize, vw: usize, charwise_visual: bool) {
    ensure_editing(editor);
    let mut moved = true;
    match c {
        'h' => {
            // In a rendered table, step cell-to-cell over the auto-managed
            // border chrome — unless the charwise Visual span is live, which
            // holds the step inside the cell; elsewhere — and always in Raw
            // — a plain grapheme step.
            let held = charwise_visual && visual_cell_step(editor, /*forward=*/ false);
            if !held && !editor.try_table_move_horizontal(/*forward=*/ false) {
                editor.cursor.move_left(&editor.buffer);
            }
        }
        'l' => {
            let held = charwise_visual && visual_cell_step(editor, /*forward=*/ true);
            if !held && !editor.try_table_move_horizontal(/*forward=*/ true) {
                editor.cursor.move_right(&editor.buffer);
            }
        }
        'j' => {
            // `try_table_move_vertical` refreshes the cursor block and
            // viewport on success, so only the plain-line path needs the
            // trailing `after_move`.
            if editor.try_table_move_vertical(/*down=*/ true, vh, vw) {
                moved = false;
            } else {
                editor.move_cursor_line(/*down=*/ true, /*visual=*/ false, vw);
            }
        }
        'k' => {
            if editor.try_table_move_vertical(/*down=*/ false, vh, vw) {
                moved = false;
            } else {
                editor.move_cursor_line(/*down=*/ false, /*visual=*/ false, vw);
            }
        }
        _ => unreachable!("feed_hjkl only handles h/j/k/l"),
    }
    if moved {
        after_move(editor, vh, vw);
    }
}

// ── Helpers ───────────────────────────────────────────────────────────────────

/// `Ctrl-*` / `Alt-*` / `Super-*` chords keep their edamame meaning —
/// they fall through to the default keymap (Save, palette, undo, …).
/// `Shift` is *not* a passthrough modifier: a shifted letter like `I`
/// arrives as `Char('I')` with `SHIFT` and must still reach the reducer.
fn is_passthrough_chord(key: &KeyEvent) -> bool {
    key.modifiers
        .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER)
}

/// Vim never rests in Preview; coming from it (or any non-edit mode)
/// switches to Rendered so the cursor is visible and edits apply.  Raw
/// is left untouched — it's a fully supported vim surface.
fn ensure_editing(editor: &mut EditorState) {
    if editor.mode == Mode::Preview {
        editor.mode = Mode::Rendered;
    }
}

/// Enter Insert sub-mode, switching out of Preview first.
fn enter_insert(vim: &mut VimState, editor: &mut EditorState) {
    ensure_editing(editor);
    vim.sub_mode = VimSubMode::Insert;
}

/// Enter Visual / Visual-Line, anchoring the selection at the cursor.
/// The anchor is recorded both on the vim state (so CP6's `o`-swap and
/// line-expansion can find it) and on the shared `EditorState::selection`
/// (so the existing overlay painter highlights it for free).
fn enter_visual(vim: &mut VimState, editor: &mut EditorState, line: bool) {
    ensure_editing(editor);
    vim.sub_mode = if line {
        VimSubMode::VisualLine
    } else {
        VimSubMode::Visual
    };
    // `$` parks the cursor on a cell's append slot; a charwise span opened
    // there would highlight the padding space before the `|` and the edit
    // would eat it, so `v` anchors on the last character instead.  The same
    // one-grapheme tightening the motions get from `CellLimit::LastChar`,
    // applied at the entry point they bypass.  Both ends come from the
    // cursor here, so pulling it back covers the anchor too.
    if !line {
        pull_cursor_into_cell(editor);
    }
    let offset = editor.cursor.offset;
    vim.visual_anchor = Some(offset);
    editor.selection = Some(Selection {
        anchor: offset,
        active: offset,
    });
}

/// Pull the cursor off its table cell's append slot onto the cell's last
/// character, for a charwise Visual span about to cover it.  A no-op
/// wherever `visual_endpoint_in_cell` declines — outside a table, in Raw,
/// on the alignment row, or already on content.
fn pull_cursor_into_cell(editor: &mut EditorState) {
    if let Some(offset) = visual_endpoint_in_cell(editor, editor.cursor.offset) {
        editor.cursor.offset = offset;
        editor.cursor.preferred_col = editor.cursor.cell_col(&editor.buffer);
    }
}

/// The anchor half of [`pull_cursor_into_cell`], against the anchor's *own*
/// cell.  Both stores of the anchor move together — `VimState` (which the
/// `o`-swap and the operator range read) and `EditorState::selection`
/// (which the overlay painter reads) — so the highlight and the edit stay
/// the same span.
fn pull_anchor_into_cell(vim: &mut VimState, editor: &mut EditorState) {
    let Some(anchor) = vim.visual_anchor else {
        return;
    };
    let Some(pulled) = visual_endpoint_in_cell(editor, anchor) else {
        return;
    };
    vim.visual_anchor = Some(pulled);
    if let Some(sel) = editor.selection.as_mut() {
        sel.anchor = pulled;
    }
}

/// Update the active end of the Visual selection to the cursor.  Falls
/// back to anchoring at the cursor if no selection exists (defensive —
/// `enter_visual` always installs one).
fn extend_selection(editor: &mut EditorState) {
    let active = editor.cursor.offset;
    match editor.selection.as_mut() {
        Some(sel) => sel.active = active,
        None => {
            editor.selection = Some(Selection {
                anchor: active,
                active,
            })
        }
    }
}

/// Open a new line below (`o`) or above (`O`) the cursor's line, place
/// the cursor on it, and enter Insert.  Inside a Markdown list the line is
/// opened as a fresh list item (marker copied, ordered list renumbered) via
/// `open_list_continue`; otherwise a plain newline is inserted.
fn open_line(vim: &mut VimState, editor: &mut EditorState, below: bool, vh: usize, vw: usize) {
    ensure_editing(editor);
    // Inside a table the "line" to open is a structural row — a bare
    // newline would split the current row in half and break the table.
    // The cursor lands on the new row's first cell.
    if open_table_row(editor, below, vh, vw) {
        after_edit(editor, vh, vw);
        vim.sub_mode = VimSubMode::Insert;
        return;
    }
    if open_list_continue(editor, below) {
        after_edit(editor, vh, vw);
        vim.sub_mode = VimSubMode::Insert;
        return;
    }
    let (line, _) = editor.cursor.line_col(&editor.buffer);
    let line_start = editor.buffer.line_to_char(line);
    if below {
        // Insert a newline at the line end; `apply_delta`'s redo-cursor
        // lands on the start of the freshly-opened line below.
        let mut probe = editor.cursor;
        probe.move_line_end(&editor.buffer);
        editor.apply_delta(EditDelta {
            offset: probe.offset,
            removed: String::new(),
            inserted: "\n".to_string(),
        });
    } else {
        // Insert a newline at the line start; the new empty line sits
        // above, so park the cursor back on it.
        editor.apply_delta(EditDelta {
            offset: line_start,
            removed: String::new(),
            inserted: "\n".to_string(),
        });
        editor.cursor.offset = line_start;
        editor.update_cursor_block();
    }
    editor.cursor.preferred_col = editor.cursor.cell_col(&editor.buffer);
    after_move(editor, vh, vw);
    vim.sub_mode = VimSubMode::Insert;
}

/// Drop any active selection before a Normal-mode motion.  A lingering
/// mouse-drag selection would otherwise keep painting under the moving
/// cursor.  Visual sub-modes instead *extend* the selection, so this is
/// only called from the Normal motion path.
fn clear_selection(editor: &mut EditorState) {
    editor.selection = None;
}

/// Re-derive the cursor block and re-clamp the viewport after a motion.
fn after_move(editor: &mut EditorState, vh: usize, vw: usize) {
    editor.update_cursor_block();
    editor.ensure_cursor_visible(vh, vw);
}

/// Re-derive the cursor block and re-clamp the viewport after an edit.
/// An in-line operator delete leaves `parsed` stale (the deferred-reparse
/// optimization); flush it first so the rendered view and the
/// visibility check see fresh geometry.  Raw mode reads the buffer
/// directly, so no flush is needed there.
fn after_edit(editor: &mut EditorState, vh: usize, vw: usize) {
    if editor.mode != Mode::Raw {
        editor.flush_parsed_if_dirty();
    }
    editor.update_cursor_block();
    editor.ensure_cursor_visible(vh, vw);
}

/// Open a command line (`/` `?` search, or `:` ex), clearing any
/// in-progress count / operator parse first.  The prompt then captures keys
/// via `feed_cmdline` until the user submits or cancels.
fn start_cmdline(vim: &mut VimState, kind: CmdLineKind) {
    vim.reset_pending();
    vim.cmdline = Some(CmdLineState::new(kind));
}

/// `n` / `N`: advance (or retreat) the focused match `count` times over the
/// active search, then sync the cursor and scroll it into view.  A no-op
/// when no search is active.  Mirrors `App::search_move_focus` but acts
/// directly on `EditorState` (vim owns the keys, so no App round-trip is
/// needed — see §2.3).
fn search_repeat(editor: &mut EditorState, forward: bool, count: u32, vh: usize, vw: usize) {
    if editor.search.is_none() {
        return;
    }
    // Vim edits can have mutated the buffer since the last search, leaving
    // the match list stale — refresh before navigating.
    editor.ensure_search_fresh();
    for _ in 0..count.max(1) {
        if let Some(s) = editor.search.as_mut() {
            if forward {
                s.advance_focus();
            } else {
                s.retreat_focus();
            }
        }
    }
    editor.sync_cursor_to_search_focus();
    editor.scroll_focused_match_into_view(vh, vw);
}

/// `*` / `#`: build a search for the word under the cursor.  Repositions
/// the cursor to the word's start first (vim's behavior) so the App's
/// cursor-relative focus is correct — without it a backward `#` from the
/// middle of an occurrence would snap to the current word's start instead
/// of jumping to the previous occurrence.  Returns `EnterSearch` so the
/// App runs the flow; a `Consumed` no-op when the line has no keyword
/// at/after the cursor.
///
/// The keyword comes from the buffer, not the keyboard, so it is
/// `escape`d before it becomes a query — `EnterSearch` carries the
/// *typed* form and the App decodes it.  A keyword run is word-class
/// only, so this is a no-op today; it is here so the contract holds by
/// construction rather than by coincidence of what `iskeyword` allows.
fn search_word_outcome(editor: &mut EditorState, forward: bool) -> VimOutcome {
    match word_under_cursor_at(&editor.buffer, editor.cursor.offset) {
        Some((start, keyword)) => {
            editor.cursor.offset = start;
            editor.cursor.preferred_col = editor.cursor.cell_col(&editor.buffer);
            editor.update_cursor_block();
            VimOutcome::EnterSearch {
                forward,
                query: crate::search::escape::escape(&keyword),
            }
        }
        None => VimOutcome::Consumed,
    }
}

/// Move the cursor to the first non-blank character of its line (the
/// `I` insert point).  Falls back to the line start on a blank line.
/// Shares the pure `vim_ops::motion::first_non_blank` resolver with the
/// `^` / `gg` / `G` motions so the two can't diverge.
fn move_first_non_blank(editor: &mut EditorState) {
    let line = editor.buffer.char_to_line(editor.cursor.offset);
    editor.cursor.offset = first_non_blank(&editor.buffer, line);
    editor.cursor.preferred_col = editor.cursor.cell_col(&editor.buffer);
    editor.update_cursor_block();
}