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::{movement, 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_block_motion, 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, 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        let last_mode = self.state.mode;
185        let prior_mode = self.state.last_mode;
186        self.state.last_mode = last_mode;
187        self.state.mode = mode;
188        self.state.operator_stack.clear();
189
190        cx.emit_global(VimEvent::ModeChanged { mode });
191
192        // Sync editor settings like clip mode
193        self.sync_vim_settings(cx);
194
195        if leave_selections {
196            return;
197        }
198
199        // Adjust selections
200        self.update_active_editor(cx, |editor, cx| {
201            if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
202            {
203                visual_block_motion(true, editor, cx, |_, point, goal| Some((point, goal)))
204            }
205
206            editor.change_selections(None, cx, |s| {
207                // we cheat with visual block mode and use multiple cursors.
208                // the cost of this cheat is we need to convert back to a single
209                // cursor whenever vim would.
210                if last_mode == Mode::VisualBlock && mode != Mode::VisualBlock {
211                    let tail = s.oldest_anchor().tail();
212                    let head = s.newest_anchor().head();
213                    s.select_anchor_ranges(vec![tail..head]);
214                } else if last_mode == Mode::Insert
215                    && prior_mode == Mode::VisualBlock
216                    && mode != Mode::VisualBlock
217                {
218                    let pos = s.first_anchor().head();
219                    s.select_anchor_ranges(vec![pos..pos])
220                }
221
222                s.move_with(|map, selection| {
223                    if last_mode.is_visual() && !mode.is_visual() {
224                        let mut point = selection.head();
225                        if !selection.reversed {
226                            point = movement::left(map, selection.head());
227                        }
228                        selection.collapse_to(point, selection.goal)
229                    } else if !last_mode.is_visual() && mode.is_visual() {
230                        if selection.is_empty() {
231                            selection.end = movement::right(map, selection.start);
232                        }
233                    }
234                });
235            })
236        });
237    }
238
239    fn push_operator(&mut self, operator: Operator, cx: &mut WindowContext) {
240        self.state.operator_stack.push(operator);
241        self.sync_vim_settings(cx);
242    }
243
244    fn push_number(&mut self, Number(number): &Number, cx: &mut WindowContext) {
245        if let Some(Operator::Number(current_number)) = self.active_operator() {
246            self.pop_operator(cx);
247            self.push_operator(Operator::Number(current_number * 10 + *number as usize), cx);
248        } else {
249            self.push_operator(Operator::Number(*number as usize), cx);
250        }
251    }
252
253    fn pop_operator(&mut self, cx: &mut WindowContext) -> Operator {
254        let popped_operator = self.state.operator_stack.pop()
255            .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
256        self.sync_vim_settings(cx);
257        popped_operator
258    }
259
260    fn pop_number_operator(&mut self, cx: &mut WindowContext) -> Option<usize> {
261        if let Some(Operator::Number(number)) = self.active_operator() {
262            self.pop_operator(cx);
263            return Some(number);
264        }
265        None
266    }
267
268    fn clear_operator(&mut self, cx: &mut WindowContext) {
269        self.state.operator_stack.clear();
270        self.sync_vim_settings(cx);
271    }
272
273    fn active_operator(&self) -> Option<Operator> {
274        self.state.operator_stack.last().copied()
275    }
276
277    fn active_editor_input_ignored(text: Arc<str>, cx: &mut WindowContext) {
278        if text.is_empty() {
279            return;
280        }
281
282        match Vim::read(cx).active_operator() {
283            Some(Operator::FindForward { before }) => {
284                let find = Motion::FindForward { before, text };
285                Vim::update(cx, |vim, _| vim.state.last_find = Some(find.clone()));
286                motion::motion(find, cx)
287            }
288            Some(Operator::FindBackward { after }) => {
289                let find = Motion::FindBackward { after, text };
290                Vim::update(cx, |vim, _| vim.state.last_find = Some(find.clone()));
291                motion::motion(find, cx)
292            }
293            Some(Operator::Replace) => match Vim::read(cx).state.mode {
294                Mode::Normal => normal_replace(text, cx),
295                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => visual_replace(text, cx),
296                _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
297            },
298            _ => {}
299        }
300    }
301
302    fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
303        if self.enabled != enabled {
304            self.enabled = enabled;
305            self.state = Default::default();
306
307            cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
308                if self.enabled {
309                    filter.filtered_namespaces.remove("vim");
310                } else {
311                    filter.filtered_namespaces.insert("vim");
312                }
313            });
314
315            cx.update_active_window(|cx| {
316                if self.enabled {
317                    let active_editor = cx
318                        .root_view()
319                        .downcast_ref::<Workspace>()
320                        .and_then(|workspace| workspace.read(cx).active_item(cx))
321                        .and_then(|item| item.downcast::<Editor>());
322                    if let Some(active_editor) = active_editor {
323                        self.set_active_editor(active_editor, cx);
324                    }
325                    self.switch_mode(Mode::Normal, false, cx);
326                }
327                self.sync_vim_settings(cx);
328            });
329        }
330    }
331
332    fn sync_vim_settings(&self, cx: &mut WindowContext) {
333        let state = &self.state;
334        let cursor_shape = state.cursor_shape();
335
336        self.update_active_editor(cx, |editor, cx| {
337            if self.enabled && editor.mode() == EditorMode::Full {
338                editor.set_cursor_shape(cursor_shape, cx);
339                editor.set_clip_at_line_ends(state.clip_at_line_ends(), cx);
340                editor.set_collapse_matches(true);
341                editor.set_input_enabled(!state.vim_controlled());
342                editor.selections.line_mode = matches!(state.mode, Mode::VisualLine);
343                let context_layer = state.keymap_context_layer();
344                editor.set_keymap_context_layer::<Self>(context_layer, cx);
345            } else {
346                // Note: set_collapse_matches is not in unhook_vim_settings, as that method is called on blur,
347                // but we need collapse_matches to persist when the search bar is focused.
348                editor.set_collapse_matches(false);
349                self.unhook_vim_settings(editor, cx);
350            }
351        });
352    }
353
354    fn unhook_vim_settings(&self, editor: &mut Editor, cx: &mut ViewContext<Editor>) {
355        editor.set_cursor_shape(CursorShape::Bar, cx);
356        editor.set_clip_at_line_ends(false, cx);
357        editor.set_input_enabled(true);
358        editor.selections.line_mode = false;
359
360        // we set the VimEnabled context on all editors so that we
361        // can distinguish between vim mode and non-vim mode in the BufferSearchBar.
362        // This is a bit of a hack, but currently the search crate does not depend on vim,
363        // and it seems nice to keep it that way.
364        if self.enabled {
365            let mut context = KeymapContext::default();
366            context.add_identifier("VimEnabled");
367            editor.set_keymap_context_layer::<Self>(context, cx)
368        } else {
369            editor.remove_keymap_context_layer::<Self>(cx);
370        }
371    }
372}
373
374impl Setting for VimModeSetting {
375    const KEY: Option<&'static str> = Some("vim_mode");
376
377    type FileContent = Option<bool>;
378
379    fn load(
380        default_value: &Self::FileContent,
381        user_values: &[&Self::FileContent],
382        _: &AppContext,
383    ) -> Result<Self> {
384        Ok(Self(user_values.iter().rev().find_map(|v| **v).unwrap_or(
385            default_value.ok_or_else(Self::missing_default)?,
386        )))
387    }
388}
389
390fn local_selections_changed(newest_empty: bool, cx: &mut WindowContext) {
391    Vim::update(cx, |vim, cx| {
392        if vim.enabled && vim.state.mode == Mode::Normal && !newest_empty {
393            vim.switch_mode(Mode::Visual, false, cx)
394        }
395    })
396}