vim.rs

  1#[cfg(test)]
  2mod vim_test_context;
  3
  4mod editor_events;
  5mod insert;
  6mod motion;
  7mod normal;
  8mod state;
  9mod utils;
 10mod visual;
 11
 12use collections::HashMap;
 13use editor::{Bias, CursorShape, Editor, Input};
 14use gpui::{impl_actions, MutableAppContext, Subscription, ViewContext, WeakViewHandle};
 15use serde::Deserialize;
 16
 17use settings::Settings;
 18use state::{Mode, Operator, VimState};
 19use workspace::{self, Workspace};
 20
 21#[derive(Clone, Deserialize, PartialEq)]
 22pub struct SwitchMode(pub Mode);
 23
 24#[derive(Clone, Deserialize, PartialEq)]
 25pub struct PushOperator(pub Operator);
 26
 27impl_actions!(vim, [SwitchMode, PushOperator]);
 28
 29pub fn init(cx: &mut MutableAppContext) {
 30    editor_events::init(cx);
 31    normal::init(cx);
 32    visual::init(cx);
 33    insert::init(cx);
 34    motion::init(cx);
 35
 36    cx.add_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {
 37        Vim::update(cx, |vim, cx| vim.switch_mode(mode, cx))
 38    });
 39    cx.add_action(
 40        |_: &mut Workspace, &PushOperator(operator): &PushOperator, cx| {
 41            Vim::update(cx, |vim, cx| vim.push_operator(operator, cx))
 42        },
 43    );
 44    cx.add_action(|_: &mut Editor, _: &Input, cx| {
 45        if Vim::read(cx).active_operator().is_some() {
 46            // Defer without updating editor
 47            MutableAppContext::defer(cx, |cx| Vim::update(cx, |vim, cx| vim.clear_operator(cx)))
 48        } else {
 49            cx.propagate_action()
 50        }
 51    });
 52
 53    cx.observe_global::<Settings, _>(|cx| {
 54        Vim::update(cx, |state, cx| {
 55            state.set_enabled(cx.global::<Settings>().vim_mode, cx)
 56        })
 57    })
 58    .detach();
 59}
 60
 61#[derive(Default)]
 62pub struct Vim {
 63    editors: HashMap<usize, WeakViewHandle<Editor>>,
 64    active_editor: Option<WeakViewHandle<Editor>>,
 65    selection_subscription: Option<Subscription>,
 66
 67    enabled: bool,
 68    state: VimState,
 69}
 70
 71impl Vim {
 72    fn read(cx: &mut MutableAppContext) -> &Self {
 73        cx.default_global()
 74    }
 75
 76    fn update<F, S>(cx: &mut MutableAppContext, update: F) -> S
 77    where
 78        F: FnOnce(&mut Self, &mut MutableAppContext) -> S,
 79    {
 80        cx.update_default_global(update)
 81    }
 82
 83    fn update_active_editor<S>(
 84        &self,
 85        cx: &mut MutableAppContext,
 86        update: impl FnOnce(&mut Editor, &mut ViewContext<Editor>) -> S,
 87    ) -> Option<S> {
 88        self.active_editor
 89            .clone()
 90            .and_then(|ae| ae.upgrade(cx))
 91            .map(|ae| ae.update(cx, update))
 92    }
 93
 94    fn switch_mode(&mut self, mode: Mode, cx: &mut MutableAppContext) {
 95        self.state.mode = mode;
 96        self.state.operator_stack.clear();
 97        self.sync_editor_options(cx);
 98    }
 99
100    fn push_operator(&mut self, operator: Operator, cx: &mut MutableAppContext) {
101        self.state.operator_stack.push(operator);
102        self.sync_editor_options(cx);
103    }
104
105    fn pop_operator(&mut self, cx: &mut MutableAppContext) -> Operator {
106        let popped_operator = self.state.operator_stack.pop().expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
107        self.sync_editor_options(cx);
108        popped_operator
109    }
110
111    fn clear_operator(&mut self, cx: &mut MutableAppContext) {
112        self.state.operator_stack.clear();
113        self.sync_editor_options(cx);
114    }
115
116    fn active_operator(&self) -> Option<Operator> {
117        self.state.operator_stack.last().copied()
118    }
119
120    fn set_enabled(&mut self, enabled: bool, cx: &mut MutableAppContext) {
121        if self.enabled != enabled {
122            self.enabled = enabled;
123            self.state = Default::default();
124            if enabled {
125                self.state.mode = Mode::Normal;
126            }
127            self.sync_editor_options(cx);
128        }
129    }
130
131    fn sync_editor_options(&self, cx: &mut MutableAppContext) {
132        let state = &self.state;
133        let cursor_shape = state.cursor_shape();
134
135        for editor in self.editors.values() {
136            if let Some(editor) = editor.upgrade(cx) {
137                editor.update(cx, |editor, cx| {
138                    if self.enabled {
139                        editor.set_cursor_shape(cursor_shape, cx);
140                        editor.set_clip_at_line_ends(state.clip_at_line_end(), cx);
141                        editor.set_input_enabled(!state.vim_controlled());
142                        editor.selections.line_mode =
143                            matches!(state.mode, Mode::Visual { line: true });
144                        let context_layer = state.keymap_context_layer();
145                        editor.set_keymap_context_layer::<Self>(context_layer);
146                        editor.change_selections(None, cx, |s| {
147                            s.move_with(|map, selection| {
148                                selection.set_head(
149                                    map.clip_point(selection.head(), Bias::Left),
150                                    selection.goal,
151                                );
152                                if state.empty_selections_only() {
153                                    selection.collapse_to(selection.head(), selection.goal)
154                                }
155                            });
156                        })
157                    } else {
158                        editor.set_cursor_shape(CursorShape::Bar, cx);
159                        editor.set_clip_at_line_ends(false, cx);
160                        editor.set_input_enabled(true);
161                        editor.selections.line_mode = false;
162                        editor.remove_keymap_context_layer::<Self>();
163                    }
164                });
165            }
166        }
167    }
168}
169
170#[cfg(test)]
171mod test {
172    use crate::{state::Mode, vim_test_context::VimTestContext};
173
174    #[gpui::test]
175    async fn test_initially_disabled(cx: &mut gpui::TestAppContext) {
176        let mut cx = VimTestContext::new(cx, false).await;
177        cx.simulate_keystrokes(["h", "j", "k", "l"]);
178        cx.assert_editor_state("hjkl|");
179    }
180
181    #[gpui::test]
182    async fn test_toggle_through_settings(cx: &mut gpui::TestAppContext) {
183        let mut cx = VimTestContext::new(cx, true).await;
184
185        cx.simulate_keystroke("i");
186        assert_eq!(cx.mode(), Mode::Insert);
187
188        // Editor acts as though vim is disabled
189        cx.disable_vim();
190        cx.simulate_keystrokes(["h", "j", "k", "l"]);
191        cx.assert_editor_state("hjkl|");
192
193        // Selections aren't changed if editor is blurred but vim-mode is still disabled.
194        cx.set_state("[hjkl}", Mode::Normal);
195        cx.assert_editor_state("[hjkl}");
196        cx.update_editor(|_, cx| cx.blur());
197        cx.assert_editor_state("[hjkl}");
198        cx.update_editor(|_, cx| cx.focus_self());
199        cx.assert_editor_state("[hjkl}");
200
201        // Enabling dynamically sets vim mode again and restores normal mode
202        cx.enable_vim();
203        assert_eq!(cx.mode(), Mode::Normal);
204        cx.simulate_keystrokes(["h", "h", "h", "l"]);
205        assert_eq!(cx.buffer_text(), "hjkl".to_owned());
206        cx.assert_editor_state("h|jkl");
207        cx.simulate_keystrokes(["i", "T", "e", "s", "t"]);
208        cx.assert_editor_state("hTest|jkl");
209
210        // Disabling and enabling resets to normal mode
211        assert_eq!(cx.mode(), Mode::Insert);
212        cx.disable_vim();
213        cx.enable_vim();
214        assert_eq!(cx.mode(), Mode::Normal);
215    }
216}