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