vim.rs

  1#[cfg(test)]
  2mod test;
  3
  4mod command;
  5mod editor_events;
  6mod insert;
  7mod mode_indicator;
  8mod motion;
  9mod normal;
 10mod object;
 11mod state;
 12mod utils;
 13mod visual;
 14
 15use anyhow::Result;
 16use collections::{CommandPaletteFilter, HashMap};
 17use command_palette::CommandPaletteInterceptor;
 18use editor::{movement, Editor, EditorEvent, EditorMode};
 19use gpui::{
 20    actions, impl_actions, Action, AppContext, EntityId, KeyContext, Subscription, View,
 21    ViewContext, WeakView, WindowContext,
 22};
 23use language::{CursorShape, Point, Selection, SelectionGoal};
 24pub use mode_indicator::ModeIndicator;
 25use motion::Motion;
 26use normal::normal_replace;
 27use serde::Deserialize;
 28use settings::{update_settings_file, Settings, SettingsStore};
 29use state::{EditorState, Mode, Operator, RecordedSelection, WorkspaceState};
 30use std::{ops::Range, sync::Arc};
 31use visual::{visual_block_motion, visual_replace};
 32use workspace::{self, Workspace};
 33
 34use crate::state::ReplayableAction;
 35
 36pub struct VimModeSetting(pub bool);
 37
 38#[derive(Clone, Deserialize, PartialEq)]
 39pub struct SwitchMode(pub Mode);
 40
 41#[derive(Clone, Deserialize, PartialEq)]
 42pub struct PushOperator(pub Operator);
 43
 44#[derive(Clone, Deserialize, PartialEq)]
 45struct Number(usize);
 46
 47actions!(
 48    vim,
 49    [Tab, Enter, Object, InnerObject, FindForward, FindBackward]
 50);
 51// in the workspace namespace so it's not filtered out when vim is disabled.
 52actions!(workspace, [ToggleVimMode]);
 53
 54impl_actions!(vim, [SwitchMode, PushOperator, Number]);
 55
 56pub fn init(cx: &mut AppContext) {
 57    cx.set_global(Vim::default());
 58    VimModeSetting::register(cx);
 59
 60    editor_events::init(cx);
 61
 62    cx.observe_new_views(|workspace: &mut Workspace, cx| register(workspace, cx))
 63        .detach();
 64
 65    // Any time settings change, update vim mode to match. The Vim struct
 66    // will be initialized as disabled by default, so we filter its commands
 67    // out when starting up.
 68    cx.update_global::<CommandPaletteFilter, _>(|filter, _| {
 69        filter.hidden_namespaces.insert("vim");
 70    });
 71    cx.update_global(|vim: &mut Vim, cx: &mut AppContext| {
 72        vim.set_enabled(VimModeSetting::get_global(cx).0, cx)
 73    });
 74    cx.observe_global::<SettingsStore>(|cx| {
 75        cx.update_global(|vim: &mut Vim, cx: &mut AppContext| {
 76            vim.set_enabled(VimModeSetting::get_global(cx).0, cx)
 77        });
 78    })
 79    .detach();
 80}
 81
 82fn register(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
 83    workspace.register_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {
 84        Vim::update(cx, |vim, cx| vim.switch_mode(mode, false, cx))
 85    });
 86    workspace.register_action(
 87        |_: &mut Workspace, &PushOperator(operator): &PushOperator, cx| {
 88            Vim::update(cx, |vim, cx| vim.push_operator(operator, cx))
 89        },
 90    );
 91    workspace.register_action(|_: &mut Workspace, n: &Number, cx: _| {
 92        Vim::update(cx, |vim, cx| vim.push_count_digit(n.0, cx));
 93    });
 94
 95    workspace.register_action(|_: &mut Workspace, _: &Tab, cx| {
 96        Vim::active_editor_input_ignored(" ".into(), cx)
 97    });
 98
 99    workspace.register_action(|_: &mut Workspace, _: &Enter, cx| {
100        Vim::active_editor_input_ignored("\n".into(), cx)
101    });
102
103    workspace.register_action(|workspace: &mut Workspace, _: &ToggleVimMode, cx| {
104        let fs = workspace.app_state().fs.clone();
105        let currently_enabled = VimModeSetting::get_global(cx).0;
106        update_settings_file::<VimModeSetting>(fs, cx, move |setting| {
107            *setting = Some(!currently_enabled)
108        })
109    });
110
111    normal::register(workspace, cx);
112    insert::register(workspace, cx);
113    motion::register(workspace, cx);
114    command::register(workspace, cx);
115    object::register(workspace, cx);
116    visual::register(workspace, cx);
117}
118
119pub fn observe_keystrokes(_: &mut WindowContext) {
120    // todo!()
121
122    // cx.observe_keystrokes(|_keystroke, result, handled_by, cx| {
123    //     if result == &MatchResult::Pending {
124    //         return true;
125    //     }
126    //     if let Some(handled_by) = handled_by {
127    //         Vim::update(cx, |vim, _| {
128    //             if vim.workspace_state.recording {
129    //                 vim.workspace_state
130    //                     .recorded_actions
131    //                     .push(ReplayableAction::Action(handled_by.boxed_clone()));
132
133    //                 if vim.workspace_state.stop_recording_after_next_action {
134    //                     vim.workspace_state.recording = false;
135    //                     vim.workspace_state.stop_recording_after_next_action = false;
136    //                 }
137    //             }
138    //         });
139
140    //         // Keystroke is handled by the vim system, so continue forward
141    //         if handled_by.namespace() == "vim" {
142    //             return true;
143    //         }
144    //     }
145
146    //     Vim::update(cx, |vim, cx| match vim.active_operator() {
147    //         Some(
148    //             Operator::FindForward { .. } | Operator::FindBackward { .. } | Operator::Replace,
149    //         ) => {}
150    //         Some(_) => {
151    //             vim.clear_operator(cx);
152    //         }
153    //         _ => {}
154    //     });
155    //     true
156    // })
157    // .detach()
158}
159
160#[derive(Default)]
161pub struct Vim {
162    active_editor: Option<WeakView<Editor>>,
163    editor_subscription: Option<Subscription>,
164    enabled: bool,
165    editor_states: HashMap<EntityId, EditorState>,
166    workspace_state: WorkspaceState,
167    default_state: EditorState,
168}
169
170impl Vim {
171    fn read(cx: &mut AppContext) -> &Self {
172        cx.global::<Self>()
173    }
174
175    fn update<F, S>(cx: &mut WindowContext, update: F) -> S
176    where
177        F: FnOnce(&mut Self, &mut WindowContext) -> S,
178    {
179        cx.update_global(update)
180    }
181
182    fn set_active_editor(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
183        self.active_editor = Some(editor.clone().downgrade());
184        self.editor_subscription = Some(cx.subscribe(&editor, |editor, event, cx| match event {
185            EditorEvent::SelectionsChanged { local: true } => {
186                let editor = editor.read(cx);
187                if editor.leader_peer_id().is_none() {
188                    let newest = editor.selections.newest::<usize>(cx);
189                    local_selections_changed(newest, cx);
190                }
191            }
192            EditorEvent::InputIgnored { text } => {
193                Vim::active_editor_input_ignored(text.clone(), cx);
194                Vim::record_insertion(text, None, cx)
195            }
196            EditorEvent::InputHandled {
197                text,
198                utf16_range_to_replace: range_to_replace,
199            } => Vim::record_insertion(text, range_to_replace.clone(), cx),
200            _ => {}
201        }));
202
203        if self.enabled {
204            let editor = editor.read(cx);
205            let editor_mode = editor.mode();
206            let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
207
208            if editor_mode == EditorMode::Full
209                && !newest_selection_empty
210                && self.state().mode == Mode::Normal
211                // When following someone, don't switch vim mode.
212                && editor.leader_peer_id().is_none()
213            {
214                self.switch_mode(Mode::Visual, true, cx);
215            }
216        }
217
218        self.sync_vim_settings(cx);
219    }
220
221    fn record_insertion(
222        text: &Arc<str>,
223        range_to_replace: Option<Range<isize>>,
224        cx: &mut WindowContext,
225    ) {
226        Vim::update(cx, |vim, _| {
227            if vim.workspace_state.recording {
228                vim.workspace_state
229                    .recorded_actions
230                    .push(ReplayableAction::Insertion {
231                        text: text.clone(),
232                        utf16_range_to_replace: range_to_replace,
233                    });
234                if vim.workspace_state.stop_recording_after_next_action {
235                    vim.workspace_state.recording = false;
236                    vim.workspace_state.stop_recording_after_next_action = false;
237                }
238            }
239        });
240    }
241
242    fn update_active_editor<S>(
243        &self,
244        cx: &mut WindowContext,
245        update: impl FnOnce(&mut Editor, &mut ViewContext<Editor>) -> S,
246    ) -> Option<S> {
247        let editor = self.active_editor.clone()?.upgrade()?;
248        Some(editor.update(cx, update))
249    }
250
251    pub fn start_recording(&mut self, cx: &mut WindowContext) {
252        if !self.workspace_state.replaying {
253            self.workspace_state.recording = true;
254            self.workspace_state.recorded_actions = Default::default();
255            self.workspace_state.recorded_count = None;
256
257            let selections = self
258                .active_editor
259                .as_ref()
260                .and_then(|editor| editor.upgrade())
261                .map(|editor| {
262                    let editor = editor.read(cx);
263                    (
264                        editor.selections.oldest::<Point>(cx),
265                        editor.selections.newest::<Point>(cx),
266                    )
267                });
268
269            if let Some((oldest, newest)) = selections {
270                self.workspace_state.recorded_selection = match self.state().mode {
271                    Mode::Visual if newest.end.row == newest.start.row => {
272                        RecordedSelection::SingleLine {
273                            cols: newest.end.column - newest.start.column,
274                        }
275                    }
276                    Mode::Visual => RecordedSelection::Visual {
277                        rows: newest.end.row - newest.start.row,
278                        cols: newest.end.column,
279                    },
280                    Mode::VisualLine => RecordedSelection::VisualLine {
281                        rows: newest.end.row - newest.start.row,
282                    },
283                    Mode::VisualBlock => RecordedSelection::VisualBlock {
284                        rows: newest.end.row.abs_diff(oldest.start.row),
285                        cols: newest.end.column.abs_diff(oldest.start.column),
286                    },
287                    _ => RecordedSelection::None,
288                }
289            } else {
290                self.workspace_state.recorded_selection = RecordedSelection::None;
291            }
292        }
293    }
294
295    pub fn stop_recording(&mut self) {
296        if self.workspace_state.recording {
297            self.workspace_state.stop_recording_after_next_action = true;
298        }
299    }
300
301    pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>) {
302        if self.workspace_state.recording {
303            self.workspace_state
304                .recorded_actions
305                .push(ReplayableAction::Action(action.boxed_clone()));
306            self.workspace_state.recording = false;
307            self.workspace_state.stop_recording_after_next_action = false;
308        }
309    }
310
311    pub fn record_current_action(&mut self, cx: &mut WindowContext) {
312        self.start_recording(cx);
313        self.stop_recording();
314    }
315
316    fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut WindowContext) {
317        let state = self.state();
318        let last_mode = state.mode;
319        let prior_mode = state.last_mode;
320        self.update_state(|state| {
321            state.last_mode = last_mode;
322            state.mode = mode;
323            state.operator_stack.clear();
324        });
325        if mode != Mode::Insert {
326            self.take_count(cx);
327        }
328
329        // todo!()
330        // cx.emit_global(VimEvent::ModeChanged { mode });
331
332        // Sync editor settings like clip mode
333        self.sync_vim_settings(cx);
334
335        if leave_selections {
336            return;
337        }
338
339        // Adjust selections
340        self.update_active_editor(cx, |editor, cx| {
341            if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
342            {
343                visual_block_motion(true, editor, cx, |_, point, goal| Some((point, goal)))
344            }
345
346            editor.change_selections(None, cx, |s| {
347                // we cheat with visual block mode and use multiple cursors.
348                // the cost of this cheat is we need to convert back to a single
349                // cursor whenever vim would.
350                if last_mode == Mode::VisualBlock
351                    && (mode != Mode::VisualBlock && mode != Mode::Insert)
352                {
353                    let tail = s.oldest_anchor().tail();
354                    let head = s.newest_anchor().head();
355                    s.select_anchor_ranges(vec![tail..head]);
356                } else if last_mode == Mode::Insert
357                    && prior_mode == Mode::VisualBlock
358                    && mode != Mode::VisualBlock
359                {
360                    let pos = s.first_anchor().head();
361                    s.select_anchor_ranges(vec![pos..pos])
362                }
363
364                s.move_with(|map, selection| {
365                    if last_mode.is_visual() && !mode.is_visual() {
366                        let mut point = selection.head();
367                        if !selection.reversed && !selection.is_empty() {
368                            point = movement::left(map, selection.head());
369                        }
370                        selection.collapse_to(point, selection.goal)
371                    } else if !last_mode.is_visual() && mode.is_visual() {
372                        if selection.is_empty() {
373                            selection.end = movement::right(map, selection.start);
374                        }
375                    }
376                });
377            })
378        });
379    }
380
381    fn push_count_digit(&mut self, number: usize, cx: &mut WindowContext) {
382        if self.active_operator().is_some() {
383            self.update_state(|state| {
384                state.post_count = Some(state.post_count.unwrap_or(0) * 10 + number)
385            })
386        } else {
387            self.update_state(|state| {
388                state.pre_count = Some(state.pre_count.unwrap_or(0) * 10 + number)
389            })
390        }
391        // update the keymap so that 0 works
392        self.sync_vim_settings(cx)
393    }
394
395    fn take_count(&mut self, cx: &mut WindowContext) -> Option<usize> {
396        if self.workspace_state.replaying {
397            return self.workspace_state.recorded_count;
398        }
399
400        let count = if self.state().post_count == None && self.state().pre_count == None {
401            return None;
402        } else {
403            Some(self.update_state(|state| {
404                state.post_count.take().unwrap_or(1) * state.pre_count.take().unwrap_or(1)
405            }))
406        };
407        if self.workspace_state.recording {
408            self.workspace_state.recorded_count = count;
409        }
410        self.sync_vim_settings(cx);
411        count
412    }
413
414    fn push_operator(&mut self, operator: Operator, cx: &mut WindowContext) {
415        if matches!(
416            operator,
417            Operator::Change | Operator::Delete | Operator::Replace
418        ) {
419            self.start_recording(cx)
420        };
421        self.update_state(|state| state.operator_stack.push(operator));
422        self.sync_vim_settings(cx);
423    }
424
425    fn maybe_pop_operator(&mut self) -> Option<Operator> {
426        self.update_state(|state| state.operator_stack.pop())
427    }
428
429    fn pop_operator(&mut self, cx: &mut WindowContext) -> Operator {
430        let popped_operator = self.update_state( |state| state.operator_stack.pop()
431        )            .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
432        self.sync_vim_settings(cx);
433        popped_operator
434    }
435    fn clear_operator(&mut self, cx: &mut WindowContext) {
436        self.take_count(cx);
437        self.update_state(|state| state.operator_stack.clear());
438        self.sync_vim_settings(cx);
439    }
440
441    fn active_operator(&self) -> Option<Operator> {
442        self.state().operator_stack.last().copied()
443    }
444
445    fn active_editor_input_ignored(text: Arc<str>, cx: &mut WindowContext) {
446        if text.is_empty() {
447            return;
448        }
449
450        match Vim::read(cx).active_operator() {
451            Some(Operator::FindForward { before }) => {
452                let find = Motion::FindForward {
453                    before,
454                    char: text.chars().next().unwrap(),
455                };
456                Vim::update(cx, |vim, _| {
457                    vim.workspace_state.last_find = Some(find.clone())
458                });
459                motion::motion(find, cx)
460            }
461            Some(Operator::FindBackward { after }) => {
462                let find = Motion::FindBackward {
463                    after,
464                    char: text.chars().next().unwrap(),
465                };
466                Vim::update(cx, |vim, _| {
467                    vim.workspace_state.last_find = Some(find.clone())
468                });
469                motion::motion(find, cx)
470            }
471            Some(Operator::Replace) => match Vim::read(cx).state().mode {
472                Mode::Normal => normal_replace(text, cx),
473                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => visual_replace(text, cx),
474                _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
475            },
476            _ => {}
477        }
478    }
479
480    fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
481        if self.enabled != enabled {
482            self.enabled = enabled;
483
484            cx.update_global::<CommandPaletteFilter, _>(|filter, _| {
485                if self.enabled {
486                    filter.hidden_namespaces.remove("vim");
487                } else {
488                    filter.hidden_namespaces.insert("vim");
489                }
490            });
491
492            if self.enabled {
493                cx.set_global::<CommandPaletteInterceptor>(Box::new(command::command_interceptor));
494            } else if cx.has_global::<CommandPaletteInterceptor>() {
495                let _ = cx.remove_global::<CommandPaletteInterceptor>();
496            }
497
498            // todo!();
499            // cx.update_active_window(|cx| {
500            //     if self.enabled {
501            //         let active_editor = cx
502            //             .root_view()
503            //             .downcast_ref::<Workspace>()
504            //             .and_then(|workspace| workspace.read(cx).active_item(cx))
505            //             .and_then(|item| item.downcast::<Editor>());
506            //         if let Some(active_editor) = active_editor {
507            //             self.set_active_editor(active_editor, cx);
508            //         }
509            //         self.switch_mode(Mode::Normal, false, cx);
510            //     }
511            //     self.sync_vim_settings(cx);
512            // });
513        }
514    }
515
516    pub fn state(&self) -> &EditorState {
517        if let Some(active_editor) = self.active_editor.as_ref() {
518            if let Some(state) = self.editor_states.get(&active_editor.entity_id()) {
519                return state;
520            }
521        }
522
523        &self.default_state
524    }
525
526    pub fn update_state<T>(&mut self, func: impl FnOnce(&mut EditorState) -> T) -> T {
527        let mut state = self.state().clone();
528        let ret = func(&mut state);
529
530        if let Some(active_editor) = self.active_editor.as_ref() {
531            self.editor_states.insert(active_editor.entity_id(), state);
532        }
533
534        ret
535    }
536
537    fn sync_vim_settings(&self, cx: &mut WindowContext) {
538        let state = self.state();
539        let cursor_shape = state.cursor_shape();
540
541        self.update_active_editor(cx, |editor, cx| {
542            if self.enabled && editor.mode() == EditorMode::Full {
543                editor.set_cursor_shape(cursor_shape, cx);
544                editor.set_clip_at_line_ends(state.clip_at_line_ends(), cx);
545                editor.set_collapse_matches(true);
546                editor.set_input_enabled(!state.vim_controlled());
547                editor.set_autoindent(state.should_autoindent());
548                editor.selections.line_mode = matches!(state.mode, Mode::VisualLine);
549                let context_layer = state.keymap_context_layer();
550                editor.set_keymap_context_layer::<Self>(context_layer, cx);
551            } else {
552                // Note: set_collapse_matches is not in unhook_vim_settings, as that method is called on blur,
553                // but we need collapse_matches to persist when the search bar is focused.
554                editor.set_collapse_matches(false);
555                self.unhook_vim_settings(editor, cx);
556            }
557        });
558    }
559
560    fn unhook_vim_settings(&self, editor: &mut Editor, cx: &mut ViewContext<Editor>) {
561        editor.set_cursor_shape(CursorShape::Bar, cx);
562        editor.set_clip_at_line_ends(false, cx);
563        editor.set_input_enabled(true);
564        editor.set_autoindent(true);
565        editor.selections.line_mode = false;
566
567        // we set the VimEnabled context on all editors so that we
568        // can distinguish between vim mode and non-vim mode in the BufferSearchBar.
569        // This is a bit of a hack, but currently the search crate does not depend on vim,
570        // and it seems nice to keep it that way.
571        if self.enabled {
572            let mut context = KeyContext::default();
573            context.add("VimEnabled");
574            editor.set_keymap_context_layer::<Self>(context, cx)
575        } else {
576            editor.remove_keymap_context_layer::<Self>(cx);
577        }
578    }
579}
580
581impl Settings for VimModeSetting {
582    const KEY: Option<&'static str> = Some("vim_mode");
583
584    type FileContent = Option<bool>;
585
586    fn load(
587        default_value: &Self::FileContent,
588        user_values: &[&Self::FileContent],
589        _: &mut AppContext,
590    ) -> Result<Self> {
591        Ok(Self(user_values.iter().rev().find_map(|v| **v).unwrap_or(
592            default_value.ok_or_else(Self::missing_default)?,
593        )))
594    }
595}
596
597fn local_selections_changed(newest: Selection<usize>, cx: &mut WindowContext) {
598    Vim::update(cx, |vim, cx| {
599        if vim.enabled && vim.state().mode == Mode::Normal && !newest.is_empty() {
600            if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
601                vim.switch_mode(Mode::VisualBlock, false, cx);
602            } else {
603                vim.switch_mode(Mode::Visual, false, cx)
604            }
605        }
606    })
607}