vim.rs

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