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