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, keymap_matcher::MatchResult, AppContext,
 19    Subscription, ViewContext, 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 result == &MatchResult::Pending {
 97            return true;
 98        }
 99        if let Some(handled_by) = handled_by {
100            // Keystroke is handled by the vim system, so continue forward
101            if handled_by.namespace() == "vim" {
102                return true;
103            }
104        }
105
106        Vim::update(cx, |vim, cx| match vim.active_operator() {
107            Some(
108                Operator::FindForward { .. } | Operator::FindBackward { .. } | Operator::Replace,
109            ) => {}
110            Some(_) => {
111                vim.clear_operator(cx);
112            }
113            _ => {}
114        });
115        true
116    })
117    .detach()
118}
119
120#[derive(Default)]
121pub struct Vim {
122    active_editor: Option<WeakViewHandle<Editor>>,
123    editor_subscription: Option<Subscription>,
124    mode_indicator: Option<ViewHandle<ModeIndicator>>,
125
126    enabled: bool,
127    state: VimState,
128}
129
130impl Vim {
131    fn read(cx: &mut AppContext) -> &Self {
132        cx.default_global()
133    }
134
135    fn update<F, S>(cx: &mut WindowContext, update: F) -> S
136    where
137        F: FnOnce(&mut Self, &mut WindowContext) -> S,
138    {
139        cx.update_default_global(update)
140    }
141
142    fn set_active_editor(&mut self, editor: ViewHandle<Editor>, cx: &mut WindowContext) {
143        self.active_editor = Some(editor.downgrade());
144        self.editor_subscription = Some(cx.subscribe(&editor, |editor, event, cx| match event {
145            Event::SelectionsChanged { local: true } => {
146                let editor = editor.read(cx);
147                if editor.leader_replica_id().is_none() {
148                    let newest_empty = editor.selections.newest::<usize>(cx).is_empty();
149                    local_selections_changed(newest_empty, cx);
150                }
151            }
152            Event::InputIgnored { text } => {
153                Vim::active_editor_input_ignored(text.clone(), cx);
154            }
155            _ => {}
156        }));
157
158        if self.enabled {
159            let editor = editor.read(cx);
160            let editor_mode = editor.mode();
161            let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
162
163            if editor_mode == EditorMode::Full && !newest_selection_empty {
164                self.switch_mode(Mode::Visual { line: false }, true, cx);
165            }
166        }
167
168        self.sync_vim_settings(cx);
169    }
170
171    fn update_active_editor<S>(
172        &self,
173        cx: &mut WindowContext,
174        update: impl FnOnce(&mut Editor, &mut ViewContext<Editor>) -> S,
175    ) -> Option<S> {
176        let editor = self.active_editor.clone()?.upgrade(cx)?;
177        Some(editor.update(cx, update))
178    }
179
180    fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut WindowContext) {
181        self.state.mode = mode;
182        self.state.operator_stack.clear();
183
184        if let Some(mode_indicator) = &self.mode_indicator {
185            mode_indicator.update(cx, |mode_indicator, cx| mode_indicator.set_mode(mode, cx))
186        }
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) -> Option<usize> {
233        if let Some(Operator::Number(number)) = self.active_operator() {
234            self.pop_operator(cx);
235            return Some(number);
236        }
237        None
238    }
239
240    fn clear_operator(&mut self, cx: &mut WindowContext) {
241        self.state.operator_stack.clear();
242        self.sync_vim_settings(cx);
243    }
244
245    fn active_operator(&self) -> Option<Operator> {
246        self.state.operator_stack.last().copied()
247    }
248
249    fn active_editor_input_ignored(text: Arc<str>, cx: &mut WindowContext) {
250        if text.is_empty() {
251            return;
252        }
253
254        match Vim::read(cx).active_operator() {
255            Some(Operator::FindForward { before }) => {
256                let find = Motion::FindForward { before, text };
257                Vim::update(cx, |vim, _| vim.state.last_find = Some(find.clone()));
258                motion::motion(find, cx)
259            }
260            Some(Operator::FindBackward { after }) => {
261                let find = Motion::FindBackward { after, text };
262                Vim::update(cx, |vim, _| vim.state.last_find = Some(find.clone()));
263                motion::motion(find, cx)
264            }
265            Some(Operator::Replace) => match Vim::read(cx).state.mode {
266                Mode::Normal => normal_replace(text, cx),
267                Mode::Visual { line } => visual_replace(text, line, cx),
268                _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
269            },
270            _ => {}
271        }
272    }
273
274    fn sync_mode_indicator(cx: &mut WindowContext) {
275        let Some(workspace) = cx.root_view()
276            .downcast_ref::<Workspace>()
277            .map(|workspace| workspace.downgrade()) else {
278                return;
279            };
280
281        cx.spawn(|mut cx| async move {
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
287                        if vim.enabled && current_position.is_none() {
288                            if vim.mode_indicator.is_none() {
289                                vim.mode_indicator =
290                                    Some(cx.add_view(|_| ModeIndicator::new(vim.state.mode)));
291                            };
292                            let mode_indicator = vim.mode_indicator.as_ref().unwrap();
293                            let position = status_bar
294                                .position_of_item::<language_selector::ActiveBufferLanguage>();
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}