hjkl-vim 0.44.0

Vim modal state types and grammar primitives for the hjkl editor stack. Pre-1.0 churn.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
//! Vim FSM: motion.
//!
//! Split out of the monolithic `vim.rs` (#267 follow-up).

use hjkl_vim_types::{LastHorizontalMotion, Mode, Motion};

use hjkl_engine::input::{Input, Key};

use super::*;
use crate::vim_state::{vim, vim_mut};
use hjkl_engine::buf_helpers::{
    buf_cursor_pos, buf_line, buf_line_chars, buf_row_count, buf_set_cursor_rc,
};
use hjkl_engine::{Editor, Move};

/// Parse the first key of a normal/visual-mode motion. Returns `None` for
/// keys that don't start a motion (operator keys, command keys, etc.).
/// Promoted to `pub` in Phase 6.6e so `hjkl-vim::normal` can call it.
pub fn parse_motion(input: &Input) -> Option<Motion> {
    if input.ctrl {
        // `<C-h>` is vim's `<BS>` — a wrapping left motion. (The hjkl app
        // rebinds `<C-h>` to window-focus-left before it reaches the engine;
        // this keeps it correct for engine consumers that don't override it.)
        if input.key == Key::Char('h') {
            return Some(Motion::BackspaceBack);
        }
        return None;
    }
    match input.key {
        Key::Char('h') | Key::Left => Some(Motion::Left),
        Key::Char('l') | Key::Right => Some(Motion::Right),
        // `<Space>`/`<BS>` are vim's right/left motions that WRAP at line ends
        // (default `whichwrap=b,s`), unlike `l`/`h`/arrows which never wrap.
        // Operators (`d<Space>`/`d<BS>`) act on one char mid-line like `dl`/`dh`.
        Key::Char(' ') => Some(Motion::SpaceFwd),
        Key::Backspace => Some(Motion::BackspaceBack),
        Key::Char('j') | Key::Down => Some(Motion::Down),
        // `+` / `<CR>` — first non-blank of next line (linewise, count-aware).
        Key::Char('+') | Key::Enter => Some(Motion::FirstNonBlankNextLine),
        // `-` — first non-blank of previous line (linewise, count-aware).
        Key::Char('-') => Some(Motion::FirstNonBlankPrevLine),
        // `_` — first non-blank of current line, or count-1 lines down (linewise).
        Key::Char('_') => Some(Motion::FirstNonBlankLine),
        Key::Char('k') | Key::Up => Some(Motion::Up),
        Key::Char('w') => Some(Motion::WordFwd),
        Key::Char('W') => Some(Motion::BigWordFwd),
        Key::Char('b') => Some(Motion::WordBack),
        Key::Char('B') => Some(Motion::BigWordBack),
        Key::Char('e') => Some(Motion::WordEnd),
        Key::Char('E') => Some(Motion::BigWordEnd),
        Key::Char('0') => Some(Motion::LineStart),
        Key::Home => Some(Motion::Home),
        Key::Char('^') => Some(Motion::FirstNonBlank),
        Key::Char('$') | Key::End => Some(Motion::LineEnd),
        Key::Char('G') => Some(Motion::FileBottom),
        Key::Char('%') => Some(Motion::MatchBracket),
        Key::Char(';') => Some(Motion::FindRepeat { reverse: false }),
        Key::Char(',') => Some(Motion::FindRepeat { reverse: true }),
        Key::Char('*') => Some(Motion::WordAtCursor {
            forward: true,
            whole_word: true,
        }),
        Key::Char('#') => Some(Motion::WordAtCursor {
            forward: false,
            whole_word: true,
        }),
        Key::Char('n') => Some(Motion::SearchNext { reverse: false }),
        Key::Char('N') => Some(Motion::SearchNext { reverse: true }),
        Key::Char('H') => Some(Motion::ViewportTop),
        Key::Char('M') => Some(Motion::ViewportMiddle),
        Key::Char('L') => Some(Motion::ViewportBottom),
        Key::Char('{') => Some(Motion::ParagraphPrev),
        Key::Char('}') => Some(Motion::ParagraphNext),
        Key::Char('(') => Some(Motion::SentencePrev),
        Key::Char(')') => Some(Motion::SentenceNext),
        Key::Char('|') => Some(Motion::GotoColumn),
        _ => None,
    }
}
pub fn execute_motion<H: hjkl_engine::types::Host>(
    ed: &mut Editor<hjkl_buffer::View, H>,
    motion: Motion,
    count: usize,
) {
    let count = count.clamp(1, MAX_COUNT);
    // `;`/`,` smart fallback: if the last horizontal motion was a sneak
    // digraph, repeat via apply_sneak instead of find-char.
    if let Motion::FindRepeat { reverse } = motion
        && vim(ed).last_horizontal_motion == LastHorizontalMotion::Sneak
    {
        if let Some(((c1, c2), fwd)) = vim(ed).last_sneak {
            let effective_fwd = if reverse { !fwd } else { fwd };
            apply_sneak(ed, c1, c2, effective_fwd, count);
        }
        return;
    }
    // FindRepeat needs the stored direction. A `;`/`,` repeat of a `t`/`T`
    // find must skip an immediately-adjacent match (vim's repeat quirk); flag
    // it so the `Motion::Find` dispatch below passes `skip_adjacent`.
    let motion = match motion {
        Motion::FindRepeat { reverse } => match vim(ed).last_find {
            Some((ch, forward, till)) => {
                vim_mut(ed).find_repeat_skip = true;
                Motion::Find {
                    ch,
                    forward: if reverse { !forward } else { forward },
                    till,
                }
            }
            None => return,
        },
        other => other,
    };
    let pre_pos = ed.cursor();
    // Read before the motion, which consumes it.
    let find_repeat = vim(ed).find_repeat_skip;
    apply_motion_cursor(ed, &motion, count);
    let post_pos = ed.cursor();
    if is_big_jump(&motion) && pre_pos != post_pos {
        ed.push_jump(pre_pos);
    }
    // Phase 1 (backlog §1.6): the motion names its own curswant semantics.
    // The landed cursor is re-moved through the matching `Move` variant —
    // for the cursor itself this is a no-op (the motion already landed and
    // clamped), and it rewrites `sticky_col` to the class's rule, replacing
    // the old post-hoc `apply_sticky_col` catch-all.
    match motion_class(&motion) {
        // A `gj` / `gk` between screen lines of one wrapped row is not
        // re-moved: back on the same row that would undo the step. The sticky
        // column stays the whole-line column, where vim's curswant follows the
        // screen line (see `docs/backlog.md`).
        MotionClass::Vertical
            if matches!(motion, Motion::ScreenUp | Motion::ScreenDown)
                && pre_pos.0 == post_pos.0
                && screen_wraps(ed) => {}
        // A `j` / `k` that cannot move fails in vim and leaves the cursor where
        // it was, even when the curswant names another column (after `zfj`,
        // say), so the clamp onto the want is skipped.
        MotionClass::Vertical
            if matches!(motion, Motion::Up | Motion::Down) && pre_pos == post_pos => {}
        MotionClass::Vertical => {
            // Re-run the sticky clamp on the landed row. The vertical motion
            // fns already clamped there, so this only confirms the
            // un-clamped want stays stored for the next vertical motion.
            ed.move_cursor(Move::Vertical { row: ed.cursor().0 });
        }
        MotionClass::Jump => {
            // Re-jump to the landed spot; `jump_cursor` sets sticky to the
            // landed column (vim resets curswant on every explicit jump).
            let pos = ed.cursor();
            ed.move_cursor(Move::Jump {
                row: pos.0,
                col: pos.1,
            });
        }
        // An `h` / `l` that cannot move fails in vim (`nv_left` / `nv_right`
        // beep), and a failed command leaves curswant alone: `$lj` still
        // aims for the end of the line.
        MotionClass::Horizontal
            if pre_pos == post_pos
                && matches!(
                    motion,
                    Motion::Left | Motion::Right | Motion::SpaceFwd | Motion::BackspaceBack
                ) => {}
        MotionClass::Horizontal => {
            // Sticky tracks the landed column.
            ed.move_cursor(Move::Horizontal { col: ed.cursor().1 });
            // vim's `nv_dollar` sets curswant to MAXCOL instead, so `j` / `k`
            // after `$` keep to the end of every line they reach. Every
            // reader clamps the want to the row it lands on.
            if matches!(motion, Motion::LineEnd) {
                ed.set_sticky_col(Some(usize::MAX));
            }
        }
    }
    // vim's `bck_word` starts each repetition by moving onto a closed
    // fold's first line, column 0; when that fold starts the buffer there is
    // nothing left to step back over and `b` fails, though the cursor moved.
    let back_word_failed = matches!(motion, Motion::WordBack | Motion::BigWordBack)
        && (1..=pre_pos.0.max(1)).all(|row| ed.buffer().is_row_hidden(row));
    // Some motions succeed without moving: a `t` / `T` onto an adjacent
    // target, and a search whose only match is under the cursor.
    let succeeded_in_place = pre_pos == post_pos
        && match motion {
            Motion::Find {
                ch,
                forward,
                till: true,
            } => till_succeeds_in_place(ed, ch, forward, count, find_repeat),
            Motion::WordAtCursor { .. } | Motion::SearchNext { .. } => {
                ed.settings().wrapscan && search_matches_at_cursor(ed)
            }
            _ => false,
        };
    let succeeded = (pre_pos != post_pos && !back_word_failed) || succeeded_in_place;
    if motion_opens_fold(&motion, count, succeeded) {
        foldopen_cursor(ed);
    }
    // Phase 7b: keep the migration buffer's cursor + viewport in
    // lockstep with the textarea after every motion. Once 7c lands
    // (motions ported onto the buffer's API), this flips: the
    // buffer becomes authoritative and the textarea mirrors it.
    ed.sync_buffer_from_textarea();
}
/// Wrapper around `execute_motion` that also syncs `block_vcol` when in
/// VisualBlock mode. The engine FSM's `step()` already does this (line ~2001);
/// the keymap path (`apply_motion_kind`) must do the same so VisualBlock h/l
/// extend the highlighted region correctly.
///
/// `update_block_vcol` is only a no-op for vertical / non-horizontal motions
/// (Up, Down, FileTop, FileBottom, Search), so passing every motion through is
/// safe — the function's own match arm handles the no-op case.
pub fn execute_motion_with_block_vcol<H: hjkl_engine::types::Host>(
    ed: &mut Editor<hjkl_buffer::View, H>,
    motion: Motion,
    count: usize,
) {
    let motion_copy = motion.clone();
    execute_motion(ed, motion, count);
    if vim(ed).mode == Mode::VisualBlock {
        update_block_vcol(ed, &motion_copy);
    }
}
/// Execute a `hjkl_engine::MotionKind` cursor motion. Called by the host's
/// `Editor::apply_motion` controller method — the keymap dispatch path for
/// Phase 3a of kryptic-sh/hjkl#69.
///
/// Maps each variant to the same internal primitives used by the engine FSM
/// so cursor, sticky column, scroll, and sync semantics are identical.
///
/// # Visual-mode post-motion sync audit (2026-05-13)
///
/// After `execute_motion`, two things are conditional on visual mode:
///
/// 1. **VisualBlock `block_vcol` sync** — `update_block_vcol(ed, &motion)` is
///    called when `mode == Mode::VisualBlock`.  This is replicated here via
///    `execute_motion_with_block_vcol` for every motion variant below.
///
/// 2. **`last_find` update** — `Motion::Find` is dispatched through
///    `Pending::Find → apply_find_char` (in hjkl-vim), which writes `last_find`
///    itself.  A post-motion `last_find` write here would be dead code.  The keymap
///    path writes `last_find` in `apply_find_char` (called from
///    `Editor::find_char`), so no gap exists here.
///
/// No VisualLine-specific or Visual-specific post-motion work exists in the
/// FSM: anchors (`visual_anchor`, `visual_line_anchor`, `block_anchor`) are
/// only written on mode-entry or `o`-swap, never on motion.  The `<`/`>`
/// mark update in `step()` fires only on visual→normal transition, not after
/// each motion.  There are **no further sync gaps** beyond the `block_vcol`
/// fix already applied above.
pub fn apply_motion_kind<H: hjkl_engine::types::Host>(
    ed: &mut Editor<hjkl_buffer::View, H>,
    kind: hjkl_engine::MotionKind,
    count: usize,
) {
    let count = count.max(1);
    match kind {
        hjkl_engine::MotionKind::CharLeft => {
            execute_motion_with_block_vcol(ed, Motion::Left, count);
        }
        hjkl_engine::MotionKind::CharRight => {
            execute_motion_with_block_vcol(ed, Motion::Right, count);
        }
        hjkl_engine::MotionKind::LineDown => {
            execute_motion_with_block_vcol(ed, Motion::Down, count);
        }
        hjkl_engine::MotionKind::LineUp => {
            execute_motion_with_block_vcol(ed, Motion::Up, count);
        }
        hjkl_engine::MotionKind::FirstNonBlankDown => {
            // `+`: move down `count` lines then land on first non-blank.
            // Not a big-jump (no jump-list entry). The landed first
            // non-blank column becomes the sticky target — vim's `+` sets
            // curswant to where it lands (jump class). Mirrors
            // scroll_cursor_rows semantics but goes through the fold-aware
            // buffer motion path.
            let folds = hjkl_engine::SnapshotFoldProvider::from_buffer(ed.buffer());
            let mut sticky = ed.sticky_col();
            let tabstop = ed.settings().tabstop;
            hjkl_engine::motions::move_down(ed.buffer_mut(), &folds, count, &mut sticky, tabstop);
            ed.set_sticky_col(sticky);
            hjkl_engine::motions::move_first_non_blank(ed.buffer_mut());
            let pos = ed.cursor();
            ed.move_cursor(Move::Jump {
                row: pos.0,
                col: pos.1,
            });
            ed.sync_buffer_from_textarea();
        }
        hjkl_engine::MotionKind::FirstNonBlankUp => {
            // `-`: move up `count` lines then land on first non-blank.
            // Same pattern as FirstNonBlankDown, direction reversed.
            let folds = hjkl_engine::SnapshotFoldProvider::from_buffer(ed.buffer());
            let mut sticky = ed.sticky_col();
            let tabstop = ed.settings().tabstop;
            hjkl_engine::motions::move_up(ed.buffer_mut(), &folds, count, &mut sticky, tabstop);
            ed.set_sticky_col(sticky);
            hjkl_engine::motions::move_first_non_blank(ed.buffer_mut());
            let pos = ed.cursor();
            ed.move_cursor(Move::Jump {
                row: pos.0,
                col: pos.1,
            });
            ed.sync_buffer_from_textarea();
        }
        hjkl_engine::MotionKind::WordForward => {
            execute_motion_with_block_vcol(ed, Motion::WordFwd, count);
        }
        hjkl_engine::MotionKind::BigWordForward => {
            execute_motion_with_block_vcol(ed, Motion::BigWordFwd, count);
        }
        hjkl_engine::MotionKind::WordBackward => {
            execute_motion_with_block_vcol(ed, Motion::WordBack, count);
        }
        hjkl_engine::MotionKind::BigWordBackward => {
            execute_motion_with_block_vcol(ed, Motion::BigWordBack, count);
        }
        hjkl_engine::MotionKind::WordEnd => {
            execute_motion_with_block_vcol(ed, Motion::WordEnd, count);
        }
        hjkl_engine::MotionKind::BigWordEnd => {
            execute_motion_with_block_vcol(ed, Motion::BigWordEnd, count);
        }
        hjkl_engine::MotionKind::LineStart => {
            // `0`: first column of the current line.
            // count is ignored — matches vim `0` semantics.
            execute_motion_with_block_vcol(ed, Motion::LineStart, 1);
        }
        hjkl_engine::MotionKind::Home => {
            // `<Home>`: as `0`, but leaves a closed fold closed.
            execute_motion_with_block_vcol(ed, Motion::Home, 1);
        }
        hjkl_engine::MotionKind::FirstNonBlank => {
            // `^`: first non-blank column on the current line.
            // count is ignored — matches vim `^` semantics.
            execute_motion_with_block_vcol(ed, Motion::FirstNonBlank, 1);
        }
        hjkl_engine::MotionKind::GotoLine => {
            // `G`: bare `G` → last line; `count G` → jump to line `count`.
            // apply_motion_kind normalises the raw count to count.max(1)
            // above, so count == 1 means "bare G" (last line) and count > 1
            // means "go to line N". execute_motion's FileBottom arm applies
            // the same `count > 1` check before calling move_bottom, so the
            // convention aligns: pass count straight through.
            // FileBottom is vertical — update_block_vcol is a no-op here
            // (preserves vcol), so the helper is safe to use.
            execute_motion_with_block_vcol(ed, Motion::FileBottom, count);
        }
        hjkl_engine::MotionKind::LineEnd => {
            // `[count]$` / `<End>`: move count-1 lines down then land
            // at the last character of the destination line.
            execute_motion_with_block_vcol(ed, Motion::LineEnd, count);
        }
        hjkl_engine::MotionKind::FindRepeat => {
            // `;` — repeat last f/F/t/T in the same direction.
            // execute_motion resolves FindRepeat via vim(ed).last_find;
            // no-op if no prior find exists (None arm returns early).
            execute_motion_with_block_vcol(ed, Motion::FindRepeat { reverse: false }, count);
        }
        hjkl_engine::MotionKind::FindRepeatReverse => {
            // `,` — repeat last f/F/t/T in the reverse direction.
            // execute_motion resolves FindRepeat via vim(ed).last_find;
            // no-op if no prior find exists (None arm returns early).
            execute_motion_with_block_vcol(ed, Motion::FindRepeat { reverse: true }, count);
        }
        hjkl_engine::MotionKind::BracketMatch => {
            // `%` — jump to the matching bracket.
            // count is passed through; engine-side matching_bracket handles
            // the no-match case as a no-op (cursor stays). Engine FSM arm
            // for `%` in parse_motion is kept intact for macro-replay.
            execute_motion_with_block_vcol(ed, Motion::MatchBracket, count);
        }
        hjkl_engine::MotionKind::ViewportTop => {
            // `H` — cursor to top of visible viewport, then count-1 rows down.
            // Engine FSM arm for `H` in parse_motion is kept intact for macro-replay.
            execute_motion_with_block_vcol(ed, Motion::ViewportTop, count);
        }
        hjkl_engine::MotionKind::ViewportMiddle => {
            // `M` — cursor to middle of visible viewport; count ignored.
            // Engine FSM arm for `M` in parse_motion is kept intact for macro-replay.
            execute_motion_with_block_vcol(ed, Motion::ViewportMiddle, count);
        }
        hjkl_engine::MotionKind::ViewportBottom => {
            // `L` — cursor to bottom of visible viewport, then count-1 rows up.
            // Engine FSM arm for `L` in parse_motion is kept intact for macro-replay.
            execute_motion_with_block_vcol(ed, Motion::ViewportBottom, count);
        }
        hjkl_engine::MotionKind::HalfPageDown => {
            // `<C-d>` — half page down, count multiplies the distance.
            // Calls scroll_cursor_rows directly rather than adding a Motion enum
            // variant, keeping engine Motion churn minimal.
            {
                let d = ed.viewport_half_rows(count) as isize;
                ed.scroll_cursor_rows(d);
            }
        }
        hjkl_engine::MotionKind::HalfPageUp => {
            // `<C-u>` — half page up, count multiplies the distance.
            // Direct call mirrors the FSM Ctrl-u arm. No new Motion variant.
            {
                let d = -(ed.viewport_half_rows(count) as isize);
                ed.scroll_cursor_rows(d);
            }
        }
        hjkl_engine::MotionKind::FullPageDown => {
            // `<C-f>` — full page down (2-line overlap), count multiplies.
            // Direct call mirrors the FSM Ctrl-f arm. No new Motion variant.
            {
                let d = ed.viewport_full_rows(count) as isize;
                ed.scroll_cursor_rows(d);
            }
        }
        hjkl_engine::MotionKind::FullPageUp => {
            // `<C-b>` — full page up (2-line overlap), count multiplies.
            // Direct call mirrors the FSM Ctrl-b arm. No new Motion variant.
            {
                let d = -(ed.viewport_full_rows(count) as isize);
                ed.scroll_cursor_rows(d);
            }
        }
        hjkl_engine::MotionKind::FirstNonBlankLine => {
            execute_motion_with_block_vcol(ed, Motion::FirstNonBlankLine, count);
        }
        hjkl_engine::MotionKind::SectionBackward => {
            execute_motion_with_block_vcol(ed, Motion::SectionBackward, count);
        }
        hjkl_engine::MotionKind::SectionForward => {
            execute_motion_with_block_vcol(ed, Motion::SectionForward, count);
        }
        hjkl_engine::MotionKind::SectionEndBackward => {
            execute_motion_with_block_vcol(ed, Motion::SectionEndBackward, count);
        }
        hjkl_engine::MotionKind::SectionEndForward => {
            execute_motion_with_block_vcol(ed, Motion::SectionEndForward, count);
        }
        // `MotionKind` is `#[non_exhaustive]` and now lives in another crate, so
        // the engine can add a motion this FSM has never heard of. Ignoring it
        // is the honest response: a discipline cannot execute a motion it has
        // no binding for. Every variant that exists today is handled above.
        _ => {}
    }
}
/// Which of the three `Move` curswant classes a plain motion belongs to
/// (backlog §1.6 phase 1). Each variant names its own curswant semantics,
/// replacing the old post-hoc `apply_sticky_col` catch-all;
/// `execute_motion` re-moves the landed cursor through the matching `Move`
/// variant.
///
/// There is deliberately no `Raw` class: `Move::Raw` is for pure
/// repositions owned by surrounding code (operator park/restore, host
/// state sync), and no plain motion is one — every motion either preserves
/// the sticky column (Vertical) or syncs it to the landed column (Jump /
/// Horizontal). The match below is exhaustive, so a Motion variant added
/// later must be classified here to compile.
///
/// See [`hjkl_engine::Move`] for the semantics of each class.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MotionClass {
    /// `j` / `k` and their screen-line equivalents — preserve the sticky
    /// column across rows.
    Vertical,
    /// Explicit jumps — the landing column is a target, not a relative
    /// step; vim resets curswant to the landed column.
    Jump,
    /// Relative moves within a row (or a row-relative target like `$`, `^`,
    /// `f`) — sticky tracks the landed column.
    Horizontal,
}

