vim.rs

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