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