fn motion_class(motion: &Motion) -> MotionClass {
    use MotionClass::*;
    match motion {
        // Vertical: only these preserve the sticky column. Everything else
        // (search, gg / G, word jumps, ...) lands at the match's own column
        // so the sticky value syncs to the new cursor column.
        Motion::Up | Motion::Down | Motion::ScreenUp | Motion::ScreenDown => Vertical,
        // Jump: explicit target landings — `gg`/`G`, `%`, `[(`/`])`,
        // `*`/`#`, `n`/`N`, `H`/`M`/`L`, `{`/`}`, `(`/`)`, `[[`/`]]`/
        // `[]`/`][`, and the first-non-blank linewise motions `+`/`-`/`_`
        // (vim sets curswant to the landed first-non-blank column).
        Motion::FileTop
        | Motion::FileBottom
        | Motion::MatchBracket
        | Motion::UnmatchedBracket { .. }
        | Motion::WordAtCursor { .. }
        | Motion::SearchNext { .. }
        | Motion::ViewportTop
        | Motion::ViewportMiddle
        | Motion::ViewportBottom
        | Motion::ParagraphPrev
        | Motion::ParagraphNext
        | Motion::SentencePrev
        | Motion::SentenceNext
        | Motion::SectionBackward
        | Motion::SectionForward
        | Motion::SectionEndBackward
        | Motion::SectionEndForward
        | Motion::FirstNonBlankNextLine
        | Motion::FirstNonBlankPrevLine
        | Motion::FirstNonBlankLine => Jump,
        // Horizontal: moves whose landed column is the sticky target on the
        // same row. `FindRepeat` is resolved to `Find` (or the sneak
        // early-return) before it ever reaches the classifier.
        Motion::Left
        | Motion::Right
        | Motion::SpaceFwd
        | Motion::BackspaceBack
        | Motion::WordFwd
        | Motion::BigWordFwd
        | Motion::WordBack
        | Motion::BigWordBack
        | Motion::WordEnd
        | Motion::BigWordEnd
        | Motion::ChangeWordEnd { .. }
        | Motion::WordEndBack
        | Motion::BigWordEndBack
        | Motion::LineStart
        | Motion::Home
        | Motion::FirstNonBlank
        | Motion::LineEnd
        | Motion::Find { .. }
        | Motion::FindRepeat { .. }
        | Motion::LastNonBlank
        | Motion::LineMiddle
        | Motion::ScreenLineMiddle
        | Motion::ScreenLineStart
        | Motion::ScreenLineFirstNonBlank
        | Motion::ScreenLineEnd
        | Motion::GotoColumn => Horizontal,
        #[cfg(not(hjkl_exhaustive))]
        _ => Horizontal,
        // No Motion variant classifies Raw — see the enum docs.
    }
}
/// Vim's `foldOpenCursor()` as `'foldopen'` runs it after a command: open
/// every closed fold holding the cursor row. Vim only does this for a command
/// typed in Normal mode — not under an operator (callers on an operator path
/// never get here), not in Visual, and not while `@q` replays keys
/// (`KeyTyped` is false there) — so the gate lives here, once.
pub fn foldopen_cursor<H: hjkl_engine::types::Host>(ed: &mut Editor<hjkl_buffer::View, H>) {
    let st = vim(ed);
    if st.mode != Mode::Normal || st.replaying_macro {
        return;
    }
    let row = ed.cursor().0;
    ed.buffer_mut().open_folds_containing(row);
}
/// Whether vim's default `'foldopen'` (`block,hor,mark,percent,quickfix,
/// search,tag,undo`) opens the folds under the cursor once `motion` finishes
/// as a Normal-mode command. Each arm is the flag vim's own handler checks;
/// `succeeded` is the handler's success test, as `execute_motion` reads it
/// back (mostly "the cursor moved"), which is why a failed `l` at the end of
/// a line opens nothing. Measured against nvim 0.12.5:
/// `ge`/`gE`, `g_`, `gm`/`gM`, `|`, `H`/`M`/`L`, `+`/`-`/`_`, `gg`/`G` and
/// `j`/`k` leave the fold closed, and so do `g0` / `g^` / `g$`.
fn motion_opens_fold(motion: &Motion, count: usize, succeeded: bool) -> bool {
    match motion {
        // `hor`: `nv_beginline()` succeeds without moving, and so does
        // `nv_dollar()` unless a count runs it off the end of the buffer.
        Motion::LineStart | Motion::FirstNonBlank => true,
        // `percent`: a `%` that finds no bracket still opens the fold under
        // the cursor in nvim 0.12.5 (`zfj%j` from a bracket-less line ends
        // below the fold's first line).
        Motion::MatchBracket => true,
        Motion::LineEnd => succeeded || count == 1,
        // `hor`.
        Motion::Left
        | Motion::Right
        | Motion::SpaceFwd
        | Motion::BackspaceBack
        | Motion::WordFwd
        | Motion::BigWordFwd
        | Motion::WordBack
        | Motion::BigWordBack
        | Motion::WordEnd
        | Motion::BigWordEnd
        | Motion::Find { .. }
        | Motion::FindRepeat { .. }
        // `block`.
        | Motion::UnmatchedBracket { .. }
        | Motion::ParagraphPrev
        | Motion::ParagraphNext
        | Motion::SentencePrev
        | Motion::SentenceNext
        | Motion::SectionBackward
        | Motion::SectionForward
        | Motion::SectionEndBackward
        | Motion::SectionEndForward
        // `search`.
        | Motion::WordAtCursor { .. }
        | Motion::SearchNext { .. } => succeeded,
        Motion::Up
        | Motion::Down
        | Motion::ScreenUp
        | Motion::ScreenDown
        | Motion::ChangeWordEnd { .. }
        | Motion::WordEndBack
        | Motion::BigWordEndBack
        | Motion::FileTop
        | Motion::FileBottom
        | Motion::ViewportTop
        | Motion::ViewportMiddle
        | Motion::ViewportBottom
        | Motion::LastNonBlank
        | Motion::LineMiddle
        | Motion::ScreenLineMiddle
        | Motion::ScreenLineStart
        | Motion::ScreenLineFirstNonBlank
        | Motion::ScreenLineEnd
        | Motion::FirstNonBlankNextLine
        | Motion::FirstNonBlankPrevLine
        | Motion::FirstNonBlankLine
        | Motion::Home
        | Motion::GotoColumn => false,
        #[cfg(not(hjkl_exhaustive))]
        _ => false,
    }
}
/// The text area's width in cells, `0` before a host has published one.
fn screen_text_width<H: hjkl_engine::types::Host>(ed: &Editor<hjkl_buffer::View, H>) -> u16 {
    let v = ed.host().viewport();
    if v.text_width > 0 {
        v.text_width
    } else {
        v.width
    }
}

