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