vorto 0.15.3

A Vim-flavored modal terminal editor with batteries included: tree-sitter, LSP, fuzzy pickers, vim-surround, multi-cursor, and optional Copilot.
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
//! Visual-mode key handling: motion application, operator dispatch
//! (`y`/`d`/`c`/`~`/`J`), and the `g` two-key prefix that mirrors
//! Normal mode.

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

use crate::action::{LastFind, MotionKind, Operator};
use crate::app::eval::handle::resolve_motion_pure;
use crate::app::{App, Selection, Toast};
use crate::editor::Cursor;
use crate::mode::Mode;

impl App {
    pub(super) fn handle_visual_key(&mut self, key: KeyEvent) -> Result<()> {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);

        // `f`/`F`/`t`/`T` left us waiting for the literal target char.
        // The very next key is that char (any other key — Esc included —
        // just cancels). A pending count multiplies the find.
        if let Some((forward, till)) = self.visual_find_pending.take() {
            let count = self.take_visual_count();
            if let KeyCode::Char(ch) = key.code {
                self.last_find = Some(LastFind { ch, forward, till });
                self.apply_visual_motion(MotionKind::FindChar { ch, forward, till }, count);
            }
            return Ok(());
        }

        // `g` is a two-key prefix in visual just like in normal — but
        // visual bypasses the token pipeline, so the one bit of state
        // we need lives on App as `visual_g_pending`. A pending count
        // (e.g. the `5` in `5gg`) survives until the follower lands.
        if std::mem::take(&mut self.visual_g_pending) {
            let had_count = self.visual_count.is_some();
            let count = self.take_visual_count();
            match key.code {
                // bare `gg` → file start; any typed count is a line jump
                // (`5gg` → line 5, `1gg` → line 1), matching vim.
                KeyCode::Char('g') => {
                    if had_count {
                        self.goto_line_n_pure(count as usize);
                    } else {
                        self.editor.move_file_start();
                    }
                }
                KeyCode::Char('e') => self.apply_visual_motion(MotionKind::WordEndBack, count),
                KeyCode::Char('E') => self.apply_visual_motion(MotionKind::BigWordEndBack, count),
                KeyCode::Char('_') => self.apply_visual_motion(MotionKind::LineLastNonBlank, count),
                // gs/gl/gc/gb — same aliases as Normal mode.
                KeyCode::Char('s') => {
                    self.apply_visual_motion(MotionKind::LineFirstNonBlank, count)
                }
                KeyCode::Char('l') => self.apply_visual_motion(MotionKind::LineEnd, count),
                KeyCode::Char('c') => self.apply_visual_motion(MotionKind::ViewportMiddle, count),
                KeyCode::Char('b') => self.apply_visual_motion(MotionKind::ViewportBottom, count),
                // `gn` / `gN` — extend the selection to cover the next
                // (or previous) search match. Anchor stays put; the
                // shared helper just walks the active end out to the
                // match's last char.
                KeyCode::Char('n') => self.run_search_select(self.search.last_forward),
                KeyCode::Char('N') => self.run_search_select(!self.search.last_forward),
                _ => {}
            }
            return Ok(());
        }

        // Digits build up a count (`5j`, `10G`, `3fx`). A bare `0` with
        // no count pending is the line-start motion, not a digit — so it
        // falls through to the match below.
        if let KeyCode::Char(c @ '0'..='9') = key.code
            && !ctrl
            && !(c == '0' && self.visual_count.is_none())
        {
            let digit = c as u32 - '0' as u32;
            let next = self
                .visual_count
                .unwrap_or(0)
                .saturating_mul(10)
                .saturating_add(digit);
            self.visual_count = Some(next);
            return Ok(());
        }

        // Prefix keys that need the next keystroke. They must return
        // *before* the count is consumed so `5gg` / `3fx` see it.
        match key.code {
            KeyCode::Char('g') => {
                self.visual_g_pending = true;
                return Ok(());
            }
            KeyCode::Char('f') if !ctrl => {
                self.visual_find_pending = Some((true, false));
                return Ok(());
            }
            KeyCode::Char('F') => {
                self.visual_find_pending = Some((false, false));
                return Ok(());
            }
            KeyCode::Char('t') => {
                self.visual_find_pending = Some((true, true));
                return Ok(());
            }
            KeyCode::Char('T') => {
                self.visual_find_pending = Some((false, true));
                return Ok(());
            }
            _ => {}
        }

