hjkl 0.33.5

Vim-modal terminal editor: standalone TUI built on the hjkl engine.
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
//! VSCode keybinding dispatcher (V7: find / Ctrl+F).
//!
//! Non-modal "EDITOR" mode: there are two underlying states —
//!   • INSERT  — no active selection; caret between chars (bar cursor).
//!   • VISUAL  — a char-wise selection exists; the selection is **exclusive**
//!               (the caret sits *before* the cell at `cursor()`).
//!
//! Shift+arrows extend/begin the selection; plain arrows collapse it.
//! Typing / Backspace / Delete with an active selection replaces / deletes it.
//! Ctrl+A selects the whole buffer.
//!
//! ## V6 clipboard (Ctrl+C / Ctrl+X / Ctrl+V)
//!
//! Cut/copy write to BOTH the unnamed register (`"`) for in-session round-trips
//! AND the system clipboard (`host.write_clipboard`) for cross-app use.
//!
//! Paste reads the OS clipboard first (`host.read_clipboard()`), falling back
//! to the unnamed register when the OS clipboard is unreadable or `None` — so
//! in-session cut→paste round-trips work deterministically in CI (where OSC52
//! is write-only / unreadable).
//!
//! Ctrl+C without a selection is a no-op (the caller keeps the `Ctrl+C →
//! quit` path alive when there is no selection — see `event_loop.rs`).
//!
//! ### Double-sync avoidance
//!
//! `dispatch_vscode_key` must NOT call `sync_after_engine_mutation` internally;
//! the caller (`event_loop.rs`) runs the full post-dispatch sync block after
//! every call. For paste we use a private `vscode_insert_text` helper that
//! calls `insert_str` + `mark_content_dirty` — matching what `handle_paste`
//! does but without the extra `sync_after_engine_mutation` call inside it.
//!
//! Caller contract (mirrors the Insert-mode FallThrough path in `event_loop`):
//! - Call `dispatch_vscode_key` before the main vim routing.
//! - The caller runs all post-edit sync after this returns (viewport, dirty,
//!   content-reset, edits, LSP, sibling cursors, fold-ops, pending_recompute).
//! - Do NOT emit cursor shape or run sync here.

use super::{App, SearchDir};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use hjkl_engine::{BufferEdit, Host, InsertDir, Motion, Pos, VimMode};

