vim.rs

  1#[cfg(test)]
  2mod test;
  3
  4mod editor_events;
  5mod insert;
  6mod motion;
  7mod normal;
  8mod object;
  9mod state;
 10mod utils;
 11mod visual;
 12
 13use std::sync::Arc;
 14
 15use collections::CommandPaletteFilter;
 16use editor::{Bias, Cancel, Editor, EditorMode};
 17use gpui::{
 18    actions, impl_actions, MutableAppContext, Subscription, ViewContext, ViewHandle, WeakViewHandle,
 19};
 20use language::CursorShape;
 21use motion::Motion;
 22use normal::normal_replace;
 23use serde::Deserialize;
 24use settings::Settings;
 25use state::{Mode, Operator, VimState};
 26use visual::visual_replace;
 27use workspace::{self, Workspace};
 28
 29#[derive(Clone, Deserialize, PartialEq)]
 30pub struct SwitchMode(pub Mode);
 31
 32#[derive(Clone, Deserialize, PartialEq)]
 33pub struct PushOperator(pub Operator);
 34
 35#[derive(Clone, Deserialize, PartialEq)]
 36struct Number(u8);
 37
 38actions!(vim, [Tab, Enter]);
 39impl_actions!(vim, [Number, SwitchMode, PushOperator]);
 40
 41pub fn init(cx: &mut MutableAppContext) {
 42    editor_events::init(cx);
 43    normal::init(cx);
 44    visual::init(cx);
 45    insert::init(cx);
 46    object::init(cx);
 47    motion::init(cx);
 48
 49    // Vim Actions
 50    cx.add_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {
 51        Vim::update(cx, |vim, cx| vim.switch_mode(mode, false, cx))
 52    });
 53    cx.add_action(
 54        |_: &mut Workspace, &PushOperator(operator): &PushOperator, cx| {
 55            Vim::update(cx, |vim, cx| vim.push_operator(operator, cx))
 56        },
 57    );
 58    cx.add_action(|_: &mut Workspace, n: &Number, cx: _| {
 59        Vim::update(cx, |vim, cx| vim.push_number(n, cx));
 60    });
 61
 62    // Editor Actions
 63    cx.add_action(|_: &mut Editor, _: &Cancel, cx| {
 64        // If we are in aren't in normal mode or have an active operator, swap to normal mode
 65        // Otherwise forward cancel on to the editor
 66        let vim = Vim::read(cx);
 67        if vim.state.mode != Mode::Normal || vim.active_operator().is_some() {
 68            MutableAppContext::defer(cx, |cx| {
 69                Vim::update(cx, |state, cx| {
 70                    state.switch_mode(Mode::Normal, false, cx);
 71                });
 72            });
 73        } else {
 74            cx.propagate_action();
 75        }
 76    });
 77
 78    cx.add_action(|_: &mut Workspace, _: &Tab, cx| {
 79        Vim::active_editor_input_ignored(" ".into(), cx)
 80    });
 81
 82    cx.add_action(|_: &mut Workspace, _: &Enter, cx| {
 83        Vim::active_editor_input_ignored("\n".into(), cx)
 84    });
 85
 86    // Sync initial settings with the rest of the app
 87    Vim::update(cx, |vim, cx| vim.sync_vim_settings(cx));
 88
 89    // Any time settings change, update vim mode to match
 90    cx.observe_global::<Settings, _>(|cx| {
 91        Vim::update(cx, |state, cx| {
 92            state.set_enabled(cx.global::<Settings>().vim_mode, cx)
 93        })
 94    })
 95    .detach();
 96}
 97
 98pub fn observe_keystrokes(window_id: usize, cx: &mut MutableAppContext) {
 99    cx.observe_keystrokes(window_id, |_keystroke, _result, handled_by, cx| {
100        if let Some(handled_by) = handled_by {
101            // Keystroke is handled by the vim system, so continue forward
102            // Also short circuit if it is the special cancel action
103            if handled_by.namespace() == "vim"
104                || (handled_by.namespace() == "editor" && handled_by.name() == "Cancel")
105            {
106                return true;
107            }
108        }
109
110        Vim::update(cx, |vim, cx| match vim.active_operator() {
111            Some(
112                Operator::FindForward { .. } | Operator::FindBackward { .. } | Operator::Replace,
113            ) => {}
114            Some(_) => {
115                vim.clear_operator(cx);
116            }
117            _ => {}
118        });
119        true
120    })
121    .detach()
122}
123
124#[derive(Default)]
125pub struct Vim {
126    active_editor: Option<WeakViewHandle<Editor>>,
127    editor_subscription: Option<Subscription>,
128
129    enabled: bool,
130    state: VimState,
131}
132
133impl Vim {
134    fn read(cx: &mut MutableAppContext) -> &Self {
135        cx.default_global()
136    }
137
138    fn update<F, S>(cx: &mut MutableAppContext, update: F) -> S
139    where
140        F: FnOnce(&mut Self, &mut MutableAppContext) -> S,
141    {
142        cx.update_default_global(update)
143    }
144
145    fn update_active_editor<S>(
146        &self,
147        cx: &mut MutableAppContext,
148        update: impl FnOnce(&mut Editor, &mut ViewContext<Editor>) -> S,
149    ) -> Option<S> {
150        self.active_editor
151            .clone()
152            .and_then(|ae| ae.upgrade(cx))
153            .map(|ae| ae.update(cx, update))
154    }
155
156    fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut MutableAppContext) {
157        self.state.mode = mode;
158        self.state.operator_stack.clear();
159
160        // Sync editor settings like clip mode
161        self.sync_vim_settings(cx);
162
163        if leave_selections {
164            return;
165        }
166
167        // Adjust selections
168        if let Some(editor) = self
169            .active_editor
170            .as_ref()
171            .and_then(|editor| editor.upgrade(cx))
172        {
173            editor.update(cx, |editor, cx| {
174                editor.change_selections(None, cx, |s| {
175                    s.move_with(|map, selection| {
176                        if self.state.empty_selections_only() {
177                            let new_head = map.clip_point(selection.head(), Bias::Left);
178                            selection.collapse_to(new_head, selection.goal)
179                        } else {
180                            selection.set_head(
181                                map.clip_point(selection.head(), Bias::Left),
182                                selection.goal,
183                            );
184                        }
185                    });
186                })
187            })
188        }
189    }
190
191    fn push_operator(&mut self, operator: Operator, cx: &mut MutableAppContext) {
192        self.state.operator_stack.push(operator);
193        self.sync_vim_settings(cx);
194    }
195
196    fn push_number(&mut self, Number(number): &Number, cx: &mut MutableAppContext) {
197        if let Some(Operator::Number(current_number)) = self.active_operator() {
198            self.pop_operator(cx);
199            self.push_operator(Operator::Number(current_number * 10 + *number as usize), cx);
200        } else {
201            self.push_operator(Operator::Number(*number as usize), cx);
202        }
203    }
204
205    fn pop_operator(&mut self, cx: &mut MutableAppContext) -> Operator {
206        let popped_operator = self.state.operator_stack.pop()
207            .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
208        self.sync_vim_settings(cx);
209        popped_operator
210    }
211
212    fn pop_number_operator(&mut self, cx: &mut MutableAppContext) -> usize {
213        let mut times = 1;
214        if let Some(Operator::Number(number)) = self.active_operator() {
215            times = number;
216            self.pop_operator(cx);
217        }
218        times
219    }
220
221    fn clear_operator(&mut self, cx: &mut MutableAppContext) {
222        self.state.operator_stack.clear();
223        self.sync_vim_settings(cx);
224    }
225
226    fn active_operator(&self) -> Option<Operator> {
227        self.state.operator_stack.last().copied()
228    }
229
230    fn active_editor_input_ignored(text: Arc<str>, cx: &mut MutableAppContext) {
231        if text.is_empty() {
232            return;
233        }
234
235        match Vim::read(cx).active_operator() {
236            Some(Operator::FindForward { before }) => {
237                motion::motion(Motion::FindForward { before, text }, cx)
238            }
239            Some(Operator::FindBackward { after }) => {
240                motion::motion(Motion::FindBackward { after, text }, cx)
241            }
242            Some(Operator::Replace) => match Vim::read(cx).state.mode {
243                Mode::Normal => normal_replace(text, cx),
244                Mode::Visual { line } => visual_replace(text, line, cx),
245                _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
246            },
247            _ => {}
248        }
249    }
250
251    fn set_enabled(&mut self, enabled: bool, cx: &mut MutableAppContext) {
252        if self.enabled != enabled {
253            self.enabled = enabled;
254            self.state = Default::default();
255            if enabled {
256                self.switch_mode(Mode::Normal, false, cx);
257            }
258            self.sync_vim_settings(cx);
259        }
260    }
261
262    fn sync_vim_settings(&self, cx: &mut MutableAppContext) {
263        let state = &self.state;
264        let cursor_shape = state.cursor_shape();
265
266        cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
267            if self.enabled {
268                filter.filtered_namespaces.remove("vim");
269            } else {
270                filter.filtered_namespaces.insert("vim");
271            }
272        });
273
274        if let Some(editor) = self
275            .active_editor
276            .as_ref()
277            .and_then(|editor| editor.upgrade(cx))
278        {
279            if self.enabled && editor.read(cx).mode() == EditorMode::Full {
280                editor.update(cx, |editor, cx| {
281                    editor.set_cursor_shape(cursor_shape, cx);
282                    editor.set_clip_at_line_ends(state.clip_at_line_end(), cx);
283                    editor.set_input_enabled(!state.vim_controlled());
284                    editor.selections.line_mode = matches!(state.mode, Mode::Visual { line: true });
285                    let context_layer = state.keymap_context_layer();
286                    editor.set_keymap_context_layer::<Self>(context_layer);
287                });
288            } else {
289                self.unhook_vim_settings(editor, cx);
290            }
291        }
292    }
293
294    fn unhook_vim_settings(&self, editor: ViewHandle<Editor>, cx: &mut MutableAppContext) {
295        editor.update(cx, |editor, cx| {
296            editor.set_cursor_shape(CursorShape::Bar, cx);
297            editor.set_clip_at_line_ends(false, cx);
298            editor.set_input_enabled(true);
299            editor.selections.line_mode = false;
300            editor.remove_keymap_context_layer::<Self>();
301        });
302    }
303}