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