impl App {
    /// VSCode-discipline early key intercept — the single routing choke point
    /// shared by the primary and drain-loop `Event::Key` paths in
    /// `event_loop.rs` (previously two byte-identical copies). When the active
    /// discipline is VSCode and no overlay owns the key, this dispatches it
    /// through the non-modal [`App::dispatch_vscode_key`] and runs the full
    /// post-edit sync chain, returning `true` so the caller `continue`s and
    /// skips the vim FSM.
    ///
    /// Returns `false` when this key is NOT a VSCode intercept — not in VSCode
    /// mode, a non-selection `Ctrl+C` (kept alive for quit / overlay-dismiss),
    /// or an overlay (command / search / hop / quickfix / loclist) is active —
    /// in which case the caller falls through to `handle_keypress`.
    ///
    /// `key` must already be discipline-normalized (VSCode keeps raw keys;
    /// `normalize_legacy` in `event_loop` runs vim-only, before this).
    pub(crate) fn try_vscode_intercept(&mut self, key: KeyEvent) -> bool {
        // Non-modal: bypass the vim FSM entirely. Ctrl+C without an active
        // selection is exempted so quit / overlay-dismiss still works; with a
        // selection it copies. Overlays take priority.
        let is_ctrl_c =
            key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL);
        let ctrl_c_copy = is_ctrl_c && self.vscode_has_selection();
        if !(self.keybinding_mode == hjkl_engine::KeybindingMode::Vscode
            && (!is_ctrl_c || ctrl_c_copy)
            && self.command_field.is_none()
            && self.search_field.is_none()
            && self.hop.is_none()
            && !self.quickfix_open
            && !self.loclist_open)
        {
            return false;
        }
        self.scroll_anim = None;
        let prev_top = self.window_scroll(self.focused_window()).0;
        self.dispatch_vscode_key(key);
        self.active_editor_mut().emit_cursor_shape_if_changed();
        self.sync_viewport_from_editor();
        if self.active_editor_mut().take_dirty() {
            let elapsed = self.active_mut().refresh_dirty_against_saved();
            self.last_signature_us = elapsed;
            if self.active().dirty {
                self.active_mut().is_new_file = false;
            }
        }
        let buffer_id = self.active().buffer_id;
        if self.active_editor_mut().take_content_reset() {
            self.handle_active_content_reset(buffer_id);
        }
        let edits = self.active_editor_mut().take_content_edits();
        if !edits.is_empty() {
            self.syntax.apply_edits(buffer_id, &edits);
            self.active_editor_mut()
                .shift_syntax_spans_for_edits(&edits);
        }
        self.lsp_notify_change_active(&edits);
        self.rebase_sibling_cursors(&edits);
        let _ = self.active_editor_mut().take_fold_ops();
        {
            let hint = self.active_editor_mut().take_scroll_anim_hint();
            if hint {
                let ms = self.active_editor().settings().scroll_duration_ms;
                let win = self.focused_window();
                let new_top = self.window_scroll(win).0;
                if ms > 0 && new_top != prev_top {
                    self.scroll_anim = Some(crate::app::ScrollAnim {
                        win_id: win,
                        start_top: prev_top,
                        target_top: new_top,
                        started_at: std::time::Instant::now(),
                        duration: std::time::Duration::from_millis(ms as u64),
                    });
                }
            }
        }
        self.pending_recompute = true;
        true
    }

    /// Dispatch a single key event in VSCode (non-modal) mode.
    ///
    /// Home state is INSERT. A charwise-Visual selection is the "selection"
    /// state — it is exclusive (half-open end, `selection_exclusive = true`
    /// on every editor in vscode mode).
    pub(crate) fn dispatch_vscode_key(&mut self, key: KeyEvent) {
        // ── ensure the editor starts in Insert (first call after launch) ─────
        // When no selection is active the engine must be in Insert. If we're
        // in Visual (selection active) we stay there; if in Normal (startup or
        // after some internal transition) we force Insert.
        {
            let mode = self.active_editor().vim_mode();
            if mode != VimMode::Insert && mode != VimMode::Visual {
                self.active_editor_mut().enter_insert_i(1);
            }
        }

        match (key.code, key.modifiers) {
            // ── Ctrl shortcuts ─────────────────────────────────────────────────

            // Ctrl+S → save
            (KeyCode::Char('s'), KeyModifiers::CONTROL) => {
                self.do_save(None);
            }

            // Ctrl+Z → undo
            (KeyCode::Char('z'), KeyModifiers::CONTROL) => {
                self.collapse_to_insert_if_visual();
                self.active_editor_mut().undo();
            }

            // Ctrl+Y → redo
            (KeyCode::Char('y'), KeyModifiers::CONTROL) => {
                self.collapse_to_insert_if_visual();
                self.active_editor_mut().redo();
            }

            // Ctrl+Shift+Z → redo (common alternative)
            (KeyCode::Char('z'), mods) if mods == KeyModifiers::CONTROL | KeyModifiers::SHIFT => {
                self.collapse_to_insert_if_visual();
                self.active_editor_mut().redo();
            }

            // Ctrl+A → select whole buffer
            (KeyCode::Char('a'), KeyModifiers::CONTROL) => {
                self.vscode_select_all();
            }

            // ── V7 find (Ctrl+F / F3 / Shift+F3) ─────────────────────────

            // Ctrl+F → open the incremental search prompt (forward).
            // If a selection is active, seed the find box with the selected
            // text (VSCode behaviour) — one-liner via set_text.
            (KeyCode::Char('f'), KeyModifiers::CONTROL) => {
                let seed = if self.vscode_has_selection() {
                    self.vscode_selection_text()
                } else {
                    None
                };
                self.open_search_prompt(SearchDir::Forward);
                if let (Some(text), Some(field)) = (seed, self.search_field.as_mut()) {
                    field.set_text(&text);
                    field.enter_insert_at_end();
                }
            }

            // F3 → next match (repeat last search forward).
            (KeyCode::F(3), KeyModifiers::NONE) => {
                self.active_editor_mut().search_repeat(true, 1);
            }

            // Shift+F3 → previous match (repeat last search backward).
            (KeyCode::F(3), mods) if mods.contains(KeyModifiers::SHIFT) => {
                self.active_editor_mut().search_repeat(false, 1);
            }

            // ── V6 clipboard chords ────────────────────────────────────────

            // Ctrl+C → copy selection (no-op when no selection; the caller
            // keeps Ctrl+C → quit alive when vscode_has_selection() is false,
            // so this arm only fires when a selection is active).
            (KeyCode::Char('c'), KeyModifiers::CONTROL) => {
                if self.vscode_has_selection() {
                    self.vscode_copy_selection();
                }
                // No selection: fall through (no-op here); the event_loop guard
                // ensures we only reach this arm when a selection is present.
            }

            // Ctrl+X → cut selection (copy + delete). No selection → cut whole line.
            (KeyCode::Char('x'), KeyModifiers::CONTROL) => {
                if self.vscode_has_selection() {
                    self.vscode_copy_selection();
                    self.vscode_delete_selection();
                } else {
                    self.vscode_cut_line();
                }
            }

            // Ctrl+V → paste. Reads OS clipboard first, falls back to the
            // unnamed register. If a selection is active, deletes it first
            // (→ INSERT) then inserts the pasted text at the caret.
            (KeyCode::Char('v'), KeyModifiers::CONTROL) => {
                // Read OS clipboard first (split borrow: host_mut is released
                // before we read the register).
                let clip = self.active_editor_mut().host_mut().read_clipboard();
                let clip_text = clip.filter(|s| !s.is_empty());
                // Fall back to unnamed register when OS clipboard is
                // unreadable (CI/PTY env where OSC52 is write-only).
                let reg_text = if clip_text.is_none() {
                    let t = self
                        .active_editor()
                        .registers()
                        .read('"')
                        .map(|s| s.text.clone())
                        .unwrap_or_default();
                    if t.is_empty() { None } else { Some(t) }
                } else {
                    None
                };
                let text = clip_text.or(reg_text);
                if let Some(text) = text {
                    if self.vscode_has_selection() {
                        self.vscode_delete_selection();
                    }
                    self.vscode_insert_text(&text);
                }
            }

            // Esc → collapse any selection, stay in Insert (non-modal; do NOT
            // leave Insert the way vim does)
            (KeyCode::Esc, _) => {
                self.collapse_to_insert_if_visual();
            }

            // ── Ctrl+Shift+arrows: word-wise selection extend ──────────────────
            (KeyCode::Left, mods) if mods == KeyModifiers::CONTROL | KeyModifiers::SHIFT => {
                self.vscode_shift_word(ShiftDir::WordBack);
            }
            (KeyCode::Right, mods) if mods == KeyModifiers::CONTROL | KeyModifiers::SHIFT => {
                self.vscode_shift_word(ShiftDir::WordFwd);
            }

            // ── Ctrl+arrows: word navigation ───────────────────────────────────
            // Ctrl+Left → word-backward (collapse selection first if any)
            (KeyCode::Left, mods) if mods == KeyModifiers::CONTROL => {
                self.collapse_to_insert_if_visual();
                self.active_editor_mut().execute_motion(Motion::WordBack, 1);
            }
            // Ctrl+Right → word-forward (collapse selection first if any)
            (KeyCode::Right, mods) if mods == KeyModifiers::CONTROL => {
                self.collapse_to_insert_if_visual();
                self.active_editor_mut().execute_motion(Motion::WordFwd, 1);
            }

            // ── Shift+arrow: begin or extend selection ─────────────────────────
            (KeyCode::Left, mods) if mods.contains(KeyModifiers::SHIFT) => {
                self.vscode_shift_arrow(ShiftDir::Left);
            }
            (KeyCode::Right, mods) if mods.contains(KeyModifiers::SHIFT) => {
                self.vscode_shift_arrow(ShiftDir::Right);
            }
            (KeyCode::Up, mods) if mods.contains(KeyModifiers::SHIFT) => {
                self.vscode_shift_arrow(ShiftDir::Up);
            }
            (KeyCode::Down, mods) if mods.contains(KeyModifiers::SHIFT) => {
                self.vscode_shift_arrow(ShiftDir::Down);
            }
            (KeyCode::Home, mods) if mods.contains(KeyModifiers::SHIFT) => {
                self.vscode_shift_arrow(ShiftDir::Home);
            }
            (KeyCode::End, mods) if mods.contains(KeyModifiers::SHIFT) => {
                self.vscode_shift_arrow(ShiftDir::End);
            }

            // ── Plain arrows: collapse selection then navigate ─────────────────
            (KeyCode::Left, KeyModifiers::NONE) => {
                self.vscode_plain_arrow(InsertDir::Left);
            }
            (KeyCode::Right, KeyModifiers::NONE) => {
                self.vscode_plain_arrow(InsertDir::Right);
            }
            (KeyCode::Up, KeyModifiers::NONE) => {
                self.vscode_plain_arrow(InsertDir::Up);
            }
            (KeyCode::Down, KeyModifiers::NONE) => {
                self.vscode_plain_arrow(InsertDir::Down);
            }
            (KeyCode::Home, KeyModifiers::NONE) => {
                self.vscode_plain_home_end(false);
            }
            (KeyCode::End, KeyModifiers::NONE) => {
                self.vscode_plain_home_end(true);
            }

            // ── Kitty chords (reachable under DISAMBIGUATE_ESCAPE_CODES) ──────

            // Ctrl+/ → toggle comment on current line or selection
            (KeyCode::Char('/'), KeyModifiers::CONTROL) => {
                let (top, bot) = if self.vscode_has_selection() {
                    if let Some(((sr, _), (er, _))) =
                        self.active_editor().visual_char_range_exclusive()
                    {
                        (sr, er)
                    } else {
                        let (row, _) = self.active_editor().cursor();
                        (row, row)
                    }
                } else {
                    let (row, _) = self.active_editor().cursor();
                    (row, row)
                };
                if self.vscode_has_selection() {
                    self.collapse_to_insert_if_visual();
                }
                self.active_editor_mut().toggle_comment_range(top, bot);
            }

            // Ctrl+] → indent selection or current line by one shiftwidth
            (KeyCode::Char(']'), KeyModifiers::CONTROL) => {
                let (top, bot) = if self.vscode_has_selection() {
                    if let Some(((sr, _), (er, _))) =
                        self.active_editor().visual_char_range_exclusive()
                    {
                        (sr, er)
                    } else {
                        let (row, _) = self.active_editor().cursor();
                        (row, row)
                    }
                } else {
                    let (row, _) = self.active_editor().cursor();
                    (row, row)
                };
                if self.vscode_has_selection() {
                    self.collapse_to_insert_if_visual();
                }
                // shiftwidth=0 → use the editor's own settings.shiftwidth
                self.active_editor_mut()
                    .indent_range((top, 0), (bot, 0), 1, 0);
            }

            // Ctrl+[ → outdent selection or current line by one shiftwidth
            (KeyCode::Char('['), KeyModifiers::CONTROL) => {
                let (top, bot) = if self.vscode_has_selection() {
                    if let Some(((sr, _), (er, _))) =
                        self.active_editor().visual_char_range_exclusive()
                    {
                        (sr, er)
                    } else {
                        let (row, _) = self.active_editor().cursor();
                        (row, row)
                    }
                } else {
                    let (row, _) = self.active_editor().cursor();
                    (row, row)
                };
                if self.vscode_has_selection() {
                    self.collapse_to_insert_if_visual();
                }
                // shiftwidth=0 → use the editor's own settings.shiftwidth
                self.active_editor_mut()
                    .indent_range((top, 0), (bot, 0), -1, 0);
            }

            // Ctrl+Backspace → delete word before caret (insert_ctrl_w)
            (KeyCode::Backspace, KeyModifiers::CONTROL) => {
                if self.vscode_has_selection() {
                    self.vscode_delete_selection();
                } else {
                    self.active_editor_mut().insert_ctrl_w();
                }
            }

            // ── Printable characters ───────────────────────────────────────────
            (KeyCode::Char(c), mods)
                if mods == KeyModifiers::NONE || mods == KeyModifiers::SHIFT =>
            {
                if self.vscode_has_selection() {
                    self.vscode_delete_selection();
                }
                self.active_editor_mut().insert_char(c);
            }

            // ── Editing keys ───────────────────────────────────────────────────
            (KeyCode::Backspace, _) => {
                if self.vscode_has_selection() {
                    self.vscode_delete_selection();
                } else {
                    self.active_editor_mut().insert_backspace();
                }
            }
            // Ctrl+Delete → delete word forward (or selection if active)
            (KeyCode::Delete, mods) if mods.contains(KeyModifiers::CONTROL) => {
                if self.vscode_has_selection() {
                    self.vscode_delete_selection();
                } else {
                    self.vscode_delete_word_fwd();
                }
            }
            (KeyCode::Delete, _) => {
                if self.vscode_has_selection() {
                    self.vscode_delete_selection();
                } else {
                    self.active_editor_mut().insert_delete();
                }
            }
            (KeyCode::Enter, _) => {
                if self.vscode_has_selection() {
                    self.vscode_delete_selection();
                }
                self.active_editor_mut().insert_newline();
            }
            (KeyCode::Tab, _) => {
                if self.vscode_has_selection() {
                    self.vscode_delete_selection();
                }
                self.active_editor_mut().insert_tab();
            }

            // ── Page navigation ────────────────────────────────────────────────
            (KeyCode::PageUp, _) => {
                self.collapse_to_insert_if_visual();
                let h = self.active_editor().viewport_height_value();
                self.active_editor_mut().insert_pageup(h);
            }
            (KeyCode::PageDown, _) => {
                self.collapse_to_insert_if_visual();
                let h = self.active_editor().viewport_height_value();
                self.active_editor_mut().insert_pagedown(h);
            }

            // Drop anything else (function keys, alt combos, …)
            _ => {}
        }
    }

    // ── Selection helpers ──────────────────────────────────────────────────────

    /// `true` when there is an active (non-empty) VSCode selection.
    /// Exposed as `pub(crate)` so `event_loop.rs` can check it inside the
    /// Ctrl+C guard without entering `dispatch_vscode_key`.
    pub(crate) fn vscode_has_selection(&self) -> bool {
        let ed = self.active_editor();
        ed.vim_mode() == VimMode::Visual && ed.visual_char_range_exclusive().is_some()
    }

    // ── V6 clipboard helpers ───────────────────────────────────────────────────

    /// Extract the text covered by the current exclusive VSCode selection.
    ///
    /// Returns `None` when no selection is active. Reads directly from the
    /// buffer rope using char indices so the result is exactly the half-open
    /// range — no trailing character, no linewise newline expansion, and
    /// correct for multi-byte/multi-codepoint content.
    fn vscode_selection_text(&self) -> Option<String> {
        let ((sr, sc), (er, ec)) = self.active_editor().visual_char_range_exclusive()?;
        let rope = self.active_editor().buffer().rope();
        // Convert (row, char-col) to absolute char indices. ropey's
        // `line_to_char` returns the char index of the first codepoint of the
        // row (including the trailing '\n' of the previous row), so adding the
        // column gives the exact codepoint position.
        let start_char = rope.line_to_char(sr) + sc;
        let end_char = rope.line_to_char(er) + ec;
        Some(rope.slice(start_char..end_char).to_string())
    }

    /// Write the current selection text to both the unnamed register and the
    /// system clipboard. Does NOT modify the buffer or change mode.
    fn vscode_copy_selection(&mut self) {
        let text = match self.vscode_selection_text() {
            Some(t) if !t.is_empty() => t,
            _ => return,
        };
        // Write to unnamed register (in-session fallback for CI / read-only clipboard).
        self.active_editor_mut().set_yank(text.clone());
        // Write to system clipboard (fire-and-forget; host queues the write).
        self.active_editor_mut().host_mut().write_clipboard(text);
    }

    /// Insert `text` at the current caret in Insert mode.
    ///
    /// Mirrors the body of `handle_paste` (CRLF normalisation + `insert_str`)
    /// but does NOT call `sync_after_engine_mutation` — the caller's post-
    /// dispatch sync block in `event_loop.rs` handles that.
    fn vscode_insert_text(&mut self, text: &str) {
        if text.is_empty() {
            return;
        }
        // Ensure we are in Insert before inserting.
        if self.active_editor().vim_mode() != VimMode::Insert {
            self.active_editor_mut().enter_insert_i(1);
        }
        let normalised = if text.contains('\r') {
            text.replace("\r\n", "\n").replace('\r', "\n")
        } else {
            text.to_owned()
        };
        self.active_editor_mut().insert_str(&normalised);
        self.active_editor_mut().mark_content_dirty();
    }

    /// Collapse a Visual selection back to Insert mode. The caret stays where
    /// it is (anchor is discarded). No-op when already in Insert.
    fn collapse_to_insert_if_visual(&mut self) {
        if self.active_editor().vim_mode() == VimMode::Visual {
            self.active_editor_mut().exit_visual_to_normal();
            self.active_editor_mut().enter_insert_i(1);
        }
    }

    /// Delete the current exclusive VSCode selection and return to Insert.
    /// The caret lands at `start` (the lower of anchor/cursor).
    ///
    /// Uses `BufferEdit::delete_range` directly (half-open, exactly what
    /// exclusive VSCode selection expresses) — no vim register or undo-group
    /// special-casing needed.
    fn vscode_delete_selection(&mut self) {
        let range = self.active_editor().visual_char_range_exclusive();
        if let Some(((sr, sc), (er, ec))) = range {
            let start = Pos::new(sr as u32, sc as u32);
            let end = Pos::new(er as u32, ec as u32);
            // Exit visual first, re-enter insert.
            self.active_editor_mut().exit_visual_to_normal();
            self.active_editor_mut().enter_insert_i(1);
            // Delete the half-open range [start, end).
            BufferEdit::delete_range(self.active_editor_mut().buffer_mut(), start..end);
            // Place the caret at start.
            self.active_editor_mut().set_cursor_doc(sr, sc);
            // Mark content dirty so sync path picks up the change.
            self.active_editor_mut().mark_content_dirty();
        }
    }

    /// Ctrl+A — select the whole buffer. Anchor at (0,0), caret at the
    /// exclusive end of the last line (char_len of last line).
    fn vscode_select_all(&mut self) {
        // Collapse any existing selection first.
        if self.active_editor().vim_mode() == VimMode::Visual {
            self.active_editor_mut().exit_visual_to_normal();
        }
        // Move to (0,0) and enter visual.
        self.active_editor_mut().enter_insert_i(1);
        self.active_editor_mut().set_cursor_doc(0, 0);
        self.active_editor_mut().enter_visual_char();
        // Move the caret to the exclusive end of the buffer.
        let (last_row, last_col) = {
            let ed = self.active_editor();
            let row_count = ed.row_count();
            if row_count == 0 {
                (0, 0)
            } else {
                let last_r = row_count - 1;
                let last_c = ed.line_char_count(last_r);
                (last_r, last_c)
            }
        };
        self.active_editor_mut().set_cursor_doc(last_row, last_col);
    }

    /// Shift+arrow: begin or extend the selection.
    fn vscode_shift_arrow(&mut self, dir: ShiftDir) {
        let in_visual = self.active_editor().vim_mode() == VimMode::Visual;
        // If Insert → anchor at current cursor, enter visual.
        if !in_visual {
            let (row, col) = self.active_editor().cursor();
            // Enter insert first (may already be there) then enter visual char.
            // (The engine anchors at the cursor when entering visual.)
            let _ = (row, col); // anchor is implicit in enter_visual_char
            self.active_editor_mut().enter_visual_char();
        }
        // Move the caret one step in the requested direction.
        let (new_row, new_col) = self.vscode_compute_move(dir);
        let anchor = self.active_editor().visual_anchor();
        self.active_editor_mut().set_cursor_doc(new_row, new_col);
        // If the caret returned to the anchor → empty selection → collapse.
        let cursor = self.active_editor().cursor();
        if cursor == anchor {
            self.active_editor_mut().exit_visual_to_normal();
            self.active_editor_mut().enter_insert_i(1);
        }
    }

    /// Plain (no-shift) arrow: if a selection is active, collapse to the
    /// appropriate boundary; if not, perform the insert-mode arrow move.
    fn vscode_plain_arrow(&mut self, dir: InsertDir) {
        if self.vscode_has_selection() {
            // VSCode collapses to selection start for Left/Up, end for Right/Down.
            let use_start = matches!(dir, InsertDir::Left | InsertDir::Up);
            let (row, col) = {
                let ed = self.active_editor();
                if let Some(((sr, sc), (er, ec))) = ed.visual_char_range_exclusive() {
                    if use_start { (sr, sc) } else { (er, ec) }
                } else {
                    ed.cursor()
                }
            };
            self.active_editor_mut().exit_visual_to_normal();
            self.active_editor_mut().enter_insert_i(1);
            self.active_editor_mut().set_cursor_doc(row, col);
        } else {
            self.active_editor_mut().insert_arrow(dir);
        }
    }

    /// Plain Home/End: if a selection is active, collapse (Home → start, End →
    /// end); if not, perform the insert-mode home/end move.
    fn vscode_plain_home_end(&mut self, is_end: bool) {
        if self.vscode_has_selection() {
            let (row, col) = {
                let ed = self.active_editor();
                if let Some(((sr, sc), (er, ec))) = ed.visual_char_range_exclusive() {
                    if is_end { (er, ec) } else { (sr, sc) }
                } else {
                    ed.cursor()
                }
            };
            self.active_editor_mut().exit_visual_to_normal();
            self.active_editor_mut().enter_insert_i(1);
            self.active_editor_mut().set_cursor_doc(row, col);
        } else if is_end {
            self.active_editor_mut().insert_end();
        } else {
            self.active_editor_mut().insert_home();
        }
    }

    /// Compute the caret position after a one-step shift-arrow move.
    /// The editor may be in Visual mode when this is called.
    fn vscode_compute_move(&self, dir: ShiftDir) -> (usize, usize) {
        let ed = self.active_editor();
        let (row, col) = ed.cursor();
        match dir {
            ShiftDir::Left => {
                if col > 0 {
                    (row, col - 1)
                } else if row > 0 {
                    // Wrap to end of previous line.
                    let prev_len = ed.line_char_count(row - 1);
                    (row - 1, prev_len)
                } else {
                    (0, 0)
                }
            }
            ShiftDir::Right => {
                let line_len = ed.line_char_count(row);
                let row_count = ed.row_count();
                if col < line_len {
                    (row, col + 1)
                } else if row + 1 < row_count {
                    // Wrap to start of next line.
                    (row + 1, 0)
                } else {
                    (row, col)
                }
            }
            ShiftDir::Up => {
                if row > 0 {
                    let new_col = col.min(ed.line_char_count(row - 1));
                    (row - 1, new_col)
                } else {
                    (0, 0)
                }
            }
            ShiftDir::Down => {
                let row_count = ed.row_count();
                if row + 1 < row_count {
                    let new_col = col.min(ed.line_char_count(row + 1));
                    (row + 1, new_col)
                } else {
                    // Already on last row — move to exclusive end of line.
                    let line_len = ed.line_char_count(row);
                    (row, line_len)
                }
            }
            ShiftDir::Home => (row, 0),
            ShiftDir::End => {
                let line_len = ed.line_char_count(row);
                (row, line_len)
            }
            ShiftDir::WordFwd | ShiftDir::WordBack => {
                // These are handled by vscode_shift_word, not vscode_compute_move.
                unreachable!("word directions are handled by vscode_shift_word")
            }
        }
    }

    /// Ctrl+Shift+arrow: begin or extend the selection by one word.
    fn vscode_shift_word(&mut self, dir: ShiftDir) {
        let in_visual = self.active_editor().vim_mode() == VimMode::Visual;
        if !in_visual {
            self.active_editor_mut().enter_visual_char();
        }
        // Execute the word motion (moves cursor, anchor stays fixed).
        match dir {
            ShiftDir::WordFwd => self.active_editor_mut().execute_motion(Motion::WordFwd, 1),
            ShiftDir::WordBack => self.active_editor_mut().execute_motion(Motion::WordBack, 1),
            _ => unreachable!(),
        }
        // Collapse if cursor == anchor (empty selection).
        let anchor = self.active_editor().visual_anchor();
        let cursor = self.active_editor().cursor();
        if cursor == anchor {
            self.active_editor_mut().exit_visual_to_normal();
            self.active_editor_mut().enter_insert_i(1);
        }
    }

    /// Ctrl+Delete: delete from the caret to the start of the next word.
    fn vscode_delete_word_fwd(&mut self) {
        // Snapshot caret before motion.
        let (row, col) = self.active_editor().cursor();
        // Execute the word forward motion → cursor lands at next word start.
        self.active_editor_mut().execute_motion(Motion::WordFwd, 1);
        let (new_row, new_col) = self.active_editor().cursor();
        // Restore cursor to original position, then delete the range [old..new).
        self.active_editor_mut().set_cursor_doc(row, col);
        // Only delete if motion actually moved (prevents deleting on last word).
        if (new_row, new_col) != (row, col) {
            let start = Pos::new(row as u32, col as u32);
            let end = Pos::new(new_row as u32, new_col as u32);
            BufferEdit::delete_range(self.active_editor_mut().buffer_mut(), start..end);
            self.active_editor_mut().mark_content_dirty();
        }
    }

    /// Ctrl+X with no selection: cut the whole current line (including newline,
    /// unless it is the last line). Writes to the unnamed register and the system
    /// clipboard, then deletes the line from the buffer.
    fn vscode_cut_line(&mut self) {
        let (row, _col) = self.active_editor().cursor();
        let row_count = self.active_editor().row_count();
        // Get line text (no newline).
        let rope = self.active_editor().buffer().rope();
        let line_text = hjkl_buffer::rope_line_str(&rope, row);
        drop(rope);
        // The text to cut: if not last line, include the newline.
        let cut_text = if row + 1 < row_count {
            format!("{line_text}\n")
        } else {
            line_text.clone()
        };
        // Write to register + clipboard.
        self.active_editor_mut().set_yank(cut_text.clone());
        self.active_editor_mut()
            .host_mut()
            .write_clipboard(cut_text);
        // Delete the line including its newline (or just the text for last line).
        if row + 1 < row_count {
            let start = Pos::new(row as u32, 0);
            let end = Pos::new((row + 1) as u32, 0);
            // Ensure insert mode before deletion.
            if self.active_editor().vim_mode() != VimMode::Insert {
                self.active_editor_mut().enter_insert_i(1);
            }
            BufferEdit::delete_range(self.active_editor_mut().buffer_mut(), start..end);
        } else {
            // Last line: delete just the text content (no newline to delete).
            let line_len = self.active_editor().line_char_count(row);
            if line_len > 0 {
                let start = Pos::new(row as u32, 0);
                let end = Pos::new(row as u32, line_len as u32);
                if self.active_editor().vim_mode() != VimMode::Insert {
                    self.active_editor_mut().enter_insert_i(1);
                }
                BufferEdit::delete_range(self.active_editor_mut().buffer_mut(), start..end);
            }
        }
        // Clamp cursor to new line start.
        let new_row_count = self.active_editor().row_count();
        let new_row = row.min(new_row_count.saturating_sub(1));
        self.active_editor_mut().set_cursor_doc(new_row, 0);
        self.active_editor_mut().mark_content_dirty();
    }
}

/// Direction for a Shift+arrow move (begins or extends a selection).
#[derive(Debug, Clone, Copy)]
enum ShiftDir {
    Left,
    Right,
    Up,
    Down,
    Home,
    End,
    WordFwd,
    WordBack,
}