vim.rs

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