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, Event};
 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            WindowContext::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    // Any time settings change, update vim mode to match.
 88    cx.update_default_global(|vim: &mut Vim, cx: &mut AppContext| {
 89        vim.set_enabled(cx.global::<Settings>().vim_mode, cx)
 90    });
 91    cx.observe_global::<Settings, _>(|cx| {
 92        cx.update_default_global(|vim: &mut Vim, cx: &mut AppContext| {
 93            vim.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 WindowContext, update: F) -> S
140    where
141        F: FnOnce(&mut Self, &mut WindowContext) -> S,
142    {
143        cx.update_default_global(update)
144    }
145
146    fn set_active_editor(&mut self, editor: ViewHandle<Editor>, cx: &mut WindowContext) {
147        self.active_editor = Some(editor.downgrade());
148        self.editor_subscription = Some(cx.subscribe(&editor, |editor, event, cx| match event {
149            Event::SelectionsChanged { local: true } => {
150                let editor = editor.read(cx);
151                if editor.leader_replica_id().is_none() {
152                    let newest_empty = editor.selections.newest::<usize>(cx).is_empty();
153                    local_selections_changed(newest_empty, cx);
154                }
155            }
156            Event::InputIgnored { text } => {
157                Vim::active_editor_input_ignored(text.clone(), cx);
158            }
159            _ => {}
160        }));
161
162        if self.enabled {
163            let editor = editor.read(cx);
164            let editor_mode = editor.mode();
165            let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
166
167            if editor_mode == EditorMode::Full && !newest_selection_empty {
168                self.switch_mode(Mode::Visual { line: false }, true, cx);
169            }
170        }
171
172        self.sync_vim_settings(cx);
173    }
174
175    fn update_active_editor<S>(
176        &self,
177        cx: &mut WindowContext,
178        update: impl FnOnce(&mut Editor, &mut ViewContext<Editor>) -> S,
179    ) -> Option<S> {
180        let editor = self.active_editor.clone()?.upgrade(cx)?;
181        Some(editor.update(cx, update))
182    }
183
184    fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut WindowContext) {
185        self.state.mode = mode;
186        self.state.operator_stack.clear();
187
188        // Sync editor settings like clip mode
189        self.sync_vim_settings(cx);
190
191        if leave_selections {
192            return;
193        }
194
195        // Adjust selections
196        self.update_active_editor(cx, |editor, cx| {
197            editor.change_selections(None, cx, |s| {
198                s.move_with(|map, selection| {
199                    if self.state.empty_selections_only() {
200                        let new_head = map.clip_point(selection.head(), Bias::Left);
201                        selection.collapse_to(new_head, selection.goal)
202                    } else {
203                        selection
204                            .set_head(map.clip_point(selection.head(), Bias::Left), selection.goal);
205                    }
206                });
207            })
208        });
209    }
210
211    fn push_operator(&mut self, operator: Operator, cx: &mut WindowContext) {
212        self.state.operator_stack.push(operator);
213        self.sync_vim_settings(cx);
214    }
215
216    fn push_number(&mut self, Number(number): &Number, cx: &mut WindowContext) {
217        if let Some(Operator::Number(current_number)) = self.active_operator() {
218            self.pop_operator(cx);
219            self.push_operator(Operator::Number(current_number * 10 + *number as usize), cx);
220        } else {
221            self.push_operator(Operator::Number(*number as usize), cx);
222        }
223    }
224
225    fn pop_operator(&mut self, cx: &mut WindowContext) -> Operator {
226        let popped_operator = self.state.operator_stack.pop()
227            .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
228        self.sync_vim_settings(cx);
229        popped_operator
230    }
231
232    fn pop_number_operator(&mut self, cx: &mut WindowContext) -> usize {
233        let mut times = 1;
234        if let Some(Operator::Number(number)) = self.active_operator() {
235            times = number;
236            self.pop_operator(cx);
237        }
238        times
239    }
240
241    fn clear_operator(&mut self, cx: &mut WindowContext) {
242        self.state.operator_stack.clear();
243        self.sync_vim_settings(cx);
244    }
245
246    fn active_operator(&self) -> Option<Operator> {
247        self.state.operator_stack.last().copied()
248    }
249
250    fn active_editor_input_ignored(text: Arc<str>, cx: &mut WindowContext) {
251        if text.is_empty() {
252            return;
253        }
254
255        match Vim::read(cx).active_operator() {
256            Some(Operator::FindForward { before }) => {
257                motion::motion(Motion::FindForward { before, text }, cx)
258            }
259            Some(Operator::FindBackward { after }) => {
260                motion::motion(Motion::FindBackward { after, text }, cx)
261            }
262            Some(Operator::Replace) => match Vim::read(cx).state.mode {
263                Mode::Normal => normal_replace(text, cx),
264                Mode::Visual { line } => visual_replace(text, line, cx),
265                _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
266            },
267            _ => {}
268        }
269    }
270
271    fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
272        if self.enabled != enabled {
273            self.enabled = enabled;
274            self.state = Default::default();
275
276            cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
277                if self.enabled {
278                    filter.filtered_namespaces.remove("vim");
279                } else {
280                    filter.filtered_namespaces.insert("vim");
281                }
282            });
283
284            cx.update_active_window(|cx| {
285                if self.enabled {
286                    let active_editor = cx
287                        .root_view()
288                        .downcast_ref::<Workspace>()
289                        .and_then(|workspace| workspace.read(cx).active_item(cx))
290                        .and_then(|item| item.downcast::<Editor>());
291                    if let Some(active_editor) = active_editor {
292                        self.set_active_editor(active_editor, cx);
293                    }
294                    self.switch_mode(Mode::Normal, false, cx);
295                }
296                self.sync_vim_settings(cx);
297            });
298        }
299    }
300
301    fn sync_vim_settings(&self, cx: &mut WindowContext) {
302        let state = &self.state;
303        let cursor_shape = state.cursor_shape();
304
305        self.update_active_editor(cx, |editor, cx| {
306            if self.enabled && editor.mode() == EditorMode::Full {
307                editor.set_cursor_shape(cursor_shape, cx);
308                editor.set_clip_at_line_ends(state.clip_at_line_end(), cx);
309                editor.set_input_enabled(!state.vim_controlled());
310                editor.selections.line_mode = matches!(state.mode, Mode::Visual { line: true });
311                let context_layer = state.keymap_context_layer();
312                editor.set_keymap_context_layer::<Self>(context_layer);
313            } else {
314                Self::unhook_vim_settings(editor, cx);
315            }
316        });
317    }
318
319    fn unhook_vim_settings(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
320        editor.set_cursor_shape(CursorShape::Bar, cx);
321        editor.set_clip_at_line_ends(false, cx);
322        editor.set_input_enabled(true);
323        editor.selections.line_mode = false;
324        editor.remove_keymap_context_layer::<Self>();
325    }
326}
327
328fn local_selections_changed(newest_empty: bool, cx: &mut WindowContext) {
329    Vim::update(cx, |vim, cx| {
330        if vim.enabled && vim.state.mode == Mode::Normal && !newest_empty {
331            vim.switch_mode(Mode::Visual { line: false }, false, cx)
332        }
333    })
334}