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