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