/// Whether the viewport soft-wraps, the test `move_screen_vertical` makes
/// before `gj` / `gk` walk screen lines instead of buffer rows.
pub fn screen_wraps<H: hjkl_engine::types::Host>(ed: &Editor<hjkl_buffer::View, H>) -> bool {
    let v = ed.host().viewport();
    !matches!(v.wrap, hjkl_buffer::Wrap::None) && v.text_width > 0
}

/// The screen line holding the cursor as `[start, end)` char columns of its
/// row, for `gm` / `g0` / `g^` / `g$`: the wrap segment under wrap, and without
/// it the columns from `Viewport::top_col` on that fit the text width. Cells
/// are measured as `wrap_segments` measures them, as `gj` / `gk` do.
fn screen_line_span<H: hjkl_engine::types::Host>(
    ed: &Editor<hjkl_buffer::View, H>,
) -> (usize, usize) {
    use hjkl_buffer::{Wrap, wrap_segments};
    let (row, col) = ed.cursor();
    let line = buf_line(ed.buffer(), row).unwrap_or_default();
    let v = *ed.host().viewport();
    if screen_wraps(ed) {
        let segs = wrap_segments(&line, v.text_width, v.wrap);
        return segs[hjkl_buffer::wrap::segment_for_col(&segs, col)];
    }
    let start = v.top_col.min(line.chars().count());
    let rest: String = line.chars().skip(start).collect();
    (
        start,
        start + wrap_segments(&rest, screen_text_width(ed), Wrap::Char)[0].1,
    )
}

