Skip to main content

iced_code_editor/canvas_editor/features/vim/
mod.rs

1//! Vim emulation for the canvas editor.
2//!
3//! This module parses key sequences into motions, operators, and actions,
4//! and tracks the modal state (normal/insert/visual/visual-line) needed to
5//! reproduce Vim-style editing behavior.
6
7mod update;
8
9/// The active editing mode when Vim behavior is enabled.
10#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
11pub enum VimMode {
12    /// Command-oriented navigation and editing mode.
13    #[default]
14    Normal,
15    /// Text insertion mode.
16    Insert,
17    /// Character-wise visual selection mode.
18    Visual,
19    /// Line-wise visual selection mode.
20    VisualLine,
21}
22
23/// A cursor motion recognized by the Vim parser.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub(crate) enum VimMotion {
26    /// Move left one character (`h`).
27    Left,
28    /// Move down one visible line (`j`).
29    Down,
30    /// Move up one visible line (`k`).
31    Up,
32    /// Move right one character (`l`).
33    Right,
34    /// Move to the start of the next word (`w`).
35    WordForward,
36    /// Move to the start of the previous word (`b`).
37    WordBackward,
38    /// Move to the end of the current/next word (`e`).
39    WordEnd,
40    /// Move to column 0 of the current line (`0`).
41    LineStart,
42    /// Move to the first non-blank character of the line (`^`).
43    FirstNonBlank,
44    /// Move to the last character of the line (`$`).
45    LineEnd,
46    /// Move to line `count` (1-based), or line 1 if no count is given (`gg`).
47    DocumentStart,
48    /// Move to line `count` (1-based) if a count is explicitly given,
49    /// otherwise the last line (`G`).
50    DocumentEnd,
51}
52
53/// An operator waiting for, or combined with, a motion.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub(crate) enum VimOperator {
56    /// Delete the targeted range (`d`).
57    Delete,
58    /// Delete the targeted range and enter Insert mode (`c`).
59    Change,
60    /// Yank (copy) the targeted range into the unnamed register (`y`).
61    Yank,
62}
63
64/// The insertion position requested by a Normal-mode command.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub(crate) enum VimInsertPosition {
67    /// Enter Insert mode before the cursor (`i`).
68    BeforeCursor,
69    /// Enter Insert mode after the cursor (`a`).
70    AfterCursor,
71    /// Enter Insert mode at the first non-blank character of the line (`I`).
72    FirstNonBlank,
73    /// Enter Insert mode at the end of the line (`A`).
74    EndOfLine,
75    /// Open a new line below the current one and enter Insert mode (`o`).
76    NewLineBelow,
77    /// Open a new line above the current one and enter Insert mode (`O`).
78    NewLineAbove,
79}
80
81/// The side of the cursor on which a paste should occur.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub(crate) enum VimPastePosition {
84    /// Paste after the cursor (`p`).
85    AfterCursor,
86    /// Paste before the cursor (`P`).
87    BeforeCursor,
88}
89
90/// A complete, buffer-independent intent emitted by [`VimState`].
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub(crate) enum VimAction {
93    /// Switch to a different Vim mode.
94    Mode(VimMode),
95    /// Move the cursor by a motion, repeated `count` times. `explicit_count`
96    /// distinguishes an explicitly typed count (e.g. `1G`) from the default
97    /// of 1 (e.g. bare `G`), since some motions (`G`) behave differently in
98    /// each case.
99    Motion { motion: VimMotion, count: usize, explicit_count: bool },
100    /// Enter Insert mode at the given position, repeating the eventual
101    /// inserted text `count` times on exit.
102    Insert { position: VimInsertPosition, count: usize },
103    /// Apply an operator to the range covered by a motion, repeated `count`
104    /// times. See [`VimAction::Motion`] for the meaning of `explicit_count`.
105    Operator {
106        operator: VimOperator,
107        motion: VimMotion,
108        count: usize,
109        explicit_count: bool,
110    },
111    /// Apply an operator to `count` whole lines (e.g. `dd`, `yy`, `cc`).
112    LineOperator { operator: VimOperator, count: usize },
113    /// Apply an operator to the active Visual/Visual Line selection.
114    VisualOperator(VimOperator),
115    /// Delete `count` characters under and after the cursor (`x`).
116    DeleteCharacters { count: usize },
117    /// Paste the unnamed register `count` times at the given position.
118    Paste { position: VimPastePosition, count: usize },
119    /// Undo the last `count` grouped commands (`u`).
120    Undo { count: usize },
121    /// Redo the last `count` undone commands (`Ctrl+R`).
122    Redo { count: usize },
123    /// Repeat the last `/` search, optionally reversing its direction
124    /// (`n`/`N`).
125    RepeatSearch { reverse: bool },
126    /// The pending `/` or `:` command-line input changed.
127    CommandLineChanged,
128    /// A `/` search was submitted with the given pattern.
129    SubmitSearch(String),
130    /// A `:N` command was submitted, requesting a jump to the given
131    /// 1-based line.
132    SubmitGotoLine(usize),
133    /// A `:w` or `:wq` command was submitted, requesting a host save and
134    /// optionally exiting Vim mode.
135    WriteFile { exit_vim: bool },
136    /// A `:q` command was submitted, requesting Vim mode be turned off.
137    ExitVimMode,
138}
139
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141enum VimCommandLineKind {
142    Search,
143    Command,
144}
145
146#[derive(Debug, Clone, PartialEq, Eq)]
147struct VimCommandLine {
148    kind: VimCommandLineKind,
149    input: String,
150}
151
152/// Whether register text represents a character range or complete lines.
153#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
154pub(crate) enum VimRegisterKind {
155    #[default]
156    Characterwise,
157    Linewise,
158}
159
160/// The per-editor unnamed Vim register.
161#[derive(Debug, Default, Clone, PartialEq, Eq)]
162pub(crate) struct VimRegister {
163    pub(crate) text: String,
164    pub(crate) kind: VimRegisterKind,
165}
166
167/// Pure Vim parsing state owned by one editor instance.
168#[derive(Debug, Default)]
169pub(crate) struct VimState {
170    mode: VimMode,
171    count: Option<usize>,
172    g_prefix: bool,
173    pending_operator: Option<VimOperator>,
174    pending_operator_count: usize,
175    visual_anchor: Option<(usize, usize)>,
176    visual_active: Option<(usize, usize)>,
177    command_line: Option<VimCommandLine>,
178    last_search: Option<String>,
179    pub(crate) register: VimRegister,
180}
181
182impl VimState {
183    pub(crate) fn mode(&self) -> VimMode {
184        self.mode
185    }
186
187    pub(crate) fn reset(&mut self) {
188        *self = Self::default();
189    }
190
191    pub(crate) fn enter_clean_normal_mode(&mut self) {
192        self.mode = VimMode::Normal;
193        self.clear_visual();
194        self.command_line = None;
195        self.clear_pending();
196    }
197
198    pub(crate) fn command_line_active(&self) -> bool {
199        self.command_line.is_some()
200    }
201
202    pub(crate) fn last_search(&self) -> Option<&str> {
203        self.last_search.as_deref()
204    }
205
206    pub(crate) fn command_line_text(&self) -> Option<String> {
207        self.command_line.as_ref().map(|command_line| {
208            let prefix = match command_line.kind {
209                VimCommandLineKind::Search => '/',
210                VimCommandLineKind::Command => ':',
211            };
212            format!("{prefix}{}", command_line.input)
213        })
214    }
215
216    pub(crate) fn pending_keys(&self) -> String {
217        let mut pending = String::new();
218        if let Some(operator) = self.pending_operator {
219            if self.pending_operator_count > 1 {
220                pending.push_str(&self.pending_operator_count.to_string());
221            }
222            pending.push(match operator {
223                VimOperator::Delete => 'd',
224                VimOperator::Change => 'c',
225                VimOperator::Yank => 'y',
226            });
227            if let Some(count) = self.count {
228                pending.push_str(&count.to_string());
229            }
230        } else if let Some(count) = self.count {
231            pending.push_str(&count.to_string());
232        }
233        if self.g_prefix {
234            pending.push('g');
235        }
236        pending
237    }
238
239    pub(crate) fn status_line_text(&self) -> (String, String) {
240        if let Some(command_line) = self.command_line_text() {
241            return (command_line, String::new());
242        }
243
244        let mode = match self.mode {
245            VimMode::Normal => "NORMAL",
246            VimMode::Insert => "INSERT",
247            VimMode::Visual => "VISUAL",
248            VimMode::VisualLine => "VISUAL LINE",
249        };
250
251        (format!("-- {mode} --"), self.pending_keys())
252    }
253
254    pub(crate) fn begin_visual(&mut self, position: (usize, usize)) {
255        self.visual_anchor = Some(position);
256        self.visual_active = Some(position);
257    }
258
259    pub(crate) fn visual_positions(
260        &self,
261    ) -> Option<((usize, usize), (usize, usize))> {
262        Some((self.visual_anchor?, self.visual_active?))
263    }
264
265    pub(crate) fn set_visual_active(&mut self, position: (usize, usize)) {
266        self.visual_active = Some(position);
267    }
268
269    pub(crate) fn clear_visual(&mut self) {
270        self.visual_anchor = None;
271        self.visual_active = None;
272    }
273
274    pub(crate) fn set_mode_from_mouse(&mut self, mode: VimMode) {
275        self.mode = mode;
276        self.clear_pending();
277    }
278
279    pub(crate) fn enter_insert_mode(&mut self) {
280        self.mode = VimMode::Insert;
281        self.clear_visual();
282        self.command_line = None;
283        self.clear_pending();
284    }
285
286    pub(crate) fn parse_key(&mut self, key: char) -> Option<VimAction> {
287        if self.command_line.is_some() {
288            return self.parse_command_line_key(key);
289        }
290
291        if self.mode == VimMode::Insert {
292            return if key == '\u{1b}' {
293                Some(self.set_mode(VimMode::Normal))
294            } else {
295                None
296            };
297        }
298
299        if key == '\u{1b}' {
300            return Some(self.set_mode(VimMode::Normal));
301        }
302
303        if key.is_ascii_digit() && (key != '0' || self.count.is_some()) {
304            self.push_count_digit(key);
305            return None;
306        }
307
308        if self.g_prefix {
309            if key == 'g' {
310                self.g_prefix = false;
311                return Some(self.finish_motion(VimMotion::DocumentStart));
312            }
313            self.clear_pending();
314            return None;
315        }
316
317        if key == 'g' {
318            self.g_prefix = true;
319            return None;
320        }
321
322        if let Some(operator) = operator_for_key(key) {
323            return self.parse_operator(operator);
324        }
325
326        if let Some(motion) = motion_for_key(key) {
327            return Some(self.finish_motion(motion));
328        }
329
330        let action = match key {
331            'i' => Some(self.insert(VimInsertPosition::BeforeCursor)),
332            'a' => Some(self.insert(VimInsertPosition::AfterCursor)),
333            'I' => Some(self.insert(VimInsertPosition::FirstNonBlank)),
334            'A' => Some(self.insert(VimInsertPosition::EndOfLine)),
335            'o' => Some(self.insert(VimInsertPosition::NewLineBelow)),
336            'O' => Some(self.insert(VimInsertPosition::NewLineAbove)),
337            'v' => Some(self.set_mode(VimMode::Visual)),
338            'V' => Some(self.set_mode(VimMode::VisualLine)),
339            'x' => {
340                Some(VimAction::DeleteCharacters { count: self.take_count() })
341            }
342            'p' => Some(VimAction::Paste {
343                position: VimPastePosition::AfterCursor,
344                count: self.take_count(),
345            }),
346            'P' => Some(VimAction::Paste {
347                position: VimPastePosition::BeforeCursor,
348                count: self.take_count(),
349            }),
350            'u' => Some(VimAction::Undo { count: self.take_count() }),
351            '\u{12}' => Some(VimAction::Redo { count: self.take_count() }),
352            'n' => Some(VimAction::RepeatSearch { reverse: false }),
353            'N' => Some(VimAction::RepeatSearch { reverse: true }),
354            '/' => Some(self.open_command_line(VimCommandLineKind::Search)),
355            ':' => Some(self.open_command_line(VimCommandLineKind::Command)),
356            _ => None,
357        };
358
359        if action.is_none() {
360            self.clear_pending();
361        }
362        action
363    }
364
365    fn open_command_line(&mut self, kind: VimCommandLineKind) -> VimAction {
366        self.clear_pending();
367        self.command_line = Some(VimCommandLine { kind, input: String::new() });
368        VimAction::CommandLineChanged
369    }
370
371    fn parse_command_line_key(&mut self, key: char) -> Option<VimAction> {
372        match key {
373            '\u{1b}' => {
374                self.command_line = None;
375                Some(VimAction::CommandLineChanged)
376            }
377            '\u{8}' => {
378                if let Some(command_line) = self.command_line.as_mut()
379                    && command_line.input.pop().is_none()
380                {
381                    self.command_line = None;
382                }
383                Some(VimAction::CommandLineChanged)
384            }
385            '\n' | '\r' => {
386                let command_line = self.command_line.take()?;
387                if command_line.input.is_empty() {
388                    return Some(VimAction::CommandLineChanged);
389                }
390                match command_line.kind {
391                    VimCommandLineKind::Search => {
392                        self.last_search = Some(command_line.input.clone());
393                        Some(VimAction::SubmitSearch(command_line.input))
394                    }
395                    VimCommandLineKind::Command => {
396                        match command_line.input.as_str() {
397                            "q" => Some(VimAction::ExitVimMode),
398                            "w" => {
399                                Some(VimAction::WriteFile { exit_vim: false })
400                            }
401                            "wq" => {
402                                Some(VimAction::WriteFile { exit_vim: true })
403                            }
404                            _ => command_line
405                                .input
406                                .parse::<usize>()
407                                .ok()
408                                .filter(|line| *line > 0)
409                                .map(VimAction::SubmitGotoLine)
410                                .or(Some(VimAction::CommandLineChanged)),
411                        }
412                    }
413                }
414            }
415            key if !key.is_control() => {
416                if let Some(command_line) = self.command_line.as_mut() {
417                    command_line.input.push(key);
418                }
419                Some(VimAction::CommandLineChanged)
420            }
421            _ => None,
422        }
423    }
424
425    fn set_mode(&mut self, mode: VimMode) -> VimAction {
426        self.mode = mode;
427        self.clear_pending();
428        VimAction::Mode(mode)
429    }
430
431    fn insert(&mut self, position: VimInsertPosition) -> VimAction {
432        let count = self.take_count();
433        self.mode = VimMode::Insert;
434        self.clear_pending();
435        VimAction::Insert { position, count }
436    }
437
438    fn parse_operator(&mut self, operator: VimOperator) -> Option<VimAction> {
439        if self.mode != VimMode::Normal {
440            self.clear_pending();
441            return Some(VimAction::VisualOperator(operator));
442        }
443
444        if let Some(pending) = self.pending_operator {
445            if pending == operator {
446                let count = self
447                    .pending_operator_count
448                    .saturating_mul(self.take_count());
449                self.clear_pending();
450                return Some(VimAction::LineOperator { operator, count });
451            }
452            self.clear_pending();
453            return None;
454        }
455
456        self.pending_operator_count = self.take_count();
457        self.pending_operator = Some(operator);
458        None
459    }
460
461    fn finish_motion(&mut self, motion: VimMotion) -> VimAction {
462        let motion_count_explicit = self.count.is_some();
463        let motion_count = self.take_count();
464        if let Some(operator) = self.pending_operator {
465            let count =
466                self.pending_operator_count.saturating_mul(motion_count);
467            // The operator's own count slot doesn't track whether it was
468            // explicitly typed, so `1dG` vs `dG` stays ambiguous; this
469            // approximates "explicit" for the combined count.
470            let explicit_count =
471                motion_count_explicit || self.pending_operator_count > 1;
472            self.clear_pending();
473            VimAction::Operator { operator, motion, count, explicit_count }
474        } else {
475            self.g_prefix = false;
476            VimAction::Motion {
477                motion,
478                count: motion_count,
479                explicit_count: motion_count_explicit,
480            }
481        }
482    }
483
484    fn push_count_digit(&mut self, key: char) {
485        let digit = key.to_digit(10).unwrap_or_default() as usize;
486        self.count = Some(
487            self.count
488                .unwrap_or_default()
489                .saturating_mul(10)
490                .saturating_add(digit),
491        );
492    }
493
494    fn take_count(&mut self) -> usize {
495        self.count.take().unwrap_or(1).max(1)
496    }
497
498    fn clear_pending(&mut self) {
499        self.count = None;
500        self.g_prefix = false;
501        self.pending_operator = None;
502        self.pending_operator_count = 1;
503    }
504}
505
506fn motion_for_key(key: char) -> Option<VimMotion> {
507    match key {
508        'h' => Some(VimMotion::Left),
509        'j' => Some(VimMotion::Down),
510        'k' => Some(VimMotion::Up),
511        'l' => Some(VimMotion::Right),
512        'w' => Some(VimMotion::WordForward),
513        'b' => Some(VimMotion::WordBackward),
514        'e' => Some(VimMotion::WordEnd),
515        '0' => Some(VimMotion::LineStart),
516        '^' => Some(VimMotion::FirstNonBlank),
517        '$' => Some(VimMotion::LineEnd),
518        'G' => Some(VimMotion::DocumentEnd),
519        _ => None,
520    }
521}
522
523fn operator_for_key(key: char) -> Option<VimOperator> {
524    match key {
525        'd' => Some(VimOperator::Delete),
526        'c' => Some(VimOperator::Change),
527        'y' => Some(VimOperator::Yank),
528        _ => None,
529    }
530}
531
532#[cfg(test)]
533mod tests {
534    use super::{
535        VimAction, VimMotion, VimOperator, VimRegister, VimRegisterKind,
536        VimState,
537    };
538
539    #[test]
540    fn vim_parser_accumulates_count_and_operator() {
541        let mut state = VimState::default();
542
543        assert_eq!(state.parse_key('2'), None);
544        assert_eq!(state.parse_key('d'), None);
545        assert_eq!(state.parse_key('3'), None);
546        assert_eq!(
547            state.parse_key('w'),
548            Some(VimAction::Operator {
549                operator: VimOperator::Delete,
550                motion: VimMotion::WordForward,
551                count: 6,
552                explicit_count: true,
553            })
554        );
555    }
556
557    #[test]
558    fn vim_parser_zero_is_motion_without_leading_count() {
559        let mut state = VimState::default();
560
561        assert_eq!(
562            state.parse_key('0'),
563            Some(VimAction::Motion {
564                motion: VimMotion::LineStart,
565                count: 1,
566                explicit_count: false,
567            })
568        );
569
570        assert_eq!(state.parse_key('1'), None);
571        assert_eq!(state.parse_key('0'), None);
572        assert_eq!(
573            state.parse_key('l'),
574            Some(VimAction::Motion {
575                motion: VimMotion::Right,
576                count: 10,
577                explicit_count: true,
578            })
579        );
580    }
581
582    #[test]
583    fn vim_parser_distinguishes_explicit_count_for_document_end() {
584        let mut state = VimState::default();
585
586        assert_eq!(
587            state.parse_key('G'),
588            Some(VimAction::Motion {
589                motion: VimMotion::DocumentEnd,
590                count: 1,
591                explicit_count: false,
592            })
593        );
594
595        assert_eq!(state.parse_key('1'), None);
596        assert_eq!(
597            state.parse_key('G'),
598            Some(VimAction::Motion {
599                motion: VimMotion::DocumentEnd,
600                count: 1,
601                explicit_count: true,
602            })
603        );
604    }
605
606    #[test]
607    fn vim_state_resets_typed_unnamed_register() {
608        let mut state = VimState {
609            register: VimRegister {
610                text: "line\n".to_owned(),
611                kind: VimRegisterKind::Linewise,
612            },
613            ..VimState::default()
614        };
615
616        assert_eq!(state.register.text, "line\n");
617        assert_eq!(state.register.kind, VimRegisterKind::Linewise);
618
619        state.reset();
620
621        assert!(state.register.text.is_empty());
622        assert_eq!(state.register.kind, VimRegisterKind::Characterwise);
623    }
624
625    #[test]
626    fn vim_command_line_parser_accepts_edit_submit_and_cancel() {
627        let mut state = VimState::default();
628
629        assert_eq!(state.parse_key('/'), Some(VimAction::CommandLineChanged));
630        assert_eq!(state.command_line_text().as_deref(), Some("/"));
631
632        for key in "foo".chars() {
633            assert_eq!(
634                state.parse_key(key),
635                Some(VimAction::CommandLineChanged)
636            );
637        }
638        assert_eq!(state.command_line_text().as_deref(), Some("/foo"));
639
640        assert_eq!(
641            state.parse_key('\u{8}'),
642            Some(VimAction::CommandLineChanged)
643        );
644        assert_eq!(state.command_line_text().as_deref(), Some("/fo"));
645        assert_eq!(
646            state.parse_key('\n'),
647            Some(VimAction::SubmitSearch("fo".to_owned()))
648        );
649        assert_eq!(state.command_line_text(), None);
650
651        assert_eq!(state.parse_key(':'), Some(VimAction::CommandLineChanged));
652        for key in "12".chars() {
653            let _ = state.parse_key(key);
654        }
655        assert_eq!(state.parse_key('\n'), Some(VimAction::SubmitGotoLine(12)));
656
657        let _ = state.parse_key(':');
658        let _ = state.parse_key('q');
659        assert_eq!(state.parse_key('\n'), Some(VimAction::ExitVimMode));
660
661        let _ = state.parse_key(':');
662        let _ = state.parse_key('w');
663        assert_eq!(
664            state.parse_key('\n'),
665            Some(VimAction::WriteFile { exit_vim: false })
666        );
667
668        let _ = state.parse_key(':');
669        let _ = state.parse_key('w');
670        let _ = state.parse_key('q');
671        assert_eq!(
672            state.parse_key('\n'),
673            Some(VimAction::WriteFile { exit_vim: true })
674        );
675
676        let _ = state.parse_key('/');
677        let _ = state.parse_key('x');
678        assert_eq!(
679            state.parse_key('\u{1b}'),
680            Some(VimAction::CommandLineChanged)
681        );
682        assert_eq!(state.command_line_text(), None);
683    }
684
685    #[test]
686    fn vim_pending_keys_formats_counts_prefixes_and_operators() {
687        let mut state = VimState::default();
688
689        assert_eq!(state.parse_key('5'), None);
690        assert_eq!(state.pending_keys(), "5");
691        assert_eq!(state.parse_key('d'), None);
692        assert_eq!(state.pending_keys(), "5d");
693        assert_eq!(state.parse_key('2'), None);
694        assert_eq!(state.pending_keys(), "5d2");
695
696        state.enter_clean_normal_mode();
697        assert_eq!(state.parse_key('3'), None);
698        assert_eq!(state.parse_key('g'), None);
699        assert_eq!(state.pending_keys(), "3g");
700    }
701
702    #[test]
703    fn vim_status_line_formats_mode_command_and_pending_input() {
704        let mut state = VimState::default();
705        assert_eq!(
706            state.status_line_text(),
707            ("-- NORMAL --".to_owned(), String::new())
708        );
709
710        let _ = state.parse_key('i');
711        assert_eq!(
712            state.status_line_text(),
713            ("-- INSERT --".to_owned(), String::new())
714        );
715        let _ = state.parse_key('\u{1b}');
716
717        let _ = state.parse_key('5');
718        let _ = state.parse_key('d');
719        assert_eq!(
720            state.status_line_text(),
721            ("-- NORMAL --".to_owned(), "5d".to_owned())
722        );
723
724        state.enter_clean_normal_mode();
725        let _ = state.parse_key('/');
726        let _ = state.parse_key('f');
727        let _ = state.parse_key('o');
728        let _ = state.parse_key('o');
729        assert_eq!(
730            state.status_line_text(),
731            ("/foo".to_owned(), String::new())
732        );
733
734        let _ = state.parse_key('\u{1b}');
735        let _ = state.parse_key('v');
736        assert_eq!(
737            state.status_line_text(),
738            ("-- VISUAL --".to_owned(), String::new())
739        );
740
741        let _ = state.parse_key('V');
742        assert_eq!(
743            state.status_line_text(),
744            ("-- VISUAL LINE --".to_owned(), String::new())
745        );
746    }
747}