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