vim.rs

  1//! Vim support for Zed.
  2
  3#[cfg(test)]
  4mod test;
  5
  6mod command;
  7mod editor_events;
  8mod insert;
  9mod mode_indicator;
 10mod motion;
 11mod normal;
 12mod object;
 13mod state;
 14mod utils;
 15mod visual;
 16
 17use anyhow::Result;
 18use collections::HashMap;
 19use command_palette_hooks::{CommandPaletteFilter, CommandPaletteInterceptor};
 20use editor::{
 21    movement::{self, FindRange},
 22    Editor, EditorEvent, EditorMode,
 23};
 24use gpui::{
 25    actions, impl_actions, Action, AppContext, EntityId, Global, Subscription, View, ViewContext,
 26    WeakView, WindowContext,
 27};
 28use language::{CursorShape, Point, Selection, SelectionGoal};
 29pub use mode_indicator::ModeIndicator;
 30use motion::Motion;
 31use normal::normal_replace;
 32use schemars::JsonSchema;
 33use serde::Deserialize;
 34use serde_derive::Serialize;
 35use settings::{update_settings_file, Settings, SettingsStore};
 36use state::{EditorState, Mode, Operator, RecordedSelection, WorkspaceState};
 37use std::{ops::Range, sync::Arc};
 38use visual::{visual_block_motion, visual_replace};
 39use workspace::{self, Workspace};
 40
 41use crate::state::ReplayableAction;
 42
 43/// Whether or not to enable Vim mode (work in progress).
 44///
 45/// Default: false
 46pub struct VimModeSetting(pub bool);
 47
 48/// An Action to Switch between modes
 49#[derive(Clone, Deserialize, PartialEq)]
 50pub struct SwitchMode(pub Mode);
 51
 52/// PushOperator is used to put vim into a "minor" mode,
 53/// where it's waiting for a specific next set of keystrokes.
 54/// For example 'd' needs a motion to complete.
 55#[derive(Clone, Deserialize, PartialEq)]
 56pub struct PushOperator(pub Operator);
 57
 58/// Number is used to manage vim's count. Pushing a digit
 59/// multiplis the current value by 10 and adds the digit.
 60#[derive(Clone, Deserialize, PartialEq)]
 61struct Number(usize);
 62
 63actions!(
 64    vim,
 65    [Tab, Enter, Object, InnerObject, FindForward, FindBackward]
 66);
 67
 68// in the workspace namespace so it's not filtered out when vim is disabled.
 69actions!(workspace, [ToggleVimMode]);
 70
 71impl_actions!(vim, [SwitchMode, PushOperator, Number]);
 72
 73/// Initializes the `vim` crate.
 74pub fn init(cx: &mut AppContext) {
 75    cx.set_global(Vim::default());
 76    VimModeSetting::register(cx);
 77    VimSettings::register(cx);
 78
 79    editor_events::init(cx);
 80
 81    cx.observe_new_views(|workspace: &mut Workspace, cx| register(workspace, cx))
 82        .detach();
 83
 84    // Any time settings change, update vim mode to match. The Vim struct
 85    // will be initialized as disabled by default, so we filter its commands
 86    // out when starting up.
 87    cx.update_global::<CommandPaletteFilter, _>(|filter, _| {
 88        filter.hidden_namespaces.insert("vim");
 89    });
 90    cx.update_global(|vim: &mut Vim, cx: &mut AppContext| {
 91        vim.set_enabled(VimModeSetting::get_global(cx).0, cx)
 92    });
 93    cx.observe_global::<SettingsStore>(|cx| {
 94        cx.update_global(|vim: &mut Vim, cx: &mut AppContext| {
 95            vim.set_enabled(VimModeSetting::get_global(cx).0, cx)
 96        });
 97    })
 98    .detach();
 99}
