vim.rs

  1#[cfg(test)]
  2mod test;
  3
  4mod editor_events;
  5mod insert;
  6mod mode_indicator;
  7mod motion;
  8mod normal;
  9mod object;
 10mod state;
 11mod utils;
 12mod visual;
 13
 14use anyhow::Result;
 15use collections::CommandPaletteFilter;
 16use editor::{Bias, Editor, EditorMode, Event};
 17use gpui::{
 18    actions, impl_actions, keymap_matcher::KeymapContext, AppContext, Subscription, ViewContext,
 19    ViewHandle, WeakViewHandle, WindowContext,
 20};
 21use language::CursorShape;
 22pub use mode_indicator::ModeIndicator;
 23use motion::Motion;
 24use normal::normal_replace;
 25use serde::Deserialize;
 26use settings::{Setting, SettingsStore};
 27use state::{Mode, Operator, VimState};
 28use std::sync::Arc;
 29use visual::visual_replace;
 30use workspace::{self, Workspace};
 31
 32struct VimModeSetting(bool);
 33
 34#[derive(Clone, Deserialize, PartialEq)]
 35pub struct SwitchMode(pub Mode);
 36
 37#[derive(Clone, Deserialize, PartialEq)]
 38pub struct PushOperator(pub Operator);
 39
 40#[derive(Clone, Deserialize, PartialEq)]
 41struct Number(u8);
 42
 43actions!(vim, [Tab, Enter]);
 44impl_actions!(vim, [Number, SwitchMode, PushOperator]);
 45
 46pub fn init(cx: &mut AppContext) {
 47    settings::register::<VimModeSetting>(cx);
 48
 49    editor_events::init(cx);
 50    normal::init(cx);
 51    visual::init(cx);
 52    insert::init(cx);
 53    object::init(cx);
 54    motion::init(cx);
 55
 56    // Vim Actions
 57    cx.add_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {
 58        Vim::update(cx, |vim, cx| vim.switch_mode(mode, false, cx))
 59    });
 60    cx.add_action(
 61        |_: &mut Workspace, &PushOperator(operator): &PushOperator, cx| {
 62            Vim::update(cx, |vim, cx| vim.push_operator(operator, cx))
 63        },
 64    );
 65    cx.add_action(|_: &mut Workspace, n: &Number, cx: _| {
 66        Vim::update(cx, |vim, cx| vim.push_number(n, cx));
 67    });
 68
 69    cx.add_action(|_: &mut Workspace, _: &Tab, cx| {
 70        Vim::active_editor_input_ignored(" ".into(), cx)
 71    });
 72
 73    cx.add_action(|_: &mut Workspace, _: &Enter, cx| {
 74        Vim::active_editor_input_ignored("\n".into(), cx)
 75    });
 76
 77    // Any time settings change, update vim mode to match. The Vim struct
 78    // will be initialized as disabled by default, so we filter its commands
 79    // out when starting up.
 80    cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
 81        filter.filtered_namespaces.insert("vim");
 82    });
 83    cx.update_default_global(|vim: &mut Vim, cx: &mut AppContext| {
 84        vim.set_enabled(settings::get::<VimModeSetting>(cx).0, cx)
 85    });
 86    cx.observe_global::<SettingsStore, _>(|cx| {
 87        cx.update_default_global(|vim: &mut Vim, cx: &mut AppContext| {
 88            vim.set_enabled(settings::get::<VimModeSetting>(cx).0, cx)
 89        });
 90    })
 91    .detach();
 92}
 93
 94pub fn observe_keystrokes(cx: &mut WindowContext) {
 95    cx.observe_keystrokes(|_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            if handled_by.namespace() == "vim" {
 99                return true;
100            }
101        }
102
103        Vim::update(cx, |vim, cx| match vim.active_operator() {
104            Some(
105                Operator::FindForward { .. } | Operator::FindBackward { .. } | Operator::Replace,
106            ) => {}
107            Some(_) => {
108                vim.clear_operator(cx);
109            }
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    mode_indicator: Option<ViewHandle<ModeIndicator>>,
122
123    enabled: bool,
124    state: VimState,
125}
126
127impl Vim {
128    fn read(cx: &mut AppContext) -> &Self {
129        cx.default_global()
130    }
131
132    fn update<F, S>(cx: &mut WindowContext, update: F) -> S
133    where
134        F: FnOnce(&mut Self, &mut WindowContext) -> S,
135    {
136        cx.update_default_global(update)
137    }
138
139    fn set_active_editor(&mut self, editor: ViewHandle<Editor>, cx: &mut WindowContext) {
140        self.active_editor = Some(editor.downgrade());
141        self.editor_subscription = Some(cx.subscribe(&editor, |editor, event, cx| match event {
142            Event::SelectionsChanged { local: true } => {
143                let editor = editor.read(cx);
144                if editor.leader_replica_id().is_none() {
145                    let newest_empty = editor.selections.newest::<usize>(cx).is_empty();
146                    local_selections_changed(newest_empty, cx);
147                }
148            }
149            Event::InputIgnored { text } => {
150                Vim::active_editor_input_ignored(text.clone(), cx);
151            }
152            _ => {}
153        }));
154
155        if self.enabled {
156            let editor = editor.read(cx);
157            let editor_mode = editor.mode();
158            let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
159
160            if editor_mode == EditorMode::Full && !newest_selection_empty {
161                self.switch_mode(Mode::Visual { line: false }, true, cx);
162            }
163        }
164
165        self.sync_vim_settings(cx);
166    }
167
168    fn update_active_editor<S>(
169        &self,
170        cx: &mut WindowContext,
171        update: impl FnOnce(&mut Editor, &mut ViewContext<Editor>) -> S,
172    ) -> Option<S> {
173        let editor = self.active_editor.clone()?.upgrade(cx)?;
174        Some(editor.update(cx, update))
175    }
176
177    fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut WindowContext) {
178        self.state.mode = mode;
179        self.state.operator_stack.clear();
180
181        if let Some(mode_indicator) = &self.mode_indicator {
182            mode_indicator.update(cx, |mode_indicator, cx| mode_indicator.set_mode(mode, cx))
183        }
184
185        // Sync editor settings like clip mode
186        self.sync_vim_settings(cx);
187
188        if leave_selections {
189            return;
190        }
191
192        // Adjust selections
193        self.update_active_editor(cx, |editor, cx| {
194            editor.change_selections(None, cx, |s| {
195                s.move_with(|map, selection| {
196                    if self.state.empty_selections_only() {
197                        let new_head = map.clip_point(selection.head(), Bias::Left);
198                        selection.collapse_to(new_head, selection.goal)
199                    } else {
200                        selection
201                            .set_head(map.clip_point(selection.head(), Bias::Left), selection.goal);
202                    }
203                });
204            })
205        });
206    }
207
208    fn push_operator(&mut self, operator: Operator, cx: &mut WindowContext) {
209        self.state.operator_stack.push(operator);
210        self.sync_vim_settings(cx);
211    }
212
213    fn push_number(&mut self, Number(number): &Number, cx: &mut WindowContext) {
214        if let Some(Operator::Number(current_number)) = self.active_operator() {
215            self.pop_operator(cx);
216            self.push_operator(Operator::Number(current_number * 10 + *number as usize), cx);
217        } else {
218            self.push_operator(Operator::Number(*number as usize), cx);
219        }
220    }
221
222    fn pop_operator(&mut self, cx: &mut WindowContext) -> Operator {
223        let popped_operator = self.state.operator_stack.pop()
224            .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
225        self.sync_vim_settings(cx);
226        popped_operator
227    }
228
229    fn pop_number_operator(&mut self, cx: &mut WindowContext) -> Option<usize> {
230        if let Some(Operator::Number(number)) = self.active_operator() {
231            self.pop_operator(cx);
232            return Some(number);
233        }
234        None
235    }
236
237    fn clear_operator(&mut self, cx: &mut WindowContext) {
238        self.state.operator_stack.clear();
239        self.sync_vim_settings(cx);
240    }
241
242    fn active_operator(&self) -> Option<Operator> {
243        self.state.operator_stack.last().copied()
244    }
245
246    fn active_editor_input_ignored(text: Arc<str>, cx: &mut WindowContext) {
247        if text.is_empty() {
248            return;
249        }
250
251        match Vim::read(cx).active_operator() {
252            Some(Operator::FindForward { before }) => {
253                motion::motion(Motion::FindForward { before, text }, cx)
254            }
255            Some(Operator::FindBackward { after }) => {
256                motion::motion(Motion::FindBackward { after, text }, cx)
257            }
258            Some(Operator::Replace) => match Vim::read(cx).state.mode {
259                Mode::Normal => normal_replace(text, cx),
260                Mode::Visual { line } => visual_replace(text, line, cx),
261                _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
262            },
263            _ => {}
264        }
265    }
266
267    fn sync_mode_indicator(cx: &mut AppContext) {
268        cx.spawn(|mut cx| async move {
269            let workspace = match cx.update(|cx| {
270                cx.update_active_window(|cx| {
271                    cx.root_view()
272                        .downcast_ref::<Workspace>()
273                        .map(|workspace| workspace.downgrade())
274                })
275            }) {
276                Some(Some(workspace)) => workspace,
277                _ => {
278                    return Ok(());
279                }
280            };
281
282            workspace.update(&mut cx, |workspace, cx| {
283                Vim::update(cx, |vim, cx| {
284                    workspace.status_bar().update(cx, |status_bar, cx| {
285                        let current_position = status_bar.position_of_item::<ModeIndicator>();
286                        if vim.enabled && current_position.is_none() {
287                            if vim.mode_indicator.is_none() {
288                                vim.mode_indicator =
289                                    Some(cx.add_view(|_| ModeIndicator::new(vim.state.mode)));
290                            };
291                            let mode_indicator = vim.mode_indicator.as_ref().unwrap();
292                            // TODO: would it be better to depend on the diagnostics crate
293                            // so we can pass the type directly?
294                            let position = status_bar.position_of_named_item("DiagnosticIndicator");
295                            if let Some(position) = position {
296                                status_bar.insert_item_after(position, mode_indicator.clone(), cx)
297                            } else {
298                                status_bar.add_left_item(mode_indicator.clone(), cx)
299                            }
300                        } else if !vim.enabled {
301                            if let Some(position) = current_position {
302                                status_bar.remove_item_at(position, cx)
303                            }
304                        }
305                    })
306                })
307            })
308        })
309        .detach_and_log_err(cx);
310    }
311
312    fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
313        if self.enabled != enabled {
314            self.enabled = enabled;
315            self.state = Default::default();
316
317            cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
318                if self.enabled {
319                    filter.filtered_namespaces.remove("vim");
320                } else {
321                    filter.filtered_namespaces.insert("vim");
322                }
323            });
324
325            cx.update_active_window(|cx| {
326                if self.enabled {
327                    let active_editor = cx
328                        .root_view()
329                        .downcast_ref::<Workspace>()
330                        .and_then(|workspace| workspace.read(cx).active_item(cx))
331                        .and_then(|item| item.downcast::<Editor>());
332                    if let Some(active_editor) = active_editor {
333                        self.set_active_editor(active_editor, cx);
334                    }
335                    self.switch_mode(Mode::Normal, false, cx);
336                }
337                self.sync_vim_settings(cx);
338            });
339        }
340    }
341
342    fn sync_vim_settings(&self, cx: &mut WindowContext) {
343        let state = &self.state;
344        let cursor_shape = state.cursor_shape();
345
346        self.update_active_editor(cx, |editor, cx| {
347            if self.enabled && editor.mode() == EditorMode::Full {
348                editor.set_cursor_shape(cursor_shape, cx);
349                editor.set_clip_at_line_ends(state.clip_at_line_end(), cx);
350                editor.set_collapse_matches(true);
351                editor.set_input_enabled(!state.vim_controlled());
352                editor.selections.line_mode = matches!(state.mode, Mode::Visual { line: true });
353                let context_layer = state.keymap_context_layer();
354                editor.set_keymap_context_layer::<Self>(context_layer, cx);
355            } else {
356                // Note: set_collapse_matches is not in unhook_vim_settings, as that method is called on blur,
357                // but we need collapse_matches to persist when the search bar is focused.
358                editor.set_collapse_matches(false);
359                self.unhook_vim_settings(editor, cx);
360            }
361        });
362
363        Vim::sync_mode_indicator(cx);
364    }
365
366    fn unhook_vim_settings(&self, editor: &mut Editor, cx: &mut ViewContext<Editor>) {
367        editor.set_cursor_shape(CursorShape::Bar, cx);
368        editor.set_clip_at_line_ends(false, cx);
369        editor.set_input_enabled(true);
370        editor.selections.line_mode = false;
371
372        // we set the VimEnabled context on all editors so that we
373        // can distinguish between vim mode and non-vim mode in the BufferSearchBar.
374        // This is a bit of a hack, but currently the search crate does not depend on vim,
375        // and it seems nice to keep it that way.
376        if self.enabled {
377            let mut context = KeymapContext::default();
378            context.add_identifier("VimEnabled");
379            editor.set_keymap_context_layer::<Self>(context, cx)
380        } else {
381            editor.remove_keymap_context_layer::<Self>(cx);
382        }
383    }
384}
385
386impl Setting for VimModeSetting {
387    const KEY: Option<&'static str> = Some("vim_mode");
388
389    type FileContent = Option<bool>;
390
391    fn load(
392        default_value: &Self::FileContent,
393        user_values: &[&Self::FileContent],
394        _: &AppContext,
395    ) -> Result<Self> {
396        Ok(Self(user_values.iter().rev().find_map(|v| **v).unwrap_or(
397            default_value.ok_or_else(Self::missing_default)?,
398        )))
399    }
400}
401
402fn local_selections_changed(newest_empty: bool, cx: &mut WindowContext) {
403    Vim::update(cx, |vim, cx| {
404        if vim.enabled && vim.state.mode == Mode::Normal && !newest_empty {
405            vim.switch_mode(Mode::Visual { line: false }, false, cx)
406        }
407    })
408}