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 anyhow::Result;
 14use collections::CommandPaletteFilter;
 15use editor::{Bias, Editor, EditorMode, Event};
 16use gpui::{
 17    actions, impl_actions, AppContext, Subscription, ViewContext, ViewHandle, WeakViewHandle,
 18    WindowContext,
 19};
 20use language::CursorShape;
 21use motion::Motion;
 22use normal::normal_replace;
 23use serde::Deserialize;
 24use settings::{Setting, SettingsStore};
 25use state::{Mode, Operator, VimState};
 26use std::sync::Arc;
 27use visual::visual_replace;
 28use workspace::{self, Workspace};
 29
 30struct VimModeSetting(bool);
 31
 32#[derive(Clone, Deserialize, PartialEq)]
 33pub struct SwitchMode(pub Mode);
 34
 35#[derive(Clone, Deserialize, PartialEq)]
 36pub struct PushOperator(pub Operator);
 37
 38#[derive(Clone, Deserialize, PartialEq)]
 39struct Number(u8);
 40
 41actions!(vim, [Tab, Enter]);
 42impl_actions!(vim, [Number, SwitchMode, PushOperator]);
 43
 44pub fn init(cx: &mut AppContext) {
 45    settings::register::<VimModeSetting>(cx);
 46
 47    editor_events::init(cx);
 48    normal::init(cx);
 49    visual::init(cx);
 50    insert::init(cx);
 51    object::init(cx);
 52    motion::init(cx);
 53
 54    // Vim Actions
 55    cx.add_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {
 56        Vim::update(cx, |vim, cx| vim.switch_mode(mode, false, cx))
 57    });
 58    cx.add_action(
 59        |_: &mut Workspace, &PushOperator(operator): &PushOperator, cx| {
 60            Vim::update(cx, |vim, cx| vim.push_operator(operator, cx))
 61        },
 62    );
 63    cx.add_action(|_: &mut Workspace, n: &Number, cx: _| {
 64        Vim::update(cx, |vim, cx| vim.push_number(n, cx));
 65    });
 66
 67    cx.add_action(|_: &mut Workspace, _: &Tab, cx| {
 68        Vim::active_editor_input_ignored(" ".into(), cx)
 69    });
 70
 71    cx.add_action(|_: &mut Workspace, _: &Enter, cx| {
 72        Vim::active_editor_input_ignored("\n".into(), cx)
 73    });
 74
 75    // Any time settings change, update vim mode to match. The Vim struct
 76    // will be initialized as disabled by default, so we filter its commands
 77    // out when starting up.
 78    cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
 79        filter.filtered_namespaces.insert("vim");
 80    });
 81    cx.update_default_global(|vim: &mut Vim, cx: &mut AppContext| {
 82        vim.set_enabled(settings::get::<VimModeSetting>(cx).0, cx)
 83    });
 84    cx.observe_global::<SettingsStore, _>(|cx| {
 85        cx.update_default_global(|vim: &mut Vim, cx: &mut AppContext| {
 86            vim.set_enabled(settings::get::<VimModeSetting>(cx).0, cx)
 87        });
 88    })
 89    .detach();
 90}
 91
 92pub fn observe_keystrokes(cx: &mut WindowContext) {
 93    cx.observe_keystrokes(|_keystroke, _result, handled_by, cx| {
 94        if let Some(handled_by) = handled_by {
 95            // Keystroke is handled by the vim system, so continue forward
 96            if handled_by.namespace() == "vim" {
 97                return true;
 98            }
 99        }
100
101        Vim::update(cx, |vim, cx| match vim.active_operator() {
102            Some(
103                Operator::FindForward { .. } | Operator::FindBackward { .. } | Operator::Replace,
104            ) => {}
105            Some(_) => {
106                vim.clear_operator(cx);
107            }
108            _ => {}
109        });
110        true
111    })
112    .detach()
113}
114
115#[derive(Default)]
116pub struct Vim {
117    active_editor: Option<WeakViewHandle<Editor>>,
118    editor_subscription: Option<Subscription>,
119
120    enabled: bool,
121    state: VimState,
122}
123
124impl Vim {
125    fn read(cx: &mut AppContext) -> &Self {
126        cx.default_global()
127    }
128
129    fn update<F, S>(cx: &mut WindowContext, update: F) -> S
130    where
131        F: FnOnce(&mut Self, &mut WindowContext) -> S,
132    {
133        cx.update_default_global(update)
134    }
135
136    fn set_active_editor(&mut self, editor: ViewHandle<Editor>, cx: &mut WindowContext) {
137        self.active_editor = Some(editor.downgrade());
138        self.editor_subscription = Some(cx.subscribe(&editor, |editor, event, cx| match event {
139            Event::SelectionsChanged { local: true } => {
140                let editor = editor.read(cx);
141                if editor.leader_replica_id().is_none() {
142                    let newest_empty = editor.selections.newest::<usize>(cx).is_empty();
143                    local_selections_changed(newest_empty, cx);
144                }
145            }
146            Event::InputIgnored { text } => {
147                Vim::active_editor_input_ignored(text.clone(), cx);
148            }
149            _ => {}
150        }));
151
152        if self.enabled {
153            let editor = editor.read(cx);
154            let editor_mode = editor.mode();
155            let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
156
157            if editor_mode == EditorMode::Full && !newest_selection_empty {
158                self.switch_mode(Mode::Visual { line: false }, true, cx);
159            }
160        }
161
162        self.sync_vim_settings(cx);
163    }
164
165    fn update_active_editor<S>(
166        &self,
167        cx: &mut WindowContext,
168        update: impl FnOnce(&mut Editor, &mut ViewContext<Editor>) -> S,
169    ) -> Option<S> {
170        let editor = self.active_editor.clone()?.upgrade(cx)?;
171        Some(editor.update(cx, update))
172    }
173
174    fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut WindowContext) {
175        self.state.mode = mode;
176        self.state.operator_stack.clear();
177
178        // Sync editor settings like clip mode
179        self.sync_vim_settings(cx);
180
181        if leave_selections {
182            return;
183        }
184
185        // Adjust selections
186        self.update_active_editor(cx, |editor, cx| {
187            editor.change_selections(None, cx, |s| {
188                s.move_with(|map, selection| {
189                    if self.state.empty_selections_only() {
190                        let new_head = map.clip_point(selection.head(), Bias::Left);
191                        selection.collapse_to(new_head, selection.goal)
192                    } else {
193                        selection
194                            .set_head(map.clip_point(selection.head(), Bias::Left), selection.goal);
195                    }
196                });
197            })
198        });
199    }
200
201    fn push_operator(&mut self, operator: Operator, cx: &mut WindowContext) {
202        self.state.operator_stack.push(operator);
203        self.sync_vim_settings(cx);
204    }
205
206    fn push_number(&mut self, Number(number): &Number, cx: &mut WindowContext) {
207        if let Some(Operator::Number(current_number)) = self.active_operator() {
208            self.pop_operator(cx);
209            self.push_operator(Operator::Number(current_number * 10 + *number as usize), cx);
210        } else {
211            self.push_operator(Operator::Number(*number as usize), cx);
212        }
213    }
214
215    fn pop_operator(&mut self, cx: &mut WindowContext) -> Operator {
216        let popped_operator = self.state.operator_stack.pop()
217            .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
218        self.sync_vim_settings(cx);
219        popped_operator
220    }
221
222    fn pop_number_operator(&mut self, cx: &mut WindowContext) -> Option<usize> {
223        if let Some(Operator::Number(number)) = self.active_operator() {
224            self.pop_operator(cx);
225            return Some(number);
226        }
227        None
228    }
229
230    fn clear_operator(&mut self, cx: &mut WindowContext) {
231        self.state.operator_stack.clear();
232        self.sync_vim_settings(cx);
233    }
234
235    fn active_operator(&self) -> Option<Operator> {
236        self.state.operator_stack.last().copied()
237    }
238
239    fn active_editor_input_ignored(text: Arc<str>, cx: &mut WindowContext) {
240        if text.is_empty() {
241            return;
242        }
243
244        match Vim::read(cx).active_operator() {
245            Some(Operator::FindForward { before }) => {
246                motion::motion(Motion::FindForward { before, text }, cx)
247            }
248            Some(Operator::FindBackward { after }) => {
249                motion::motion(Motion::FindBackward { after, text }, cx)
250            }
251            Some(Operator::Replace) => match Vim::read(cx).state.mode {
252                Mode::Normal => normal_replace(text, cx),
253                Mode::Visual { line } => visual_replace(text, line, cx),
254                _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
255            },
256            _ => {}
257        }
258    }
259
260    fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
261        if self.enabled != enabled {
262            self.enabled = enabled;
263            self.state = Default::default();
264
265            cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
266                if self.enabled {
267                    filter.filtered_namespaces.remove("vim");
268                } else {
269                    filter.filtered_namespaces.insert("vim");
270                }
271            });
272
273            cx.update_active_window(|cx| {
274                if self.enabled {
275                    let active_editor = cx
276                        .root_view()
277                        .downcast_ref::<Workspace>()
278                        .and_then(|workspace| workspace.read(cx).active_item(cx))
279                        .and_then(|item| item.downcast::<Editor>());
280                    if let Some(active_editor) = active_editor {
281                        self.set_active_editor(active_editor, cx);
282                    }
283                    self.switch_mode(Mode::Normal, false, cx);
284                }
285                self.sync_vim_settings(cx);
286            });
287        }
288    }
289
290    fn sync_vim_settings(&self, cx: &mut WindowContext) {
291        let state = &self.state;
292        let cursor_shape = state.cursor_shape();
293
294        self.update_active_editor(cx, |editor, cx| {
295            if self.enabled && editor.mode() == EditorMode::Full {
296                editor.set_cursor_shape(cursor_shape, cx);
297                editor.set_clip_at_line_ends(state.clip_at_line_end(), cx);
298                editor.set_collapse_matches(true);
299                editor.set_input_enabled(!state.vim_controlled());
300                editor.selections.line_mode = matches!(state.mode, Mode::Visual { line: true });
301                let context_layer = state.keymap_context_layer();
302                editor.set_keymap_context_layer::<Self>(context_layer, cx);
303            } else {
304                // Note: set_collapse_matches is not in unhook_vim_settings, as that method is called on blur,
305                // but we need collapse_matches to persist when the search bar is focused.
306                editor.set_collapse_matches(false);
307                Self::unhook_vim_settings(editor, cx);
308            }
309        });
310    }
311
312    fn unhook_vim_settings(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
313        editor.set_cursor_shape(CursorShape::Bar, cx);
314        editor.set_clip_at_line_ends(false, cx);
315        editor.set_input_enabled(true);
316        editor.selections.line_mode = false;
317        editor.remove_keymap_context_layer::<Self>(cx);
318    }
319}
320
321impl Setting for VimModeSetting {
322    const KEY: Option<&'static str> = Some("vim_mode");
323
324    type FileContent = Option<bool>;
325
326    fn load(
327        default_value: &Self::FileContent,
328        user_values: &[&Self::FileContent],
329        _: &AppContext,
330    ) -> Result<Self> {
331        Ok(Self(user_values.iter().rev().find_map(|v| **v).unwrap_or(
332            default_value.ok_or_else(Self::missing_default)?,
333        )))
334    }
335}
336
337fn local_selections_changed(newest_empty: bool, cx: &mut WindowContext) {
338    Vim::update(cx, |vim, cx| {
339        if vim.enabled && vim.state.mode == Mode::Normal && !newest_empty {
340            vim.switch_mode(Mode::Visual { line: false }, false, cx)
341        }
342    })
343}