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