/// The `cursor_down(count - 1)` that vim's `nv_dollar` and `g_` run before
/// moving along the line; false when it fails, which aborts the command.
/// It fails only on the last line: a count that overshoots the buffer still
/// succeeds, clamped (`5$` on three rows lands on row 2). Without this, `2$`
/// on a one-line buffer moved to the line end and `2C` / `2D` emptied the
/// line, where vim does nothing at all.
fn count_lines_down<H: hjkl_engine::types::Host>(
    ed: &mut Editor<hjkl_buffer::View, H>,
    count: usize,
) -> bool {
    if count <= 1 {
        return true;
    }
    if ed.cursor().0 >= last_content_row(ed) {
        return false;
    }
    let folds = hjkl_engine::SnapshotFoldProvider::from_buffer(ed.buffer());
    let mut sticky = ed.sticky_col();
    let tabstop = ed.settings().tabstop;
    hjkl_engine::motions::move_down(ed.buffer_mut(), &folds, count - 1, &mut sticky, tabstop);
    ed.set_sticky_col(sticky);
    true
}
pub fn apply_motion_cursor<H: hjkl_engine::types::Host>(
    ed: &mut Editor<hjkl_buffer::View, H>,
    motion: &Motion,
    count: usize,
) {
    apply_motion_cursor_ctx(ed, motion, count, false)
}
pub fn apply_motion_cursor_ctx<H: hjkl_engine::types::Host>(
    ed: &mut Editor<hjkl_buffer::View, H>,
    motion: &Motion,
    count: usize,
    as_operator: bool,
) {
    // Clamp the count where it fans out into the per-motion `0..count` walk.
    // Two bounds:
    //  - vim's documented ceiling (`:h count`) for folded counts; and
    //  - the buffer's character count, since a motion can never make progress
    //    past the end of the buffer — without this a pathological prefix
    //    (`999999999w`, `<big>dw`) would spin the walk up to ~1e9 times,
    //    freezing the UI, even though the result is identical to stopping at
    //    the buffer edge.
    let count = count
        .min(MAX_COUNT)
        .min(ed.buffer().rope().len_chars().saturating_add(1));
    match motion {
        Motion::Left => {
            // `h` — View clamps at col 0 (no wrap), matching vim.
            hjkl_engine::motions::move_left(ed.buffer_mut(), count);
        }
        Motion::Right => {
            // `l` — operator-motion context (`dl`/`cl`/`yl`) is allowed
            // one past the last char so the range includes it, and so is
            // Visual mode (vim's `nv_right` `past_line`), where the NUL
            // selects the line break; Normal mode clamps at the last char.
            if as_operator || vim(ed).is_visual() {
                hjkl_engine::motions::move_right_to_end(ed.buffer_mut(), count);
            } else {
                hjkl_engine::motions::move_right_in_line(ed.buffer_mut(), count);
            }
        }
        Motion::SpaceFwd => {
            // `<Space>` — wraps to next line at EOL in cursor context; mid-line
            // char delete like `l` under an operator (`d<Space>`).
            if as_operator {
                hjkl_engine::motions::move_right_to_end(ed.buffer_mut(), count);
            } else {
                hjkl_engine::motions::move_space_fwd(ed.buffer_mut(), count);
            }
        }
        Motion::BackspaceBack => {
            // `<BS>` — wraps to prev line's last char at BOL in cursor context;
            // mid-line char move like `h` under an operator (`d<BS>`).
            if as_operator {
                hjkl_engine::motions::move_left(ed.buffer_mut(), count);
            } else {
                hjkl_engine::motions::move_backspace_back(ed.buffer_mut(), count);
            }
        }
        Motion::Up => {
            // Final col is clamped by the `Move::Vertical` re-move in
            // `execute_motion` below — push the post-move row to the
            // textarea and let the vertical clamp finish the work.
            let folds = hjkl_engine::SnapshotFoldProvider::from_buffer(ed.buffer());
            let mut sticky = ed.sticky_col();
            let tabstop = ed.settings().tabstop;
            hjkl_engine::motions::move_up(ed.buffer_mut(), &folds, count, &mut sticky, tabstop);
            ed.set_sticky_col(sticky);
        }
        Motion::Down => {
            let folds = hjkl_engine::SnapshotFoldProvider::from_buffer(ed.buffer());
            let mut sticky = ed.sticky_col();
            let tabstop = ed.settings().tabstop;
            hjkl_engine::motions::move_down(ed.buffer_mut(), &folds, count, &mut sticky, tabstop);
            ed.set_sticky_col(sticky);
        }
        Motion::ScreenUp => {
            let v = *ed.host().viewport();
            let folds = hjkl_engine::SnapshotFoldProvider::from_buffer(ed.buffer());
            let mut sticky = ed.sticky_col();
            let tabstop = ed.settings().tabstop;
            hjkl_engine::motions::move_screen_up(
                ed.buffer_mut(),
                &folds,
                &v,
                count,
                &mut sticky,
                tabstop,
            );
            ed.set_sticky_col(sticky);
        }
        Motion::ScreenDown => {
            let v = *ed.host().viewport();
            let folds = hjkl_engine::SnapshotFoldProvider::from_buffer(ed.buffer());
            let mut sticky = ed.sticky_col();
            let tabstop = ed.settings().tabstop;
            hjkl_engine::motions::move_screen_down(
                ed.buffer_mut(),
                &folds,
                &v,
                count,
                &mut sticky,
                tabstop,
            );
            ed.set_sticky_col(sticky);
        }
        Motion::WordFwd | Motion::BigWordFwd => {
            let big = matches!(motion, Motion::BigWordFwd);
            let iskeyword = ed.settings().iskeyword.clone();
            let folds = hjkl_engine::SnapshotFoldProvider::from_buffer(ed.buffer());
            hjkl_engine::motions::move_word_fwd(ed.buffer_mut(), &folds, big, count, &iskeyword);
            // Cursor context: clamp to the last char of the line so a counted
            // `w` past EOF never lands past the last character.
            if !as_operator {
                let (row, col) = ed.cursor();
                let line_len = buf_line_chars(ed.buffer(), row);
                if col > line_len.saturating_sub(1) {
                    ed.jump_cursor(row, line_len.saturating_sub(1));
                }
            }
        }
        Motion::WordBack | Motion::BigWordBack => {
            let big = matches!(motion, Motion::BigWordBack);
            let iskeyword = ed.settings().iskeyword.clone();
            let folds = hjkl_engine::SnapshotFoldProvider::from_buffer(ed.buffer());
            hjkl_engine::motions::move_word_back(ed.buffer_mut(), &folds, big, count, &iskeyword);
        }
        Motion::WordEnd | Motion::BigWordEnd | Motion::ChangeWordEnd { .. } => {
            let (big, stop) = match motion {
                Motion::BigWordEnd => (true, false),
                Motion::ChangeWordEnd { big } => (*big, true),
                _ => (false, false),
            };
            let iskeyword = ed.settings().iskeyword.clone();
            let folds = hjkl_engine::SnapshotFoldProvider::from_buffer(ed.buffer());
            hjkl_engine::motions::move_word_end(
                ed.buffer_mut(),
                &folds,
                big,
                count,
                stop,
                &iskeyword,
            );
        }
        Motion::WordEndBack => {
            let iskeyword = ed.settings().iskeyword.clone();
            hjkl_engine::motions::move_word_end_back(ed.buffer_mut(), false, count, &iskeyword);
        }
        Motion::BigWordEndBack => {
            let iskeyword = ed.settings().iskeyword.clone();
            hjkl_engine::motions::move_word_end_back(ed.buffer_mut(), true, count, &iskeyword);
        }
        Motion::LineStart | Motion::Home => {
            hjkl_engine::motions::move_line_start(ed.buffer_mut());
        }
        Motion::FirstNonBlank => {
            hjkl_engine::motions::move_first_non_blank(ed.buffer_mut());
        }
        Motion::LineEnd => {
            // `[count]$`: move count-1 lines down, then to line end.
            // Vim normal-mode `$` lands on the last char, not one past it;
            // Visual mode lands on the NUL, so `v$` takes the line break.
            if count_lines_down(ed, count) {
                if vim(ed).is_visual() && !as_operator {
                    let row = ed.cursor().0;
                    let len = buf_line_chars(ed.buffer(), row);
                    buf_set_cursor_rc(ed.buffer_mut(), row, len);
                } else {
                    hjkl_engine::motions::move_line_end(ed.buffer_mut());
                }
            }
        }
        Motion::FileTop => {
            // `count gg` jumps to line `count` (first non-blank);
            // bare `gg` lands at the top.
            if count > 1 {
                hjkl_engine::motions::move_bottom(ed.buffer_mut(), count);
            } else {
                hjkl_engine::motions::move_top(ed.buffer_mut());
            }
        }
        Motion::FileBottom => {
            // `count G` jumps to line `count`; bare `G` lands at
            // the buffer bottom (`View::move_bottom(0)`).
            if count > 1 {
                hjkl_engine::motions::move_bottom(ed.buffer_mut(), count);
            } else {
                hjkl_engine::motions::move_bottom(ed.buffer_mut(), 0);
            }
        }
        Motion::Find { ch, forward, till } => {
            // Skip an adjacent target when this is a `;`/`,` repeat, and on the
            // 2nd..Nth step of a counted `t`/`T` (the cursor lands one cell
            // short each time, so a naive repeat would stick).
            let repeat = std::mem::take(&mut vim_mut(ed).find_repeat_skip);
            for i in 0..count {
                let skip_adjacent = repeat || i > 0;
                if !find_char_on_line(ed, *ch, *forward, *till, skip_adjacent) {
                    break;
                }
            }
        }
        Motion::FindRepeat { .. } => {} // already resolved upstream
        Motion::MatchBracket => {
            let _ = matching_bracket(ed);
        }
        Motion::UnmatchedBracket { forward, open } => {
            goto_unmatched_bracket(ed, *forward, *open, count);
        }
        Motion::WordAtCursor {
            forward,
            whole_word,
        } => {
            word_at_cursor_search(ed, *forward, *whole_word, count);
        }
        Motion::SearchNext { reverse } => {
            // Re-push the last query so the buffer's search state is
            // correct even if the host happened to clear it (e.g. while
            // a Visual mode draw was in progress).
            if let Some(pattern) = ed.last_search_pattern() {
                ed.push_search_pattern(&pattern);
            }
            if ed.search_state().pattern.is_none() {
                return;
            }
            // `n` repeats the last search in its committed direction;
            // `N` inverts. So a `?` search makes `n` walk backward and
            // `N` walk forward.
            let forward = ed.last_search_forward() != *reverse;
            // The last search's offset (`/pat/e`) applies again.
            let offset = ed.last_search_offset();
            crate::search_prompt::search_with_offset(ed, forward, offset.as_deref(), count);
        }
        Motion::ViewportTop => {
            let v = *ed.host().viewport();
            hjkl_engine::motions::move_viewport_top(ed.buffer_mut(), &v, count.saturating_sub(1));
        }
        Motion::ViewportMiddle => {
            let v = *ed.host().viewport();
            hjkl_engine::motions::move_viewport_middle(ed.buffer_mut(), &v);
        }
        Motion::ViewportBottom => {
            let v = *ed.host().viewport();
            hjkl_engine::motions::move_viewport_bottom(
                ed.buffer_mut(),
                &v,
                count.saturating_sub(1),
            );
        }
        Motion::LastNonBlank => {
            // `[count]g_`: count-1 lines down, as `$`.
            if count_lines_down(ed, count) {
                hjkl_engine::motions::move_last_non_blank(ed.buffer_mut());
            }
        }
        Motion::LineMiddle => {
            let row = ed.cursor().0;
            let line_chars = buf_line_chars(ed.buffer(), row);
            // Vim's `gM`: column = floor(chars / 2). Empty / single-char
            // lines stay at col 0.
            let target = line_chars / 2;
            ed.jump_cursor(row, target);
        }
        Motion::ScreenLineMiddle => {
            // Vim's `gm`: half the text width past the screen line's start
            // (where `g0` goes), clamped to the last char of the line.
            let row = ed.cursor().0;
            let width = usize::from(screen_text_width(ed));
            let last = buf_line_chars(ed.buffer(), row).saturating_sub(1);
            let target = (screen_line_span(ed).0 + width / 2).min(last);
            ed.jump_cursor(row, target);
        }
        Motion::ScreenLineStart => {
            let row = ed.cursor().0;
            ed.jump_cursor(row, screen_line_span(ed).0);
        }
        Motion::ScreenLineFirstNonBlank => {
            // vim steps right over blanks with `oneright`, which never goes
            // past the line's last character.
            let row = ed.cursor().0;
            let line: Vec<char> = buf_line(ed.buffer(), row)
                .unwrap_or_default()
                .chars()
                .collect();
            let start = screen_line_span(ed).0;
            let target = (start..line.len())
                .find(|&c| !matches!(line[c], ' ' | '\t'))
                .unwrap_or_else(|| line.len().saturating_sub(1));
            ed.jump_cursor(row, target);
        }
        Motion::ScreenLineEnd => {
            // `[count]g$`: count-1 screen lines down first; unlike `$`,
            // running out of lines still moves along the last one.
            if count > 1 {
                apply_motion_cursor_ctx(ed, &Motion::ScreenDown, count - 1, as_operator);
            }
            let row = ed.cursor().0;
            let len = buf_line_chars(ed.buffer(), row);
            let (start, end) = screen_line_span(ed);
            let width = usize::from(screen_text_width(ed));
            // vim aims at the screen line's last cell; past the line's end
            // that is the NUL in Visual, as `v$` takes it.
            let past_end = end == len && (width == 0 || end - start < width);
            if past_end && vim(ed).is_visual() && !as_operator {
                buf_set_cursor_rc(ed.buffer_mut(), row, len);
            } else {
                ed.jump_cursor(row, end.saturating_sub(1).max(start));
            }
        }
        Motion::ParagraphPrev => {
            hjkl_engine::motions::move_paragraph_prev(ed.buffer_mut(), count);
        }
        Motion::ParagraphNext => {
            hjkl_engine::motions::move_paragraph_next(ed.buffer_mut(), count);
        }
        // `(` / `)` are all-or-nothing under a count: vim's `findsent` returns
        // FAIL as soon as one repetition has nowhere left to go, and
        // `nv_brace` then beeps with the cursor untouched. Moving as far as
        // possible is what made `2)` on a single sentence-less line land on
        // the last char instead of staying put.
        Motion::SentencePrev => {
            if let Some((row, col)) = crate::vim::text_object::sentence_backward(ed, count) {
                ed.jump_cursor(row, col);
            }
        }
        // A `)` landing on the NUL past a line's end steps back onto the
        // last character in Normal mode (vim's `adjust_cursor`) and stays
        // on it in Visual, as `$` does.
        Motion::SentenceNext => {
            if let Some((row, col)) = crate::vim::text_object::sentence_forward(ed, count) {
                let on_nul = col > 0 && col == buf_line_chars(ed.buffer(), row);
                if on_nul && vim(ed).is_visual() && !as_operator {
                    buf_set_cursor_rc(ed.buffer_mut(), row, col);
                } else {
                    ed.jump_cursor(row, if on_nul { col - 1 } else { col });
                }
            }
        }
        Motion::SectionBackward => {
            hjkl_engine::motions::move_section_backward(ed.buffer_mut(), count);
        }
        Motion::SectionForward => {
            hjkl_engine::motions::move_section_forward(ed.buffer_mut(), count);
        }
        Motion::SectionEndBackward => {
            hjkl_engine::motions::move_section_end_backward(ed.buffer_mut(), count);
        }
        Motion::SectionEndForward => {
            hjkl_engine::motions::move_section_end_forward(ed.buffer_mut(), count);
        }
        // `+` / `<CR>` / `-` move with vim's `cursor_down` / `cursor_up`: a
        // closed fold counts as one line, a count past the edge stops there,
        // and the motion fails only when no line is left below / above the
        // cursor's fold.
        Motion::FirstNonBlankNextLine | Motion::FirstNonBlankPrevLine => {
            use hjkl_engine::types::FoldProvider;
            let down = matches!(motion, Motion::FirstNonBlankNextLine);
            let folds = hjkl_engine::SnapshotFoldProvider::from_buffer(ed.buffer());
            let mut row = ed.cursor().0;
            // `cursor_up` starts from the first line of the cursor's fold.
            if !down
                && folds.is_row_hidden(row)
                && let Some(first) = folds.prev_visible_row(row)
            {
                row = first;
                let col = ed.cursor().1;
                buf_set_cursor_rc(ed.buffer_mut(), row, col);
            }
            let has_line = if down {
                folds
                    .next_visible_row(row, last_content_row(ed) + 1)
                    .is_some()
            } else {
                folds.prev_visible_row(row).is_some()
            };
            if has_line {
                let mut sticky = ed.sticky_col();
                let tabstop = ed.settings().tabstop;
                if down {
                    hjkl_engine::motions::move_down(
                        ed.buffer_mut(),
                        &folds,
                        count,
                        &mut sticky,
                        tabstop,
                    );
                } else {
                    hjkl_engine::motions::move_up(
                        ed.buffer_mut(),
                        &folds,
                        count,
                        &mut sticky,
                        tabstop,
                    );
                }
                hjkl_engine::motions::move_first_non_blank(ed.buffer_mut());
            }
        }
        Motion::FirstNonBlankLine => {
            hjkl_engine::motions::move_first_non_blank_line(ed.buffer_mut(), count);
        }
        Motion::GotoColumn => {
            hjkl_engine::motions::move_goto_column(ed.buffer_mut(), count);
        }
        #[cfg(not(hjkl_exhaustive))]
        _ => {}
    }
}
pub fn move_first_non_whitespace<H: hjkl_engine::types::Host>(
    ed: &mut Editor<hjkl_buffer::View, H>,
) {
    // Some call sites invoke this right after `dd` / `<<` / `>>` etc
    // mutates the textarea content, so the migration buffer hasn't
    // seen the new lines OR new cursor yet. Mirror the full content
    // across before delegating, then push the result back so the
    // textarea reflects the resolved column too.
    ed.sync_buffer_content_from_textarea();
    hjkl_engine::motions::move_first_non_blank(ed.buffer_mut());
}
/// Where `I` starts inserting: before the first non-blank, or — on a row that
/// is all whitespace — after it. That is vim's `beginline(BL_WHITE)` without
/// the `BL_FIX` that keeps `^` on the row's last char.
pub fn move_to_insert_start<H: hjkl_engine::types::Host>(ed: &mut Editor<hjkl_buffer::View, H>) {
    move_first_non_whitespace(ed);
    let row = ed.cursor().0;
    let line = buf_line(ed.buffer(), row).unwrap_or_default();
    if !line.is_empty() && line.chars().all(super::vim_buf::is_vim_white) {
        buf_set_cursor_rc(ed.buffer_mut(), row, line.chars().count());
    }
}
/// Whether a `t` / `T` that left the cursor in place succeeded: vim's
/// `searchc` stops before an adjacent target without moving, but only with
/// no count and outside a `;` / `,` repeat, which skips that target.
pub fn till_succeeds_in_place<H: hjkl_engine::types::Host>(
    ed: &Editor<hjkl_buffer::View, H>,
    ch: char,
    forward: bool,
    count: usize,
    find_repeat: bool,
) -> bool {
    if count > 1 || find_repeat {
        return false;
    }
    let (row, col) = ed.cursor();
    let line: Vec<char> = buf_line(ed.buffer(), row)
        .unwrap_or_default()
        .chars()
        .collect();
    let adjacent = if forward {
        line.get(col + 1)
    } else {
        col.checked_sub(1).and_then(|c| line.get(c))
    };
    adjacent == Some(&ch)
}
/// Whether the search pattern matches at the cursor: the one place an `n`
/// / `N` / `*` / `#` whose only match is under the cursor wraps back to, a
/// success that does not move.
fn search_matches_at_cursor<H: hjkl_engine::types::Host>(
    ed: &Editor<hjkl_buffer::View, H>,
) -> bool {
    let Some(re) = ed.search_state().pattern.as_ref() else {
        return false;
    };
    let (row, col) = ed.cursor();
    let line = buf_line(ed.buffer(), row).unwrap_or_default();
    let byte = line.char_indices().nth(col).map_or(line.len(), |(b, _)| b);
    hjkl_buffer::search_match_ranges(re, &line)
        .iter()
        .any(|&(start, _)| start == byte)
}
pub fn find_char_on_line<H: hjkl_engine::types::Host>(
    ed: &mut Editor<hjkl_buffer::View, H>,
    ch: char,
    forward: bool,
    till: bool,
    skip_adjacent: bool,
) -> bool {
    hjkl_engine::motions::find_char_on_line(ed.buffer_mut(), ch, forward, till, skip_adjacent)
}
pub fn matching_bracket<H: hjkl_engine::types::Host>(
    ed: &mut Editor<hjkl_buffer::View, H>,
) -> bool {
    hjkl_engine::motions::match_bracket(ed.buffer_mut())
}
/// `[(` / `])` / `[{` / `]}` — move to the `count`-th previous (`forward =
/// false`) / next (`forward = true`) unmatched bracket of the kind given by
/// `open` (`(` or `{`). Balanced inner pairs are skipped via a depth counter.
pub fn goto_unmatched_bracket<H: hjkl_engine::types::Host>(
    ed: &mut Editor<hjkl_buffer::View, H>,
    forward: bool,
    open: char,
    count: usize,
) {
    let close = match open {
        '(' => ')',
        '{' => '}',
        _ => return,
    };
    let cursor = buf_cursor_pos(ed.buffer());
    let rows = buf_row_count(ed.buffer());
    let target = count.max(1);
    let mut found = 0usize;
    let mut depth = 0i32;

    if forward {
        let mut r = cursor.row;
        let mut from_col = cursor.col + 1;
        while r < rows {
            let line: Vec<char> = buf_line(ed.buffer(), r)
                .unwrap_or_default()
                .chars()
                .collect();
            let mut ci = from_col;
            while ci < line.len() {
                let ch = line[ci];
                if ch == open {
                    depth += 1;
                } else if ch == close {
                    if depth == 0 {
                        found += 1;
                        if found == target {
                            buf_set_cursor_rc(ed.buffer_mut(), r, ci);
                            return;
                        }
                    } else {
                        depth -= 1;
                    }
                }
                ci += 1;
            }
            r += 1;
            from_col = 0;
        }
    } else {
        let mut r = cursor.row as isize;
        // First row scans from the column left of the cursor; earlier rows from
        // their last column (`isize::MAX` clamps to `len - 1`).
        let mut from_col = cursor.col as isize - 1;
        while r >= 0 {
            let line: Vec<char> = buf_line(ed.buffer(), r as usize)
                .unwrap_or_default()
                .chars()
                .collect();
            let mut ci = from_col.min(line.len() as isize - 1);
            while ci >= 0 {
                let ch = line[ci as usize];
                if ch == close {
                    depth += 1;
                } else if ch == open {
                    if depth == 0 {
                        found += 1;
                        if found == target {
                            buf_set_cursor_rc(ed.buffer_mut(), r as usize, ci as usize);
                            return;
                        }
                    } else {
                        depth -= 1;
                    }
                }
                ci -= 1;
            }
            r -= 1;
            from_col = isize::MAX;
        }
    }
}
pub fn word_at_cursor_search<H: hjkl_engine::types::Host>(
    ed: &mut Editor<hjkl_buffer::View, H>,
    forward: bool,
    whole_word: bool,
    count: usize,
) {
    let (row, col) = ed.cursor();
    let line: String = buf_line(ed.buffer(), row).unwrap_or_default();
    let chars: Vec<char> = line.chars().collect();
    if chars.is_empty() {
        return;
    }
    // Expand around cursor to a word boundary.
    let spec = ed.settings().iskeyword.clone();
    let is_word = |c: char| is_keyword_char(c, &spec);
    let mut start = col.min(chars.len().saturating_sub(1));
    if is_word(chars[start]) {
        while start > 0 && is_word(chars[start - 1]) {
            start -= 1;
        }
    } else {
        // B19: the cursor isn't on a keyword char. `:h star` — both `*`
        // and `#` advance FORWARD to the next keyword char on this line
        // before extracting the word; only the SEARCH that follows differs
        // by direction. Anchor the actual cursor at the found word's start
        // so the subsequent search-advance call's skip-current logic
        // treats it as the current match and steps to the true next (or,
        // for `#`, previous) occurrence — matching nvim, which lands on
        // the *second* occurrence from punctuation, not the nearest one.
        while start < chars.len() && !is_word(chars[start]) {
            start += 1;
        }
        if start >= chars.len() {
            return;
        }
        buf_set_cursor_rc(ed.buffer_mut(), row, start);
    }
    let mut end = start;
    while end < chars.len() && is_word(chars[end]) {
        end += 1;
    }
    if end <= start {
        return;
    }
    let word: String = chars[start..end].iter().collect();
    let escaped = regex_escape(&word);
    let pattern = if whole_word {
        format!(r"\b{escaped}\b")
    } else {
        escaped
    };
    search_pattern_and_advance(ed, pattern, forward, count);
}