        // Pure-motion keys that map straight onto `MotionKind` and
        // can use the shared `motion_target` path. Selection follows
        // automatically because the anchor stays fixed.
        if let Some(motion) = visual_motion_for(key) {
            let count = self.take_visual_count();
            self.apply_visual_motion(motion, count);
            return Ok(());
        }

        // Everything below consumes (and thus clears) any pending count.
        let had_count = self.visual_count.is_some();
        let count = self.take_visual_count();
        match key.code {
            KeyCode::Esc => self.enter_mode(Mode::Normal),
            KeyCode::Char('h') | KeyCode::Left => {
                for _ in 0..count {
                    self.editor.move_left();
                }
            }
            KeyCode::Char('l') | KeyCode::Right => {
                for _ in 0..count {
                    ed_op_ref!(self, move_right(false));
                }
            }
            KeyCode::Char('j') | KeyCode::Down => {
                for _ in 0..count {
                    ed_op_ref!(self, move_down());
                }
            }
            KeyCode::Char('k') | KeyCode::Up => {
                for _ in 0..count {
                    ed_op_ref!(self, move_up());
                }
            }
            KeyCode::Char('0') | KeyCode::Home => self.editor.move_line_start(),
            // bare `G` → file end; any typed count is a line jump
            // (`20G` → line 20, `1G` → line 1), matching vim.
            KeyCode::Char('G') => {
                if had_count {
                    self.goto_line_n_pure(count as usize);
                } else {
                    ed_op_ref!(self, move_file_end());
                }
            }
            // `;` / `,` — repeat the last find-char, count times.
            KeyCode::Char(';') => self.repeat_visual_find(false, count),
            KeyCode::Char(',') => self.repeat_visual_find(true, count),
            // `n` / `N` — move the active end to the next / previous
            // search match (the anchor stays put, extending selection).
            KeyCode::Char('n') => {
                for _ in 0..count {
                    self.run_jump_search(self.search.last_forward);
                }
            }
            KeyCode::Char('N') => {
                for _ in 0..count {
                    self.run_jump_search(!self.search.last_forward);
                }
            }
            // `*` / `#` reuse the Normal-mode helper to seed search state.
            KeyCode::Char('*') => self.search_word_under_cursor(true),
            KeyCode::Char('#') => self.search_word_under_cursor(false),
            // `o` — swap the anchor and the cursor so the user can
            // extend the *other* end of the selection.
            KeyCode::Char('o') => self.swap_visual_endpoints(),
            // Toggle visual sub-modes: pressing the same trigger again
            // exits, a different one switches without losing the anchor.
            KeyCode::Char('v') if !ctrl => self.toggle_visual(Mode::Visual),
            KeyCode::Char('v') if ctrl => self.toggle_visual(Mode::VisualBlock),
            KeyCode::Char('V') => self.toggle_visual(Mode::VisualLine),
            KeyCode::Char('y') => {
                self.apply_visual_op(Operator::Yank);
                self.enter_mode(Mode::Normal);
            }
            KeyCode::Char('d') | KeyCode::Char('x') => {
                ed_op!(self, snapshot());
                self.apply_visual_op(Operator::Delete);
                self.enter_mode(Mode::Normal);
            }
            KeyCode::Char('c') | KeyCode::Char('s') => {
                ed_op!(self, snapshot());
                self.apply_visual_op(Operator::Change);
            }
            // `I` / `A` — enter Insert at the start / end of the selection.
            // Block mode fans out: one cursor per selected row so each
            // typed char repeats down the column.
            KeyCode::Char('I') => self.visual_insert_at_start(),
            KeyCode::Char('A') => self.visual_append_at_end(),
            // `S` / `R` — linewise change (force).
            KeyCode::Char('S') | KeyCode::Char('R') => self.visual_change_lines(),
            // `C` — linewise change everywhere except VisualBlock, where
            // it changes from c0 to EOL on each row (with fan-out).
            KeyCode::Char('C') => self.visual_change_to_eol(),
            // `D` — linewise delete everywhere except VisualBlock, where
            // it deletes from c0 to EOL on each row.
            KeyCode::Char('D') => self.visual_delete_to_eol(),
            // `X` — always linewise delete.
            KeyCode::Char('X') => self.visual_delete_lines(),
            // `Y` — always linewise yank.
            KeyCode::Char('Y') => self.visual_yank_lines(),
            // `u` / `U` — lowercase / uppercase the selection. Vim
            // semantics: bare `u` in visual is *not* undo, it lowercases.
            KeyCode::Char('u') => self.transform_case_selection(crate::editor::to_lower_keep_width),
            KeyCode::Char('U') => self.transform_case_selection(crate::editor::to_upper_keep_width),
            KeyCode::Char('~') => self.toggle_case_selection(),
            KeyCode::Char('J') => self.join_selection_lines(),
            KeyCode::Char('>') => self.indent_selection(true),
            KeyCode::Char('<') => self.indent_selection(false),
            // `:` — open the command prompt, keeping the selection alive
            // for `:agent <intent> @selection`.
            KeyCode::Char(':') => self.open_command_from_visual(),
            _ => {}
        }
        Ok(())
    }

    /// Resolve a motion `count` times against the current cursor and
    /// assign — the selection follows because the anchor is fixed.
    fn apply_visual_motion(&mut self, motion: MotionKind, count: u32) {
        let target = self
            .active_doc()
            .motion_target(self.editor.cursor, motion, count.max(1));
        self.editor.cursor = target;
    }

    /// Consume the pending Visual-mode count, defaulting to 1. Clears
    /// the accumulator so the next motion starts fresh.
    fn take_visual_count(&mut self) -> u32 {
        self.visual_count.take().unwrap_or(1).max(1)
    }

    /// `;` / `,` in visual — repeat the last find-char motion (`,`
    /// reverses direction), `count` times. No-op with a toast when
    /// there's no prior find, mirroring Normal mode.
    fn repeat_visual_find(&mut self, reverse: bool, count: u32) {
        let (resolved, _) = resolve_motion_pure(MotionKind::RepeatFind { reverse }, self.last_find);
        match resolved {
            Some(motion) => self.apply_visual_motion(motion, count),
            None => self.push_toast(Toast::error("no previous find")),
        }
    }

    fn swap_visual_endpoints(&mut self) {
        if let Some(anchor) = self.visual_anchor {
            let cur = self.editor.cursor;
            self.editor.cursor = anchor;
            self.visual_anchor = Some(cur);
        }
    }

    /// `~` in visual — toggle case across the entire selection.
    fn toggle_case_selection(&mut self) {
        self.transform_case_selection(crate::editor::flip_case_char_keep_width);
    }

    /// `u` / `U` / `~` in visual — apply a per-char transform across
    /// the selection. Charwise covers the span, linewise covers whole
    /// rows, block covers the rectangle. Exits visual when finished.
    fn transform_case_selection(&mut self, f: fn(char) -> char) {
        let Some(sel) = self.selection() else { return };
        ed_op!(self, snapshot());
        let doc = self.active_doc_mut();
        match sel {
            Selection::Char { from, to } => {
                let end = doc.advance_one(to);
                doc.transform_case_range(from, end, f);
            }
            Selection::Line { from_row, to_row } => {
                doc.transform_case_lines(from_row, to_row, f);
            }
            Selection::Block { r0, c0, r1, c1 } => {
                doc.transform_case_block(r0, c0, r1, c1, f);
            }
        }
        self.enter_mode(Mode::Normal);
    }

    /// `J` in visual: join every selected line (any flavour of visual)
    /// into the first one. Equivalent to repeating `J` `n-1` times
    /// after positioning the cursor at the top of the selection.
    fn join_selection_lines(&mut self) {
        let Some(sel) = self.selection() else { return };
        let (from_row, to_row) = match sel {
            Selection::Char { from, to } => (from.row, to.row),
            Selection::Line { from_row, to_row } => (from_row, to_row),
            Selection::Block { r0, r1, .. } => (r0, r1),
        };
        if from_row == to_row {
            return;
        }
        ed_op!(self, snapshot());
        self.editor.cursor.row = from_row;
        self.editor.cursor.col = 0;
        let doc_ref = self.editor.doc.clone();
        let doc = self
            .documents
            .get_mut(&doc_ref)
            .expect("active doc present");
        for _ in 0..(to_row - from_row) {
            self.editor.join_next_line(doc);
        }
        self.enter_mode(Mode::Normal);
    }

    /// `>` / `<` in visual — shift every line covered by the selection
    /// one indent level right (`indent = true`) or left. Always
    /// line-wise, regardless of the visual sub-mode. Exits to Normal
    /// with the cursor on the first non-blank of the top selected row,
    /// matching vim's landing position.
    fn indent_selection(&mut self, indent: bool) {
        let Some(sel) = self.selection() else { return };
        let (from_row, to_row) = match sel {
            Selection::Char { from, to } => (from.row, to.row),
            Selection::Line { from_row, to_row } => (from_row, to_row),
            Selection::Block { r0, r1, .. } => (r0, r1),
        };
        ed_op!(self, snapshot());
        let indent_settings = self.indent_settings();
        let doc_ref = self.editor.doc.clone();
        let doc = self
            .documents
            .get_mut(&doc_ref)
            .expect("active doc present");
        for r in from_row..=to_row {
            if indent {
                self.editor.indent_line(doc, r, indent_settings);
            } else {
                self.editor.dedent_line(doc, r, indent_settings);
            }
        }
        self.editor.cursor.row = from_row;
        let col = {
            let line = self.editor.current_line(doc);
            line.chars().position(|c| !c.is_whitespace()).unwrap_or(0)
        };
        self.editor.cursor.col = col;
        self.enter_mode(Mode::Normal);
    }

    /// `I` in visual: position the cursor at the start of the selection
    /// and enter Insert. Block mode adds one extra cursor per row so the
    /// inserted text mirrors down the left edge of the block.
    fn visual_insert_at_start(&mut self) {
        let Some(sel) = self.selection() else { return };
        ed_op!(self, snapshot());
        self.editor.extra_cursors.clear();
        match sel {
            Selection::Char { from, .. } => {
                self.editor.cursor = from;
            }
            Selection::Line { from_row, to_row } => {
                // Fan out: one cursor per row at each row's first
                // non-blank, so typed text replicates down the indent.
                self.editor.cursor = Cursor {
                    row: from_row,
                    col: first_non_blank(&self.active_doc().lines[from_row]),
                };
                for r in (from_row + 1)..=to_row {
                    self.editor.extra_cursors.push(Cursor {
                        row: r,
                        col: first_non_blank(&self.active_doc().lines[r]),
                    });
                }
            }
            Selection::Block { r0, c0, r1, .. } => {
                self.editor.cursor = Cursor { row: r0, col: c0 };
                for r in (r0 + 1)..=r1 {
                    let len = self.active_doc().lines[r].chars().count();
                    self.editor.extra_cursors.push(Cursor {
                        row: r,
                        col: c0.min(len),
                    });
                }
            }
        }
        self.enter_mode(Mode::Insert);
    }

    /// `A` in visual: position the cursor just past the end of the
    /// selection and enter Insert. Block mode mirrors the cursor onto
    /// each selected row at `c1 + 1` (clamped to that row's length).
    fn visual_append_at_end(&mut self) {
        let Some(sel) = self.selection() else { return };
        ed_op!(self, snapshot());
        self.editor.extra_cursors.clear();
        match sel {
            Selection::Char { to, .. } => {
                let len = self.active_doc().lines[to.row].chars().count();
                self.editor.cursor = Cursor {
                    row: to.row,
                    col: (to.col + 1).min(len),
                };
            }
            Selection::Line { from_row, to_row } => {
                // Fan out: each row's cursor lands at its own EOL.
                self.editor.cursor = Cursor {
                    row: from_row,
                    col: self.active_doc().lines[from_row].chars().count(),
                };
                for r in (from_row + 1)..=to_row {
                    self.editor.extra_cursors.push(Cursor {
                        row: r,
                        col: self.active_doc().lines[r].chars().count(),
                    });
                }
            }
            Selection::Block { r0, r1, c1, .. } => {
                let primary_len = self.active_doc().lines[r0].chars().count();
                self.editor.cursor = Cursor {
                    row: r0,
                    col: (c1 + 1).min(primary_len),
                };
                for r in (r0 + 1)..=r1 {
                    let len = self.active_doc().lines[r].chars().count();
                    self.editor.extra_cursors.push(Cursor {
                        row: r,
                        col: (c1 + 1).min(len),
                    });
                }
            }
        }
        self.enter_mode(Mode::Insert);
    }

    /// `S` / `R` / `C` (non-block) in visual — drop every covered row
    /// and enter Insert. Cursor lands at col 0 of the deleted region.
    fn visual_change_lines(&mut self) {
        let Some((from_row, to_row)) = self.selection_row_span() else {
            return;
        };
        ed_op!(self, snapshot());
        self.editor.extra_cursors.clear();
        ed_op!(self, delete_lines(from_row, to_row));
        self.editor.cursor.col = 0;
        self.enter_mode(Mode::Insert);
    }

    /// `C` in visual — linewise change everywhere except VisualBlock,
    /// where it changes from `c0` to EOL on each row and fans cursors
    /// out so the user's typed text replicates down the column.
    fn visual_change_to_eol(&mut self) {
        let Some(sel) = self.selection() else { return };
        match sel {
            Selection::Block { r0, c0, r1, .. } => {
                ed_op!(self, snapshot());
                self.editor.extra_cursors.clear();
                truncate_block_to_eol(self, r0, c0, r1);
                self.editor.cursor = Cursor { row: r0, col: c0 };
                for r in (r0 + 1)..=r1 {
                    let len = self.active_doc().lines[r].chars().count();
                    self.editor.extra_cursors.push(Cursor {
                        row: r,
                        col: c0.min(len),
                    });
                }
                self.enter_mode(Mode::Insert);
            }
            _ => self.visual_change_lines(),
        }
    }

    /// `D` in visual — linewise delete everywhere except VisualBlock,
    /// where it deletes from `c0` to EOL on each row. Exits to Normal.
    fn visual_delete_to_eol(&mut self) {
        let Some(sel) = self.selection() else { return };
        match sel {
            Selection::Block { r0, c0, r1, .. } => {
                ed_op!(self, snapshot());
                truncate_block_to_eol(self, r0, c0, r1);
                self.editor.cursor = Cursor { row: r0, col: c0 };
                ed_op_ref!(self, clamp_col(false));
                self.enter_mode(Mode::Normal);
            }
            _ => self.visual_delete_lines(),
        }
    }

    /// `X` (and `D` for non-block) — drop every covered row.
    fn visual_delete_lines(&mut self) {
        let Some((from_row, to_row)) = self.selection_row_span() else {
            return;
        };
        ed_op!(self, snapshot());
        ed_op!(self, delete_lines(from_row, to_row));
        self.enter_mode(Mode::Normal);
    }

    /// `Y` — always linewise yank.
    fn visual_yank_lines(&mut self) {
        let Some((from_row, to_row)) = self.selection_row_span() else {
            return;
        };
        self.active_doc_mut().yank_lines(from_row, to_row);
        self.sync_yank_to_clipboard();
        self.push_toast(Toast::info("yanked"));
        self.editor.cursor.row = from_row;
        self.editor.cursor.col = 0;
        self.enter_mode(Mode::Normal);
    }

    /// Common helper: rows covered by the current selection, regardless
    /// of its sub-mode flavour.
    fn selection_row_span(&self) -> Option<(usize, usize)> {
        Some(match self.selection()? {
            Selection::Char { from, to } => (from.row, to.row),
            Selection::Line { from_row, to_row } => (from_row, to_row),
            Selection::Block { r0, r1, .. } => (r0, r1),
        })
    }

    fn toggle_visual(&mut self, target: Mode) {
        if self.editor.mode == target {
            self.enter_mode(Mode::Normal);
        } else {
            // Switch sub-mode but keep the anchor — pressing `V` from
            // charwise visual should extend the selection line-wise.
            self.editor.mode = target;
        }
    }

    fn apply_visual_op(&mut self, op: Operator) {
        let Some(sel) = self.selection() else { return };
        match sel {
            Selection::Char { from, to } => {
                let end = self.active_doc().advance_one(to);
                match op {
                    Operator::Yank => {
                        self.active_doc_mut().yank_range(from, end);
                        self.sync_yank_to_clipboard();
                        self.push_toast(Toast::info("yanked"));
                        self.editor.cursor = from;
                    }
                    Operator::Delete => ed_op!(self, delete_range(from, end)),
                    Operator::Change => {
                        ed_op!(self, delete_range(from, end));
                        self.enter_mode(Mode::Insert);
                    }
                    Operator::Indent | Operator::Dedent => {
                        unreachable!("indent/dedent dispatched via indent_selection")
                    }
                    Operator::Comment => self.apply_visual_comment(from.row, end.row),
                    Operator::BlockComment => {
                        self.apply_visual_block_comment(from, end, from.row, end.row)
                    }
                }
            }
            Selection::Line { from_row, to_row } => match op {
                Operator::Yank => {
                    self.active_doc_mut().yank_lines(from_row, to_row);
                    self.sync_yank_to_clipboard();
                    self.push_toast(Toast::info("yanked"));
                    self.editor.cursor.row = from_row;
                    self.editor.cursor.col = 0;
                }
                Operator::Delete => ed_op!(self, delete_lines(from_row, to_row)),
                Operator::Change => {
                    ed_op!(self, delete_lines(from_row, to_row));
                    self.enter_mode(Mode::Insert);
                }
                Operator::Indent | Operator::Dedent => {
                    unreachable!("indent/dedent dispatched via indent_selection")
                }
                Operator::Comment => self.apply_visual_comment(from_row, to_row),
                Operator::BlockComment => {
                    // Line-visual wrap spans whole lines: col 0 of the
                    // first to end-of-last.
                    let (lo_row, hi_row) = (from_row.min(to_row), from_row.max(to_row));
                    let hi_col = self.active_doc().lines[hi_row].chars().count();
                    self.apply_visual_block_comment(
                        Cursor {
                            row: lo_row,
                            col: 0,
                        },
                        Cursor {
                            row: hi_row,
                            col: hi_col,
                        },
                        lo_row,
                        hi_row,
                    );
                }
            },
            Selection::Block { r0, c0, r1, c1 } => match op {
                Operator::Yank => {
                    self.active_doc_mut().yank_block(r0, c0, r1, c1);
                    self.sync_yank_to_clipboard();
                    self.push_toast(Toast::info("yanked"));
                    self.editor.cursor = Cursor { row: r0, col: c0 };
                }
                Operator::Delete => ed_op!(self, delete_block(r0, c0, r1, c1)),
                Operator::Change => {
                    // Fan-out: after the block delete, each row gets its
                    // own cursor at the left edge so typed text repeats
                    // down the column when Insert mode finishes.
                    self.editor.extra_cursors.clear();
                    ed_op!(self, delete_block(r0, c0, r1, c1));
                    self.editor.cursor = Cursor { row: r0, col: c0 };
                    for r in (r0 + 1)..=r1 {
                        let len = self.active_doc().lines[r].chars().count();
                        self.editor.extra_cursors.push(Cursor {
                            row: r,
                            col: c0.min(len),
                        });
                    }
                    self.enter_mode(Mode::Insert);
                }
                Operator::Indent | Operator::Dedent => {
                    unreachable!("indent/dedent dispatched via indent_selection")
                }
                // Visual-block + comment ops collapse to line-comment
                // over the touched rows. Wrapping a rectangle with
                // `/* … */` doesn't have a natural meaning, so we
                // intentionally don't honor BlockComment differently
                // here — both fall through to per-row line comment.
                Operator::Comment | Operator::BlockComment => self.apply_visual_comment(r0, r1),
            },
        }
    }

    fn apply_visual_comment(&mut self, row_a: usize, row_b: usize) {
        let (lo, hi) = (row_a.min(row_b), row_a.max(row_b));
        let rows: Vec<usize> = (lo..=hi).collect();
        if !self.apply_line_comment(&rows) {
            self.push_toast(Toast::error("no comment token for this buffer"));
        }
    }

    fn apply_visual_block_comment(&mut self, from: Cursor, to: Cursor, row_a: usize, row_b: usize) {
        let (lo, hi) = (row_a.min(row_b), row_a.max(row_b));
        let rows: Vec<usize> = (lo..=hi).collect();
        if !self.apply_block_comment(&rows, Some((from, to))) {
            self.push_toast(Toast::error(
                "no block- or line-comment tokens for this buffer",
            ));
        }
    }
}