100
101fn register(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
102    workspace.register_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {
103        Vim::update(cx, |vim, cx| vim.switch_mode(mode, false, cx))
104    });
105    workspace.register_action(
106        |_: &mut Workspace, &PushOperator(operator): &PushOperator, cx| {
107            Vim::update(cx, |vim, cx| vim.push_operator(operator, cx))
108        },
109    );
110    workspace.register_action(|_: &mut Workspace, n: &Number, cx: _| {
111        Vim::update(cx, |vim, cx| vim.push_count_digit(n.0, cx));
112    });
113
114    workspace.register_action(|_: &mut Workspace, _: &Tab, cx| {
115        Vim::active_editor_input_ignored(" ".into(), cx)
116    });
117
118    workspace.register_action(|_: &mut Workspace, _: &Enter, cx| {
119        Vim::active_editor_input_ignored("\n".into(), cx)
120    });
121
122    workspace.register_action(|workspace: &mut Workspace, _: &ToggleVimMode, cx| {
123        let fs = workspace.app_state().fs.clone();
124        let currently_enabled = VimModeSetting::get_global(cx).0;
125        update_settings_file::<VimModeSetting>(fs, cx, move |setting| {
126            *setting = Some(!currently_enabled)
127        })
128    });
129
130    normal::register(workspace, cx);
131    insert::register(workspace, cx);
132    motion::register(workspace, cx);
133    command::register(workspace, cx);
134    object::register(workspace, cx);
135    visual::register(workspace, cx);
136}
137
138/// Registers a keystroke observer to observe keystrokes for the Vim integration.
139pub fn observe_keystrokes(cx: &mut WindowContext) {
140    cx.observe_keystrokes(|keystroke_event, cx| {
141        if let Some(action) = keystroke_event
142            .action
143            .as_ref()
144            .map(|action| action.boxed_clone())
145        {
146            Vim::update(cx, |vim, _| {
147                if vim.workspace_state.recording {
148                    vim.workspace_state
149                        .recorded_actions
150                        .push(ReplayableAction::Action(action.boxed_clone()));
151
152                    if vim.workspace_state.stop_recording_after_next_action {
153                        vim.workspace_state.recording = false;
154                        vim.workspace_state.stop_recording_after_next_action = false;
155                    }
156                }
157            });
158
159            // Keystroke is handled by the vim system, so continue forward
160            if action.name().starts_with("vim::") {
161                return;
162            }
163        } else if cx.has_pending_keystrokes() {
164            return;
165        }
166
167        Vim::update(cx, |vim, cx| match vim.active_operator() {
168            Some(
169                Operator::FindForward { .. } | Operator::FindBackward { .. } | Operator::Replace,
170            ) => {}
171            Some(_) => {
172                vim.clear_operator(cx);
173            }
174            _ => {}
175        });
176    })
177    .detach()
178}
179
180/// The state pertaining to Vim mode.
181#[derive(Default)]
182struct Vim {
183    active_editor: Option<WeakView<Editor>>,
184    editor_subscription: Option<Subscription>,
185    enabled: bool,
186    editor_states: HashMap<EntityId, EditorState>,
187    workspace_state: WorkspaceState,
188    default_state: EditorState,
189}
190
191impl Global for Vim {}
192
193impl Vim {
194    fn read(cx: &mut AppContext) -> &Self {
195        cx.global::<Self>()
196    }
197
198    fn update<F, S>(cx: &mut WindowContext, update: F) -> S
199    where
200        F: FnOnce(&mut Self, &mut WindowContext) -> S,
201    {
202        cx.update_global(update)
203    }
204
205    fn activate_editor(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
206        if !editor.read(cx).use_modal_editing() {
207            return;
208        }
209
210        self.active_editor = Some(editor.clone().downgrade());
211        self.editor_subscription = Some(cx.subscribe(&editor, |editor, event, cx| match event {
212            EditorEvent::SelectionsChanged { local: true } => {
213                let editor = editor.read(cx);
214                if editor.leader_peer_id().is_none() {
215                    let newest = editor.selections.newest::<usize>(cx);
216                    let is_multicursor = editor.selections.count() > 1;
217                    local_selections_changed(newest, is_multicursor, cx);
218                }
219            }
220            EditorEvent::InputIgnored { text } => {
221                Vim::active_editor_input_ignored(text.clone(), cx);
222                Vim::record_insertion(text, None, cx)
223            }
224            EditorEvent::InputHandled {
225                text,
226                utf16_range_to_replace: range_to_replace,
227            } => Vim::record_insertion(text, range_to_replace.clone(), cx),
228            _ => {}
229        }));
230
231        let editor = editor.read(cx);
232        let editor_mode = editor.mode();
233        let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
234
235        if editor_mode == EditorMode::Full
236                && !newest_selection_empty
237                && self.state().mode == Mode::Normal
238                // When following someone, don't switch vim mode.
239                && editor.leader_peer_id().is_none()
240        {
241            self.switch_mode(Mode::Visual, true, cx);
242        }
243
244        self.sync_vim_settings(cx);
245    }
246
247    fn record_insertion(
248        text: &Arc<str>,
249        range_to_replace: Option<Range<isize>>,
250        cx: &mut WindowContext,
251    ) {
252        Vim::update(cx, |vim, _| {
253            if vim.workspace_state.recording {
254                vim.workspace_state
255                    .recorded_actions
256                    .push(ReplayableAction::Insertion {
257                        text: text.clone(),
258                        utf16_range_to_replace: range_to_replace,
259                    });
260                if vim.workspace_state.stop_recording_after_next_action {
261                    vim.workspace_state.recording = false;
262                    vim.workspace_state.stop_recording_after_next_action = false;
263                }
264            }
265        });
266    }
267
268    fn update_active_editor<S>(
269        &mut self,
270        cx: &mut WindowContext,
271        update: impl FnOnce(&mut Vim, &mut Editor, &mut ViewContext<Editor>) -> S,
272    ) -> Option<S> {
273        let editor = self.active_editor.clone()?.upgrade()?;
274        Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
275    }
276
277    /// When doing an action that modifies the buffer, we start recording so that `.`
278    /// will replay the action.
279    pub fn start_recording(&mut self, cx: &mut WindowContext) {
280        if !self.workspace_state.replaying {
281            self.workspace_state.recording = true;
282            self.workspace_state.recorded_actions = Default::default();
283            self.workspace_state.recorded_count = None;
284
285            let selections = self
286                .active_editor
287                .as_ref()
288                .and_then(|editor| editor.upgrade())
289                .map(|editor| {
290                    let editor = editor.read(cx);
291                    (
292                        editor.selections.oldest::<Point>(cx),
293                        editor.selections.newest::<Point>(cx),
294                    )
295                });
296
297            if let Some((oldest, newest)) = selections {
298                self.workspace_state.recorded_selection = match self.state().mode {
299                    Mode::Visual if newest.end.row == newest.start.row => {
300                        RecordedSelection::SingleLine {
301                            cols: newest.end.column - newest.start.column,
302                        }
303                    }
304                    Mode::Visual => RecordedSelection::Visual {
305                        rows: newest.end.row - newest.start.row,
306                        cols: newest.end.column,
307                    },
308                    Mode::VisualLine => RecordedSelection::VisualLine {
309                        rows: newest.end.row - newest.start.row,
310                    },
311                    Mode::VisualBlock => RecordedSelection::VisualBlock {
312                        rows: newest.end.row.abs_diff(oldest.start.row),
313                        cols: newest.end.column.abs_diff(oldest.start.column),
314                    },
315                    _ => RecordedSelection::None,
316                }
317            } else {
318                self.workspace_state.recorded_selection = RecordedSelection::None;
319            }
320        }
321    }
322
323    /// When finishing an action that modifies the buffer, stop recording.
324    /// as you usually call this within a keystroke handler we also ensure that
325    /// the current action is recorded.
326    pub fn stop_recording(&mut self) {
327        if self.workspace_state.recording {
328            self.workspace_state.stop_recording_after_next_action = true;
329        }
330    }
331
332    /// Stops recording actions immediately rather than waiting until after the
333    /// next action to stop recording.
334    ///
335    /// This doesn't include the current action.
336    pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>) {
337        if self.workspace_state.recording {
338            self.workspace_state
339                .recorded_actions
340                .push(ReplayableAction::Action(action.boxed_clone()));
341            self.workspace_state.recording = false;
342            self.workspace_state.stop_recording_after_next_action = false;
343        }
344    }
345
346    /// Explicitly record one action (equivalents to start_recording and stop_recording)
347    pub fn record_current_action(&mut self, cx: &mut WindowContext) {
348        self.start_recording(cx);
349        self.stop_recording();
350    }
351
352    fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut WindowContext) {
353        let state = self.state();
354        let last_mode = state.mode;
355        let prior_mode = state.last_mode;
356        self.update_state(|state| {
357            state.last_mode = last_mode;
358            state.mode = mode;
359            state.operator_stack.clear();
360        });
361        if mode != Mode::Insert {
362            self.take_count(cx);
363        }
364
365        // Sync editor settings like clip mode
366        self.sync_vim_settings(cx);
367
368        if leave_selections {
369            return;
370        }
371
372        // Adjust selections
373        self.update_active_editor(cx, |_, editor, cx| {
374            if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
375            {
376                visual_block_motion(true, editor, cx, |_, point, goal| Some((point, goal)))
377            }
378
379            editor.change_selections(None, cx, |s| {
380                // we cheat with visual block mode and use multiple cursors.
381                // the cost of this cheat is we need to convert back to a single
382                // cursor whenever vim would.
383                if last_mode == Mode::VisualBlock
384                    && (mode != Mode::VisualBlock && mode != Mode::Insert)
385                {
386                    let tail = s.oldest_anchor().tail();
387                    let head = s.newest_anchor().head();
388                    s.select_anchor_ranges(vec![tail..head]);
389                } else if last_mode == Mode::Insert
390                    && prior_mode == Mode::VisualBlock
391                    && mode != Mode::VisualBlock
392                {
393                    let pos = s.first_anchor().head();
394                    s.select_anchor_ranges(vec![pos..pos])
395                }
396
397                s.move_with(|map, selection| {
398                    if last_mode.is_visual() && !mode.is_visual() {
399                        let mut point = selection.head();
400                        if !selection.reversed && !selection.is_empty() {
401                            point = movement::left(map, selection.head());
402                        }
403                        selection.collapse_to(point, selection.goal)
404                    } else if !last_mode.is_visual() && mode.is_visual() {
405                        if selection.is_empty() {
406                            selection.end = movement::right(map, selection.start);
407                        }
408                    }
409                });
410            })
411        });
412    }
413
414    fn push_count_digit(&mut self, number: usize, cx: &mut WindowContext) {
415        if self.active_operator().is_some() {
416            self.update_state(|state| {
417                state.post_count = Some(state.post_count.unwrap_or(0) * 10 + number)
418            })
419        } else {
420            self.update_state(|state| {
421                state.pre_count = Some(state.pre_count.unwrap_or(0) * 10 + number)
422            })
423        }
424        // update the keymap so that 0 works
425        self.sync_vim_settings(cx)
426    }
427
428    fn take_count(&mut self, cx: &mut WindowContext) -> Option<usize> {
429        if self.workspace_state.replaying {
430            return self.workspace_state.recorded_count;
431        }
432
433        let count = if self.state().post_count == None && self.state().pre_count == None {
434            return None;
435        } else {
436            Some(self.update_state(|state| {
437                state.post_count.take().unwrap_or(1) * state.pre_count.take().unwrap_or(1)
438            }))
439        };
440        if self.workspace_state.recording {
441            self.workspace_state.recorded_count = count;
442        }
443        self.sync_vim_settings(cx);
444        count
445    }
446
447    fn push_operator(&mut self, operator: Operator, cx: &mut WindowContext) {
448        if matches!(
449            operator,
450            Operator::Change | Operator::Delete | Operator::Replace
451        ) {
452            self.start_recording(cx)
453        };
454        self.update_state(|state| state.operator_stack.push(operator));
455        self.sync_vim_settings(cx);
456    }
457
458    fn maybe_pop_operator(&mut self) -> Option<Operator> {
459        self.update_state(|state| state.operator_stack.pop())
460    }
461
462    fn pop_operator(&mut self, cx: &mut WindowContext) -> Operator {
463        let popped_operator = self.update_state( |state| state.operator_stack.pop()
464        )            .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
465        self.sync_vim_settings(cx);
466        popped_operator
467    }
468    fn clear_operator(&mut self, cx: &mut WindowContext) {
469        self.take_count(cx);
470        self.update_state(|state| state.operator_stack.clear());
471        self.sync_vim_settings(cx);
472    }
473
474    fn active_operator(&self) -> Option<Operator> {
475        self.state().operator_stack.last().copied()
476    }
477
478    fn active_editor_input_ignored(text: Arc<str>, cx: &mut WindowContext) {
479        if text.is_empty() {
480            return;
481        }
482
483        match Vim::read(cx).active_operator() {
484            Some(Operator::FindForward { before }) => {
485                let find = Motion::FindForward {
486                    before,
487                    char: text.chars().next().unwrap(),
488                    mode: if VimSettings::get_global(cx).use_multiline_find {
489                        FindRange::MultiLine
490                    } else {
491                        FindRange::SingleLine
492                    },
493                };
494                Vim::update(cx, |vim, _| {
495                    vim.workspace_state.last_find = Some(find.clone())
496                });
497                motion::motion(find, cx)
498            }
499            Some(Operator::FindBackward { after }) => {
500                let find = Motion::FindBackward {
501                    after,
502                    char: text.chars().next().unwrap(),
503                    mode: if VimSettings::get_global(cx).use_multiline_find {
504                        FindRange::MultiLine
505                    } else {
506                        FindRange::SingleLine
507                    },
508                };
509                Vim::update(cx, |vim, _| {
510                    vim.workspace_state.last_find = Some(find.clone())
511                });
512                motion::motion(find, cx)
513            }
514            Some(Operator::Replace) => match Vim::read(cx).state().mode {
515                Mode::Normal => normal_replace(text, cx),
516                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => visual_replace(text, cx),
517                _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
518            },
519            _ => {}
520        }
521    }
522
523    fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
524        if self.enabled == enabled {
525            return;
526        }
527        if !enabled {
528            let _ = cx.remove_global::<CommandPaletteInterceptor>();
529            cx.update_global::<CommandPaletteFilter, _>(|filter, _| {
530                filter.hidden_namespaces.insert("vim");
531            });
532            *self = Default::default();
533            return;
534        }
535
536        self.enabled = true;
537        cx.update_global::<CommandPaletteFilter, _>(|filter, _| {
538            filter.hidden_namespaces.remove("vim");
539        });
540        cx.set_global::<CommandPaletteInterceptor>(CommandPaletteInterceptor(Box::new(
541            command::command_interceptor,
542        )));
543
544        if let Some(active_window) = cx
545            .active_window()
546            .and_then(|window| window.downcast::<Workspace>())
547        {
548            active_window
549                .update(cx, |workspace, cx| {
550                    let active_editor = workspace.active_item_as::<Editor>(cx);
551                    if let Some(active_editor) = active_editor {
552                        self.activate_editor(active_editor, cx);
553                        self.switch_mode(Mode::Normal, false, cx);
554                    }
555                })
556                .ok();
557        }
558    }
559
560    /// Returns the state of the active editor.
561    pub fn state(&self) -> &EditorState {
562        if let Some(active_editor) = self.active_editor.as_ref() {
563            if let Some(state) = self.editor_states.get(&active_editor.entity_id()) {
564                return state;
565            }
566        }
567
568        &self.default_state
569    }
570
571    /// Updates the state of the active editor.
572    pub fn update_state<T>(&mut self, func: impl FnOnce(&mut EditorState) -> T) -> T {
573        let mut state = self.state().clone();
574        let ret = func(&mut state);
575
576        if let Some(active_editor) = self.active_editor.as_ref() {
577            self.editor_states.insert(active_editor.entity_id(), state);
578        }
579
580        ret
581    }
582
583    fn sync_vim_settings(&mut self, cx: &mut WindowContext) {
584        self.update_active_editor(cx, |vim, editor, cx| {
585            let state = vim.state();
586            editor.set_cursor_shape(state.cursor_shape(), cx);
587            editor.set_clip_at_line_ends(state.clip_at_line_ends(), cx);
588            editor.set_collapse_matches(true);
589            editor.set_input_enabled(!state.vim_controlled());
590            editor.set_autoindent(state.should_autoindent());
591            editor.selections.line_mode = matches!(state.mode, Mode::VisualLine);
592            if editor.is_focused(cx) {
593                editor.set_keymap_context_layer::<Self>(state.keymap_context_layer(), cx);
594            } else {
595                editor.remove_keymap_context_layer::<Self>(cx);
596            }
597        });
598    }
599
600    fn unhook_vim_settings(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
601        if editor.mode() == EditorMode::Full {
602            editor.set_cursor_shape(CursorShape::Bar, cx);
603            editor.set_clip_at_line_ends(false, cx);
604            editor.set_collapse_matches(false);
605            editor.set_input_enabled(true);
606            editor.set_autoindent(true);
607            editor.selections.line_mode = false;
608        }
609        editor.remove_keymap_context_layer::<Self>(cx)
610    }
611}
612
613impl Settings for VimModeSetting {
614    const KEY: Option<&'static str> = Some("vim_mode");
615
616    type FileContent = Option<bool>;
617
618    fn load(
619        default_value: &Self::FileContent,
620        user_values: &[&Self::FileContent],
621        _: &mut AppContext,
622    ) -> Result<Self> {
623        Ok(Self(user_values.iter().rev().find_map(|v| **v).unwrap_or(
624            default_value.ok_or_else(Self::missing_default)?,
625        )))
626    }
627}
628
629/// Controls the soft-wrapping behavior in the editor.
630#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
631#[serde(rename_all = "snake_case")]
632pub enum UseSystemClipboard {
633    Never,
634    Always,
635    OnYank,
636}
637
638#[derive(Deserialize)]
639struct VimSettings {
640    // all vim uses vim clipboard
641    // vim always uses system cliupbaord
642    // some magic where yy is system and dd is not.
643    pub use_system_clipboard: UseSystemClipboard,
644    pub use_multiline_find: bool,
645}
646
647#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
648struct VimSettingsContent {
649    pub use_system_clipboard: Option<UseSystemClipboard>,
650    pub use_multiline_find: Option<bool>,
651}
652
653impl Settings for VimSettings {
654    const KEY: Option<&'static str> = Some("vim");
655
656    type FileContent = VimSettingsContent;
657
658    fn load(
659        default_value: &Self::FileContent,
660        user_values: &[&Self::FileContent],
661        _: &mut AppContext,
662    ) -> Result<Self> {
663        Self::load_via_json_merge(default_value, user_values)
664    }
665}
666
667fn local_selections_changed(
668    newest: Selection<usize>,
669    is_multicursor: bool,
670    cx: &mut WindowContext,
671) {
672    Vim::update(cx, |vim, cx| {
673        if vim.state().mode == Mode::Normal && !newest.is_empty() {
674            if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
675                vim.switch_mode(Mode::VisualBlock, false, cx);
676            } else {
677                vim.switch_mode(Mode::Visual, false, cx)
678            }
679        } else if newest.is_empty()
680            && !is_multicursor
681            && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&vim.state().mode)
682        {
683            vim.switch_mode(Mode::Normal, true, cx)
684        }
685    })
686}