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)]
 22pub struct SwitchMode(pub Mode);
 23
 24#[derive(Clone, Deserialize)]
 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                    } else {
147                        editor.set_cursor_shape(CursorShape::Bar, cx);
148                        editor.set_clip_at_line_ends(false, cx);
149                        editor.set_input_enabled(true);
150                        editor.selections.line_mode = false;
151                        editor.remove_keymap_context_layer::<Self>();
152                    }
153
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                });
166            }
167        }
168    }
169}
170
171#[cfg(test)]
172mod test {
173    use crate::{state::Mode, vim_test_context::VimTestContext};
174
175    #[gpui::test]
176    async fn test_initially_disabled(cx: &mut gpui::TestAppContext) {
177        let mut cx = VimTestContext::new(cx, false).await;
178        cx.simulate_keystrokes(["h", "j", "k", "l"]);
179        cx.assert_editor_state("hjkl|");
180    }
181
182    #[gpui::test]
183    async fn test_toggle_through_settings(cx: &mut gpui::TestAppContext) {
184        let mut cx = VimTestContext::new(cx, true).await;
185
186        cx.simulate_keystroke("i");
187        assert_eq!(cx.mode(), Mode::Insert);
188
189        // Editor acts as though vim is disabled
190        cx.disable_vim();
191        cx.simulate_keystrokes(["h", "j", "k", "l"]);
192        cx.assert_editor_state("hjkl|");
193
194        // Enabling dynamically sets vim mode again and restores normal mode
195        cx.enable_vim();
196        assert_eq!(cx.mode(), Mode::Normal);
197        cx.simulate_keystrokes(["h", "h", "h", "l"]);
198        assert_eq!(cx.editor_text(), "hjkl".to_owned());
199        cx.assert_editor_state("h|jkl");
200        cx.simulate_keystrokes(["i", "T", "e", "s", "t"]);
201        cx.assert_editor_state("hTest|jkl");
202
203        // Disabling and enabling resets to normal mode
204        assert_eq!(cx.mode(), Mode::Insert);
205        cx.disable_vim();
206        cx.enable_vim();
207        assert_eq!(cx.mode(), Mode::Normal);
208    }
209}