fn first_non_blank(line: &str) -> usize {
    line.chars().position(|c| !c.is_whitespace()).unwrap_or(0)
}

/// `D`/`C` in VisualBlock — chop every row in `[r0..=r1]` so its
/// content stops at column `c0`. Implements the per-row right-side
/// truncation that `delete_block` doesn't cover (delete_block needs
/// a finite `c1`, and the longest row may not match the visual `c1`).
/// Cursor/yank are left to the caller.
fn truncate_block_to_eol(app: &mut App, r0: usize, c0: usize, r1: usize) {
    let r1 = r1.min(app.active_doc().lines.len().saturating_sub(1));
    let max_len = (r0..=r1)
        .map(|r| app.active_doc().lines[r].chars().count())
        .max()
        .unwrap_or(0);
    if max_len <= c0 {
        return;
    }
    // delete_block computes `hi = (c1 + 1).min(line_len)`, so passing
    // `max_len.saturating_sub(1)` covers every row to its own EOL.
    ed_op!(app, delete_block(r0, c0, r1, max_len.saturating_sub(1)));
}

/// Map a visual-mode key event to the motion it triggers, if any.
/// Returns `None` for keys that require special handling (operators,
/// prefixes, edits, mode toggles, etc.).
fn visual_motion_for(key: KeyEvent) -> Option<MotionKind> {
    use MotionKind as M;
    let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
    // Page motions (Ctrl-modified) need to be matched first so the
    // bare-letter cases below don't shadow them.
    if ctrl {
        return match key.code {
            KeyCode::Char('d') => Some(M::HalfPageDown),
            KeyCode::Char('u') => Some(M::HalfPageUp),
            KeyCode::Char('f') => Some(M::PageDown),
            KeyCode::Char('b') => Some(M::PageUp),
            _ => None,
        };
    }
    Some(match key.code {
        KeyCode::Char('w') => M::WordForward,
        KeyCode::Char('b') => M::WordBack,
        KeyCode::Char('e') => M::WordEnd,
        KeyCode::Char('W') => M::BigWordForward,
        KeyCode::Char('B') => M::BigWordBack,
        KeyCode::Char('E') => M::BigWordEnd,
        KeyCode::Char('^') => M::LineFirstNonBlank,
        KeyCode::Char('$') | KeyCode::End => M::LineEnd,
        KeyCode::Char('%') => M::BracketMatch,
        KeyCode::Char('H') => M::ViewportTop,
        KeyCode::Char('M') => M::ViewportMiddle,
        KeyCode::Char('L') => M::ViewportBottom,
        KeyCode::Char('{') => M::ParagraphBack,
        KeyCode::Char('}') => M::ParagraphForward,
        _ => return None,
    })
}

