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