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