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