pub fn search_selected_text<H: hjkl_engine::types::Host>(
    ed: &mut Editor<hjkl_buffer::View, H>,
    selected: &str,
    forward: bool,
    count: usize,
) -> bool {
    if selected.is_empty() {
        return false;
    }
    let selected = selected.replace('\\', r"\\").replace('\n', r"\n");
    let pattern = format!(r"\V{selected}");
    let (installed, found) = search_pattern_and_advance(ed, pattern.clone(), forward, count);
    if installed {
        ed.record_search_history(&pattern);
    }
    found
}

fn search_pattern_and_advance<H: hjkl_engine::types::Host>(
    ed: &mut Editor<hjkl_buffer::View, H>,
    pattern: String,
    forward: bool,
    count: usize,
) -> (bool, bool) {
    ed.push_search_pattern(&pattern);
    if ed.search_state().pattern.is_none() {
        return (false, false);
    }
    // Remember the query so `n` / `N` keep working after the jump. A new
    // pattern without an offset drops the old one, as vim's `do_search` does.
    ed.set_last_search_pattern_only(Some(pattern));
    ed.set_last_search_offset(None);
    ed.set_last_search_forward_only(forward);
    let mut found = false;
    for _ in 0..count.max(1) {
        found |= if forward {
            ed.search_advance_forward(true)
        } else {
            ed.search_advance_backward(true)
        };
    }
    (true, found)
}
pub fn regex_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        if matches!(
            c,
            '.' | '+' | '*' | '?' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | '^' | '$' | '\\'
        ) {
            out.push('\\');
        }
        out.push(c);
    }
    out
}