vim.rs

  1#[cfg(test)]
  2mod test_contexts;
  3
  4mod editor_events;
  5mod insert;
  6mod motion;
  7mod normal;
  8mod object;
  9mod state;
 10mod utils;
 11mod visual;
 12
 13use collections::HashMap;
 14use command_palette::CommandPaletteFilter;
 15use editor::{Bias, Cancel, CursorShape, Editor};
 16use gpui::{impl_actions, MutableAppContext, Subscription, ViewContext, WeakViewHandle};
 17use serde::Deserialize;
 18
 19use settings::Settings;
 20use state::{Mode, Operator, VimState};
 21use workspace::{self, Workspace};
 22
 23#[derive(Clone, Deserialize, PartialEq)]
 24pub struct SwitchMode(pub Mode);
 25
 26#[derive(Clone, Deserialize, PartialEq)]
 27pub struct PushOperator(pub Operator);
 28
 29impl_actions!(vim, [SwitchMode, PushOperator]);
 30
 31pub fn init(cx: &mut MutableAppContext) {
 32    editor_events::init(cx);
 33    normal::init(cx);
 34    visual::init(cx);
 35    insert::init(cx);
 36    object::init(cx);
 37    motion::init(cx);
 38
 39    // Vim Actions
 40    cx.add_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {
 41        Vim::update(cx, |vim, cx| vim.switch_mode(mode, false, cx))
 42    });
 43    cx.add_action(
 44        |_: &mut Workspace, &PushOperator(operator): &PushOperator, cx| {
 45            Vim::update(cx, |vim, cx| vim.push_operator(operator, cx))
 46        },
 47    );
 48
 49    // Editor Actions
 50    cx.add_action(|_: &mut Editor, _: &Cancel, cx| {
 51        // If we are in a non normal mode or have an active operator, swap to normal mode
 52        // Otherwise forward cancel on to the editor
 53        let vim = Vim::read(cx);
 54        if vim.state.mode != Mode::Normal || vim.active_operator().is_some() {
 55            MutableAppContext::defer(cx, |cx| {
 56                Vim::update(cx, |state, cx| {
 57                    state.switch_mode(Mode::Normal, false, cx);
 58                });
 59            });
 60        } else {
 61            cx.propagate_action();
 62        }
 63    });
 64
 65    // Sync initial settings with the rest of the app
 66    Vim::update(cx, |state, cx| state.sync_vim_settings(cx));
 67
 68    // Any time settings change, update vim mode to match
 69    cx.observe_global::<Settings, _>(|cx| {
 70        Vim::update(cx, |state, cx| {
 71            state.set_enabled(cx.global::<Settings>().vim_mode, cx)
 72        })
 73    })
 74    .detach();
 75}
 76
 77#[derive(Default)]
 78pub struct Vim {
 79    editors: HashMap<usize, WeakViewHandle<Editor>>,
 80    active_editor: Option<WeakViewHandle<Editor>>,
 81    selection_subscription: Option<Subscription>,
 82
 83    enabled: bool,
 84    state: VimState,
 85}
 86
 87impl Vim {
 88    fn read(cx: &mut MutableAppContext) -> &Self {
 89        cx.default_global()
 90    }
 91
 92    fn update<F, S>(cx: &mut MutableAppContext, update: F) -> S
 93    where
 94        F: FnOnce(&mut Self, &mut MutableAppContext) -> S,
 95    {
 96        cx.update_default_global(update)
 97    }
 98
 99    fn update_active_editor<S>(
100        &self,
101        cx: &mut MutableAppContext,
102        update: impl FnOnce(&mut Editor, &mut ViewContext<Editor>) -> S,
103    ) -> Option<S> {
104        self.active_editor
105            .clone()
106            .and_then(|ae| ae.upgrade(cx))
107            .map(|ae| ae.update(cx, update))
108    }
109
110    fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut MutableAppContext) {
111        self.state.mode = mode;
112        self.state.operator_stack.clear();
113
114        // Sync editor settings like clip mode
115        self.sync_vim_settings(cx);
116
117        if leave_selections {
118            return;
119        }
120
121        // Adjust selections
122        for editor in self.editors.values() {
123            if let Some(editor) = editor.upgrade(cx) {
124                editor.update(cx, |editor, cx| {
125                    editor.change_selections(None, cx, |s| {
126                        s.move_with(|map, selection| {
127                            if self.state.empty_selections_only() {
128                                let new_head = map.clip_point(selection.head(), Bias::Left);
129                                selection.collapse_to(new_head, selection.goal)
130                            } else {
131                                selection.set_head(
132                                    map.clip_point(selection.head(), Bias::Left),
133                                    selection.goal,
134                                );
135                            }
136                        });
137                    })
138                })
139            }
140        }
141    }
142
143    fn push_operator(&mut self, operator: Operator, cx: &mut MutableAppContext) {
144        self.state.operator_stack.push(operator);
145        self.sync_vim_settings(cx);
146    }
147
148    fn pop_operator(&mut self, cx: &mut MutableAppContext) -> Operator {
149        let popped_operator = self.state.operator_stack.pop()
150            .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
151        self.sync_vim_settings(cx);
152        popped_operator
153    }
154
155    fn clear_operator(&mut self, cx: &mut MutableAppContext) {
156        self.state.operator_stack.clear();
157        self.sync_vim_settings(cx);
158    }
159
160    fn active_operator(&self) -> Option<Operator> {
161        self.state.operator_stack.last().copied()
162    }
163
164    fn set_enabled(&mut self, enabled: bool, cx: &mut MutableAppContext) {
165        if self.enabled != enabled {
166            self.enabled = enabled;
167            self.state = Default::default();
168            if enabled {
169                self.switch_mode(Mode::Normal, false, cx);
170            }
171            self.sync_vim_settings(cx);
172        }
173    }
174
175    fn sync_vim_settings(&self, cx: &mut MutableAppContext) {
176        let state = &self.state;
177        let cursor_shape = state.cursor_shape();
178
179        cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
180            if self.enabled {
181                filter.filtered_namespaces.remove("vim");
182            } else {
183                filter.filtered_namespaces.insert("vim");
184            }
185        });
186
187        for editor in self.editors.values() {
188            if let Some(editor) = editor.upgrade(cx) {
189                editor.update(cx, |editor, cx| {
190                    if self.enabled {
191                        editor.set_cursor_shape(cursor_shape, cx);
192                        editor.set_clip_at_line_ends(state.clip_at_line_end(), cx);
193                        editor.set_input_enabled(!state.vim_controlled());
194                        editor.selections.line_mode =
195                            matches!(state.mode, Mode::Visual { line: true });
196                        let context_layer = state.keymap_context_layer();
197                        editor.set_keymap_context_layer::<Self>(context_layer);
198                    } else {
199                        editor.set_cursor_shape(CursorShape::Bar, cx);
200                        editor.set_clip_at_line_ends(false, cx);
201                        editor.set_input_enabled(true);
202                        editor.selections.line_mode = false;
203                        editor.remove_keymap_context_layer::<Self>();
204                    }
205                });
206            }
207        }
208    }
209}
210
211#[cfg(test)]
212mod test {
213    use indoc::indoc;
214    use search::BufferSearchBar;
215
216    use crate::{
217        state::Mode,
218        test_contexts::{NeovimBackedTestContext, VimTestContext},
219    };
220
221    #[gpui::test]
222    async fn test_initially_disabled(cx: &mut gpui::TestAppContext) {
223        let mut cx = VimTestContext::new(cx, false).await;
224        cx.simulate_keystrokes(["h", "j", "k", "l"]);
225        cx.assert_editor_state("hjklˇ");
226    }
227
228    #[gpui::test]
229    async fn test_neovim(cx: &mut gpui::TestAppContext) {
230        let mut cx = NeovimBackedTestContext::new("test_neovim", cx).await;
231
232        cx.simulate_shared_keystroke("i").await;
233        cx.simulate_shared_keystrokes([
234            "shift-T", "e", "s", "t", " ", "t", "e", "s", "t", "escape", "0", "d", "w",
235        ])
236        .await;
237        cx.assert_state_matches().await;
238        cx.assert_editor_state("ˇtest");
239    }
240
241    #[gpui::test]
242    async fn test_toggle_through_settings(cx: &mut gpui::TestAppContext) {
243        let mut cx = VimTestContext::new(cx, true).await;
244
245        cx.simulate_keystroke("i");
246        assert_eq!(cx.mode(), Mode::Insert);
247
248        // Editor acts as though vim is disabled
249        cx.disable_vim();
250        cx.simulate_keystrokes(["h", "j", "k", "l"]);
251        cx.assert_editor_state("hjklˇ");
252
253        // Selections aren't changed if editor is blurred but vim-mode is still disabled.
254        cx.set_state("«hjklˇ»", Mode::Normal);
255        cx.assert_editor_state("«hjklˇ»");
256        cx.update_editor(|_, cx| cx.blur());
257        cx.assert_editor_state("«hjklˇ»");
258        cx.update_editor(|_, cx| cx.focus_self());
259        cx.assert_editor_state("«hjklˇ»");
260
261        // Enabling dynamically sets vim mode again and restores normal mode
262        cx.enable_vim();
263        assert_eq!(cx.mode(), Mode::Normal);
264        cx.simulate_keystrokes(["h", "h", "h", "l"]);
265        assert_eq!(cx.buffer_text(), "hjkl".to_owned());
266        cx.assert_editor_state("hˇjkl");
267        cx.simulate_keystrokes(["i", "T", "e", "s", "t"]);
268        cx.assert_editor_state("hTestˇjkl");
269
270        // Disabling and enabling resets to normal mode
271        assert_eq!(cx.mode(), Mode::Insert);
272        cx.disable_vim();
273        cx.enable_vim();
274        assert_eq!(cx.mode(), Mode::Normal);
275    }
276
277    #[gpui::test]
278    async fn test_buffer_search(cx: &mut gpui::TestAppContext) {
279        let mut cx = VimTestContext::new(cx, true).await;
280
281        cx.set_state(
282            indoc! {"
283            The quick brown
284            fox juˇmps over
285            the lazy dog"},
286            Mode::Normal,
287        );
288        cx.simulate_keystroke("/");
289
290        // We now use a weird insert mode with selection when jumping to a single line editor
291        assert_eq!(cx.mode(), Mode::Insert);
292
293        let search_bar = cx.workspace(|workspace, cx| {
294            workspace
295                .active_pane()
296                .read(cx)
297                .toolbar()
298                .read(cx)
299                .item_of_type::<BufferSearchBar>()
300                .expect("Buffer search bar should be deployed")
301        });
302
303        search_bar.read_with(cx.cx, |bar, cx| {
304            assert_eq!(bar.query_editor.read(cx).text(cx), "jumps");
305        })
306    }
307}