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