#[cfg(test)]
mod tests {
    use crate::app::App;
    use crate::editor::Cursor;
    use crate::mode::Mode;
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    /// Minimal `App` over a scratch buffer holding `src`. Mirrors the
    /// helper in `app::fold`'s tests — no grammar dirs, so nothing
    /// heavyweight attaches.
    fn app_with_lines(src: &[&str]) -> App {
        let config = crate::config::Config::load(None).expect("default config loads");
        let loader =
            crate::syntax::Loader::new(std::path::PathBuf::new(), std::path::PathBuf::new());
        let (tx, _rx) = std::sync::mpsc::channel();
        let cwd = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
        let mut app = App::new(config, loader, tx, cwd);
        app.active_doc_mut().lines = src.iter().map(|s| s.to_string()).collect();
        app
    }

    /// Drop the cursor at `(row, col)` and enter charwise Visual, which
    /// pins the anchor there.
    fn enter_visual_at(app: &mut App, row: usize, col: usize) {
        app.editor.cursor = Cursor { row, col };
        app.enter_mode(Mode::Visual);
    }

    fn press(app: &mut App, ch: char) {
        app.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE))
            .expect("key handled");
    }

    fn type_keys(app: &mut App, keys: &str) {
        for ch in keys.chars() {
            press(app, ch);
        }
    }

    #[test]
    fn count_repeats_vertical_motion() {
        let mut app = app_with_lines(&["a", "b", "c", "d", "e"]);
        enter_visual_at(&mut app, 0, 0);
        type_keys(&mut app, "3j");
        assert_eq!(app.editor.cursor.row, 3);
        // Anchor stays pinned so the selection spans the moved range.
        assert_eq!(app.visual_anchor, Some(Cursor { row: 0, col: 0 }));
    }

    #[test]
    fn count_with_g_prefix_jumps_to_line() {
        let mut app = app_with_lines(&["1", "2", "3", "4", "5", "6", "7"]);
        enter_visual_at(&mut app, 6, 0);
        type_keys(&mut app, "3gg");
        assert_eq!(app.editor.cursor.row, 2);
        // An explicit `1gg` is a line jump to line 1, not bare file-start.
        enter_visual_at(&mut app, 6, 0);
        type_keys(&mut app, "1gg");
        assert_eq!(app.editor.cursor.row, 0);
    }

    #[test]
    fn capital_g_with_count_jumps_else_file_end() {
        let mut app = app_with_lines(&["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"]);
        enter_visual_at(&mut app, 0, 0);
        type_keys(&mut app, "10G");
        assert_eq!(app.editor.cursor.row, 9);
        // Bare `G` (no count) still lands on the last line.
        press(&mut app, 'G');
        assert_eq!(app.editor.cursor.row, 10);
        // An explicit `1G` is a line jump to line 1 (vim), not file-end.
        type_keys(&mut app, "1G");
        assert_eq!(app.editor.cursor.row, 0);
    }

    #[test]
    fn find_char_and_repeat_with_count() {
        let mut app = app_with_lines(&["a.b.c.d"]);
        enter_visual_at(&mut app, 0, 0);
        press(&mut app, 'f');
        press(&mut app, '.');
        assert_eq!(app.editor.cursor.col, 1);
        // `;` repeats the last find.
        press(&mut app, ';');
        assert_eq!(app.editor.cursor.col, 3);
        // `,` repeats in reverse.
        press(&mut app, ',');
        assert_eq!(app.editor.cursor.col, 1);
    }

    #[test]
    fn count_applies_to_find_char() {
        let mut app = app_with_lines(&["a.b.c.d"]);
        enter_visual_at(&mut app, 0, 0);
        // dots sit at columns 1, 3, 5; `3f.` lands on the third.
        type_keys(&mut app, "3f.");
        assert_eq!(app.editor.cursor.col, 5);
    }

    #[test]
    fn bare_zero_is_line_start_not_a_count() {
        let mut app = app_with_lines(&["hello world"]);
        enter_visual_at(&mut app, 0, 6);
        press(&mut app, '0');
        assert_eq!(app.editor.cursor.col, 0);
    }

    #[test]
    fn n_and_capital_n_walk_search_matches() {
        let mut app = app_with_lines(&["foo", "bar", "foo", "baz", "foo"]);
        app.search.set("foo".into(), true);
        enter_visual_at(&mut app, 0, 0);
        press(&mut app, 'n');
        assert_eq!(app.editor.cursor.row, 2);
        press(&mut app, 'n');
        assert_eq!(app.editor.cursor.row, 4);
        // `N` reverses, anchor stays pinned at the origin.
        press(&mut app, 'N');
        assert_eq!(app.editor.cursor.row, 2);
        assert_eq!(app.visual_anchor, Some(Cursor { row: 0, col: 0 }));
    }
}