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