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
 46#[derive(Copy, Clone, Debug)]
 47enum VimEvent {
 48    ModeChanged { mode: Mode },
 49}
 50
 51pub fn init(cx: &mut AppContext) {
 52    settings::register::<VimModeSetting>(cx);
 53
 54    editor_events::init(cx);
 55    normal::init(cx);
 56    visual::init(cx);
 57    insert::init(cx);
 58    object::init(cx);
 59    motion::init(cx);
 60
 61    // Vim Actions
 62    cx.add_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {
 63        Vim::update(cx, |vim, cx| vim.switch_mode(mode, false, cx))
 64    });
 65    cx.add_action(
 66        |_: &mut Workspace, &PushOperator(operator): &PushOperator, cx| {
 67            Vim::update(cx, |vim, cx| vim.push_operator(operator, cx))
 68        },
 69    );
 70    cx.add_action(|_: &mut Workspace, n: &Number, cx: _| {
 71        Vim::update(cx, |vim, cx| vim.push_number(n, cx));
 72    });
 73
 74    cx.add_action(|_: &mut Workspace, _: &Tab, cx| {
 75        Vim::active_editor_input_ignored(" ".into(), cx)
 76    });
 77
 78    cx.add_action(|_: &mut Workspace, _: &Enter, cx| {
 79        Vim::active_editor_input_ignored("\n".into(), cx)
 80    });
 81
 82    // Any time settings change, update vim mode to match. The Vim struct
 83    // will be initialized as disabled by default, so we filter its commands
 84    // out when starting up.
 85    cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
 86        filter.filtered_namespaces.insert("vim");
 87    });
 88    cx.update_default_global(|vim: &mut Vim, cx: &mut AppContext| {
 89        vim.set_enabled(settings::get::<VimModeSetting>(cx).0, cx)
 90    });
 91    cx.observe_global::<SettingsStore, _>(|cx| {
 92        cx.update_default_global(|vim: &mut Vim, cx: &mut AppContext| {
 93            vim.set_enabled(settings::get::<VimModeSetting>(cx).0, 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 result == &MatchResult::Pending {
102            return true;
103        }
104        if let Some(handled_by) = handled_by {
105            // Keystroke is handled by the vim system, so continue forward
106            if handled_by.namespace() == "vim" {
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    enabled: bool,
130    state: VimState,
131}
132
133impl Vim {
134    fn read(cx: &mut AppContext) -> &Self {
135        cx.default_global()
136    }
137
138    fn update<F, S>(cx: &mut WindowContext, update: F) -> S
139    where
140        F: FnOnce(&mut Self, &mut WindowContext) -> S,
141    {
142        cx.update_default_global(update)
143    }
144
145    fn set_active_editor(&mut self, editor: ViewHandle<Editor>, cx: &mut WindowContext) {
146        self.active_editor = Some(editor.downgrade());
147        self.editor_subscription = Some(cx.subscribe(&editor, |editor, event, cx| match event {
148            Event::SelectionsChanged { local: true } => {
149                let editor = editor.read(cx);
150                if editor.leader_replica_id().is_none() {
151                    let newest_empty = editor.selections.newest::<usize>(cx).is_empty();
152                    local_selections_changed(newest_empty, cx);
153                }
154            }
155            Event::InputIgnored { text } => {
156                Vim::active_editor_input_ignored(text.clone(), cx);
157            }
158            _ => {}
159        }));
160
161        if self.enabled {
162            let editor = editor.read(cx);
163            let editor_mode = editor.mode();
164            let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
165
166            if editor_mode == EditorMode::Full && !newest_selection_empty {
167                self.switch_mode(Mode::Visual { line: false }, true, cx);
168            }
169        }
170
171        self.sync_vim_settings(cx);
172    }
173
174    fn update_active_editor<S>(
175        &self,
176        cx: &mut WindowContext,
177        update: impl FnOnce(&mut Editor, &mut ViewContext<Editor>) -> S,
178    ) -> Option<S> {
179        let editor = self.active_editor.clone()?.upgrade(cx)?;
180        Some(editor.update(cx, update))
181    }
182
183    fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut WindowContext) {
184        self.state.mode = mode;
185        self.state.operator_stack.clear();
186
187        cx.emit_global(VimEvent::ModeChanged { mode });
188
189        // Sync editor settings like clip mode
190        self.sync_vim_settings(cx);
191
192        if leave_selections {
193            return;
194        }
195
196        // Adjust selections
197        self.update_active_editor(cx, |editor, cx| {
198            editor.change_selections(None, cx, |s| {
199                s.move_with(|map, selection| {
200                    if self.state.empty_selections_only() {
201                        let new_head = map.clip_point(selection.head(), Bias::Left);
202                        selection.collapse_to(new_head, selection.goal)
203                    } else {
204                        selection
205                            .set_head(map.clip_point(selection.head(), Bias::Left), selection.goal);
206                    }
207                });
208            })
209        });
210    }
211
212    fn push_operator(&mut self, operator: Operator, cx: &mut WindowContext) {
213        self.state.operator_stack.push(operator);
214        self.sync_vim_settings(cx);
215    }
216
217    fn push_number(&mut self, Number(number): &Number, cx: &mut WindowContext) {
218        if let Some(Operator::Number(current_number)) = self.active_operator() {
219            self.pop_operator(cx);
220            self.push_operator(Operator::Number(current_number * 10 + *number as usize), cx);
221        } else {
222            self.push_operator(Operator::Number(*number as usize), cx);
223        }
224    }
225
226    fn pop_operator(&mut self, cx: &mut WindowContext) -> Operator {
227        let popped_operator = self.state.operator_stack.pop()
228            .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
229        self.sync_vim_settings(cx);
230        popped_operator
231    }
232
233    fn pop_number_operator(&mut self, cx: &mut WindowContext) -> Option<usize> {
234        if let Some(Operator::Number(number)) = self.active_operator() {
235            self.pop_operator(cx);
236            return Some(number);
237        }
238        None
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                let find = Motion::FindForward { before, text };
258                Vim::update(cx, |vim, _| vim.state.last_find = Some(find.clone()));
259                motion::motion(find, cx)
260            }
261            Some(Operator::FindBackward { after }) => {
262                let find = Motion::FindBackward { after, text };
263                Vim::update(cx, |vim, _| vim.state.last_find = Some(find.clone()));
264                motion::motion(find, cx)
265            }
266            Some(Operator::Replace) => match Vim::read(cx).state.mode {
267                Mode::Normal => normal_replace(text, cx),
268                Mode::Visual { line } => visual_replace(text, line, cx),
269                _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
270            },
271            _ => {}
272        }
273    }
274
275    fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
276        if self.enabled != enabled {
277            self.enabled = enabled;
278            self.state = Default::default();
279
280            cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
281                if self.enabled {
282                    filter.filtered_namespaces.remove("vim");
283                } else {
284                    filter.filtered_namespaces.insert("vim");
285                }
286            });
287
288            cx.update_active_window(|cx| {
289                if self.enabled {
290                    let active_editor = cx
291                        .root_view()
292                        .downcast_ref::<Workspace>()
293                        .and_then(|workspace| workspace.read(cx).active_item(cx))
294                        .and_then(|item| item.downcast::<Editor>());
295                    if let Some(active_editor) = active_editor {
296                        self.set_active_editor(active_editor, cx);
297                    }
298                    self.switch_mode(Mode::Normal, false, cx);
299                }
300                self.sync_vim_settings(cx);
301            });
302        }
303    }
304
305    fn sync_vim_settings(&self, cx: &mut WindowContext) {
306        let state = &self.state;
307        let cursor_shape = state.cursor_shape();
308
309        self.update_active_editor(cx, |editor, cx| {
310            if self.enabled && editor.mode() == EditorMode::Full {
311                editor.set_cursor_shape(cursor_shape, cx);
312                editor.set_clip_at_line_ends(state.clip_at_line_end(), cx);
313                editor.set_collapse_matches(true);
314                editor.set_input_enabled(!state.vim_controlled());
315                editor.selections.line_mode = matches!(state.mode, Mode::Visual { line: true });
316                let context_layer = state.keymap_context_layer();
317                editor.set_keymap_context_layer::<Self>(context_layer, cx);
318            } else {
319                // Note: set_collapse_matches is not in unhook_vim_settings, as that method is called on blur,
320                // but we need collapse_matches to persist when the search bar is focused.
321                editor.set_collapse_matches(false);
322                self.unhook_vim_settings(editor, cx);
323            }
324        });
325    }
326
327    fn unhook_vim_settings(&self, editor: &mut Editor, cx: &mut ViewContext<Editor>) {
328        editor.set_cursor_shape(CursorShape::Bar, cx);
329        editor.set_clip_at_line_ends(false, cx);
330        editor.set_input_enabled(true);
331        editor.selections.line_mode = false;
332
333        // we set the VimEnabled context on all editors so that we
334        // can distinguish between vim mode and non-vim mode in the BufferSearchBar.
335        // This is a bit of a hack, but currently the search crate does not depend on vim,
336        // and it seems nice to keep it that way.
337        if self.enabled {
338            let mut context = KeymapContext::default();
339            context.add_identifier("VimEnabled");
340            editor.set_keymap_context_layer::<Self>(context, cx)
341        } else {
342            editor.remove_keymap_context_layer::<Self>(cx);
343        }
344    }
345}
346
347impl Setting for VimModeSetting {
348    const KEY: Option<&'static str> = Some("vim_mode");
349
350    type FileContent = Option<bool>;
351
352    fn load(
353        default_value: &Self::FileContent,
354        user_values: &[&Self::FileContent],
355        _: &AppContext,
356    ) -> Result<Self> {
357        Ok(Self(user_values.iter().rev().find_map(|v| **v).unwrap_or(
358            default_value.ok_or_else(Self::missing_default)?,
359        )))
360    }
361}
362
363fn local_selections_changed(newest_empty: bool, cx: &mut WindowContext) {
364    Vim::update(cx, |vim, cx| {
365        if vim.enabled && vim.state.mode == Mode::Normal && !newest_empty {
366            vim.switch_mode(Mode::Visual { line: false }, false, cx)
367        }
368    })
369}