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