vim.rs

  1//! Vim support for Zed.
  2
  3#[cfg(test)]
  4mod test;
  5
  6mod command;
  7mod editor_events;
  8mod insert;
  9mod mode_indicator;
 10mod motion;
 11mod normal;
 12mod object;
 13mod replace;
 14mod state;
 15mod surrounds;
 16mod utils;
 17mod visual;
 18
 19use anyhow::Result;
 20use collections::HashMap;
 21use command_palette_hooks::{CommandPaletteFilter, CommandPaletteInterceptor};
 22use editor::{
 23    movement::{self, FindRange},
 24    Editor, EditorEvent, EditorMode,
 25};
 26use gpui::{
 27    actions, impl_actions, Action, AppContext, EntityId, FocusableView, Global, KeystrokeEvent,
 28    Subscription, View, ViewContext, WeakView, WindowContext,
 29};
 30use language::{CursorShape, Point, Selection, SelectionGoal, TransactionId};
 31pub use mode_indicator::ModeIndicator;
 32use motion::Motion;
 33use normal::normal_replace;
 34use replace::multi_replace;
 35use schemars::JsonSchema;
 36use serde::Deserialize;
 37use serde_derive::Serialize;
 38use settings::{update_settings_file, Settings, SettingsStore};
 39use state::{EditorState, Mode, Operator, RecordedSelection, WorkspaceState};
 40use std::{ops::Range, sync::Arc};
 41use surrounds::{add_surrounds, change_surrounds, delete_surrounds};
 42use ui::BorrowAppContext;
 43use visual::{visual_block_motion, visual_replace};
 44use workspace::{self, Workspace};
 45
 46use crate::state::ReplayableAction;
 47
 48/// Whether or not to enable Vim mode (work in progress).
 49///
 50/// Default: false
 51pub struct VimModeSetting(pub bool);
 52
 53/// An Action to Switch between modes
 54#[derive(Clone, Deserialize, PartialEq)]
 55pub struct SwitchMode(pub Mode);
 56
 57/// PushOperator is used to put vim into a "minor" mode,
 58/// where it's waiting for a specific next set of keystrokes.
 59/// For example 'd' needs a motion to complete.
 60#[derive(Clone, Deserialize, PartialEq)]
 61pub struct PushOperator(pub Operator);
 62
 63/// Number is used to manage vim's count. Pushing a digit
 64/// multiplis the current value by 10 and adds the digit.
 65#[derive(Clone, Deserialize, PartialEq)]
 66struct Number(usize);
 67
 68actions!(
 69    vim,
 70    [Tab, Enter, Object, InnerObject, FindForward, FindBackward]
 71);
 72
 73// in the workspace namespace so it's not filtered out when vim is disabled.
 74actions!(workspace, [ToggleVimMode]);
 75
 76impl_actions!(vim, [SwitchMode, PushOperator, Number]);
 77
 78/// Initializes the `vim` crate.
 79pub fn init(cx: &mut AppContext) {
 80    cx.set_global(Vim::default());
 81    VimModeSetting::register(cx);
 82    VimSettings::register(cx);
 83
 84    cx.observe_keystrokes(observe_keystrokes).detach();
 85    editor_events::init(cx);
 86
 87    cx.observe_new_views(|workspace: &mut Workspace, cx| register(workspace, cx))
 88        .detach();
 89
 90    // Any time settings change, update vim mode to match. The Vim struct
 91    // will be initialized as disabled by default, so we filter its commands
 92    // out when starting up.
 93    CommandPaletteFilter::update_global(cx, |filter, _| {
 94        filter.hide_namespace(Vim::NAMESPACE);
 95    });
 96    cx.update_global(|vim: &mut Vim, cx: &mut AppContext| {
 97        vim.set_enabled(VimModeSetting::get_global(cx).0, cx)
 98    });
 99    cx.observe_global::<SettingsStore>(|cx| {
100        cx.update_global(|vim: &mut Vim, cx: &mut AppContext| {
101            vim.set_enabled(VimModeSetting::get_global(cx).0, cx)
102        });
103    })
104    .detach();
105}
106
107fn register(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
108    workspace.register_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {
109        Vim::update(cx, |vim, cx| vim.switch_mode(mode, false, cx))
110    });
111    workspace.register_action(
112        |_: &mut Workspace, PushOperator(operator): &PushOperator, cx| {
113            Vim::update(cx, |vim, cx| vim.push_operator(operator.clone(), cx))
114        },
115    );
116    workspace.register_action(|_: &mut Workspace, n: &Number, cx: _| {
117        Vim::update(cx, |vim, cx| vim.push_count_digit(n.0, cx));
118    });
119
120    workspace.register_action(|_: &mut Workspace, _: &Tab, cx| {
121        Vim::active_editor_input_ignored(" ".into(), cx)
122    });
123
124    workspace.register_action(|_: &mut Workspace, _: &Enter, cx| {
125        Vim::active_editor_input_ignored("\n".into(), cx)
126    });
127
128    workspace.register_action(|workspace: &mut Workspace, _: &ToggleVimMode, cx| {
129        let fs = workspace.app_state().fs.clone();
130        let currently_enabled = VimModeSetting::get_global(cx).0;
131        update_settings_file::<VimModeSetting>(fs, cx, move |setting| {
132            *setting = Some(!currently_enabled)
133        })
134    });
135
136    normal::register(workspace, cx);
137    insert::register(workspace, cx);
138    motion::register(workspace, cx);
139    command::register(workspace, cx);
140    replace::register(workspace, cx);
141    object::register(workspace, cx);
142    visual::register(workspace, cx);
143}
144
145/// Called whenever an keystroke is typed so vim can observe all actions
146/// and keystrokes accordingly.
147fn observe_keystrokes(keystroke_event: &KeystrokeEvent, cx: &mut WindowContext) {
148    if let Some(action) = keystroke_event
149        .action
150        .as_ref()
151        .map(|action| action.boxed_clone())
152    {
153        Vim::update(cx, |vim, _| {
154            if vim.workspace_state.recording {
155                vim.workspace_state
156                    .recorded_actions
157                    .push(ReplayableAction::Action(action.boxed_clone()));
158
159                if vim.workspace_state.stop_recording_after_next_action {
160                    vim.workspace_state.recording = false;
161                    vim.workspace_state.stop_recording_after_next_action = false;
162                }
163            }
164        });
165
166        // Keystroke is handled by the vim system, so continue forward
167        if action.name().starts_with("vim::") {
168            return;
169        }
170    } else if cx.has_pending_keystrokes() {
171        return;
172    }
173
174    Vim::update(cx, |vim, cx| match vim.active_operator() {
175        Some(
176            Operator::FindForward { .. }
177            | Operator::FindBackward { .. }
178            | Operator::Replace
179            | Operator::AddSurrounds { .. }
180            | Operator::ChangeSurrounds { .. }
181            | Operator::DeleteSurrounds,
182        ) => {}
183        Some(_) => {
184            vim.clear_operator(cx);
185        }
186        _ => {}
187    });
188}
189
190/// The state pertaining to Vim mode.
191#[derive(Default)]
192struct Vim {
193    active_editor: Option<WeakView<Editor>>,
194    editor_subscription: Option<Subscription>,
195    enabled: bool,
196    editor_states: HashMap<EntityId, EditorState>,
197    workspace_state: WorkspaceState,
198    default_state: EditorState,
199}
200
201impl Global for Vim {}
202
203impl Vim {
204    /// The namespace for Vim actions.
205    const NAMESPACE: &'static str = "vim";
206
207    fn read(cx: &mut AppContext) -> &Self {
208        cx.global::<Self>()
209    }
210
211    fn update<F, S>(cx: &mut WindowContext, update: F) -> S
212    where
213        F: FnOnce(&mut Self, &mut WindowContext) -> S,
214    {
215        cx.update_global(update)
216    }
217
218    fn activate_editor(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
219        if !editor.read(cx).use_modal_editing() {
220            return;
221        }
222
223        self.active_editor = Some(editor.clone().downgrade());
224        self.editor_subscription = Some(cx.subscribe(&editor, |editor, event, cx| match event {
225            EditorEvent::SelectionsChanged { local: true } => {
226                let editor = editor.read(cx);
227                if editor.leader_peer_id().is_none() {
228                    let newest = editor.selections.newest_anchor().clone();
229                    let is_multicursor = editor.selections.count() > 1;
230                    Vim::update(cx, |vim, cx| {
231                        vim.local_selections_changed(newest, is_multicursor, cx);
232                    })
233                }
234            }
235            EditorEvent::InputIgnored { text } => {
236                Vim::active_editor_input_ignored(text.clone(), cx);
237                Vim::record_insertion(text, None, cx)
238            }
239            EditorEvent::InputHandled {
240                text,
241                utf16_range_to_replace: range_to_replace,
242            } => Vim::record_insertion(text, range_to_replace.clone(), cx),
243            EditorEvent::TransactionBegun { transaction_id } => Vim::update(cx, |vim, cx| {
244                vim.transaction_begun(*transaction_id, cx);
245            }),
246            EditorEvent::TransactionUndone { transaction_id } => Vim::update(cx, |vim, cx| {
247                vim.transaction_undone(transaction_id, cx);
248            }),
249            _ => {}
250        }));
251
252        let editor = editor.read(cx);
253        let editor_mode = editor.mode();
254        let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
255
256        if editor_mode == EditorMode::Full
257                && !newest_selection_empty
258                && self.state().mode == Mode::Normal
259                // When following someone, don't switch vim mode.
260                && editor.leader_peer_id().is_none()
261        {
262            self.switch_mode(Mode::Visual, true, cx);
263        }
264
265        self.sync_vim_settings(cx);
266    }
267
268    fn record_insertion(
269        text: &Arc<str>,
270        range_to_replace: Option<Range<isize>>,
271        cx: &mut WindowContext,
272    ) {
273        Vim::update(cx, |vim, _| {
274            if vim.workspace_state.recording {
275                vim.workspace_state
276                    .recorded_actions
277                    .push(ReplayableAction::Insertion {
278                        text: text.clone(),
279                        utf16_range_to_replace: range_to_replace,
280                    });
281                if vim.workspace_state.stop_recording_after_next_action {
282                    vim.workspace_state.recording = false;
283                    vim.workspace_state.stop_recording_after_next_action = false;
284                }
285            }
286        });
287    }
288
289    fn update_active_editor<S>(
290        &mut self,
291        cx: &mut WindowContext,
292        update: impl FnOnce(&mut Vim, &mut Editor, &mut ViewContext<Editor>) -> S,
293    ) -> Option<S> {
294        let editor = self.active_editor.clone()?.upgrade()?;
295        Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
296    }
297
298    /// When doing an action that modifies the buffer, we start recording so that `.`
299    /// will replay the action.
300    pub fn start_recording(&mut self, cx: &mut WindowContext) {
301        if !self.workspace_state.replaying {
302            self.workspace_state.recording = true;
303            self.workspace_state.recorded_actions = Default::default();
304            self.workspace_state.recorded_count = None;
305
306            let selections = self
307                .active_editor
308                .as_ref()
309                .and_then(|editor| editor.upgrade())
310                .map(|editor| {
311                    let editor = editor.read(cx);
312                    (
313                        editor.selections.oldest::<Point>(cx),
314                        editor.selections.newest::<Point>(cx),
315                    )
316                });
317
318            if let Some((oldest, newest)) = selections {
319                self.workspace_state.recorded_selection = match self.state().mode {
320                    Mode::Visual if newest.end.row == newest.start.row => {
321                        RecordedSelection::SingleLine {
322                            cols: newest.end.column - newest.start.column,
323                        }
324                    }
325                    Mode::Visual => RecordedSelection::Visual {
326                        rows: newest.end.row - newest.start.row,
327                        cols: newest.end.column,
328                    },
329                    Mode::VisualLine => RecordedSelection::VisualLine {
330                        rows: newest.end.row - newest.start.row,
331                    },
332                    Mode::VisualBlock => RecordedSelection::VisualBlock {
333                        rows: newest.end.row.abs_diff(oldest.start.row),
334                        cols: newest.end.column.abs_diff(oldest.start.column),
335                    },
336                    _ => RecordedSelection::None,
337                }
338            } else {
339                self.workspace_state.recorded_selection = RecordedSelection::None;
340            }
341        }
342    }
343
344    pub fn stop_replaying(&mut self) {
345        self.workspace_state.replaying = false;
346    }
347
348    /// When finishing an action that modifies the buffer, stop recording.
349    /// as you usually call this within a keystroke handler we also ensure that
350    /// the current action is recorded.
351    pub fn stop_recording(&mut self) {
352        if self.workspace_state.recording {
353            self.workspace_state.stop_recording_after_next_action = true;
354        }
355    }
356
357    /// Stops recording actions immediately rather than waiting until after the
358    /// next action to stop recording.
359    ///
360    /// This doesn't include the current action.
361    pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>) {
362        if self.workspace_state.recording {
363            self.workspace_state
364                .recorded_actions
365                .push(ReplayableAction::Action(action.boxed_clone()));
366            self.workspace_state.recording = false;
367            self.workspace_state.stop_recording_after_next_action = false;
368        }
369    }
370
371    /// Explicitly record one action (equivalents to start_recording and stop_recording)
372    pub fn record_current_action(&mut self, cx: &mut WindowContext) {
373        self.start_recording(cx);
374        self.stop_recording();
375    }
376
377    fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut WindowContext) {
378        let state = self.state();
379        let last_mode = state.mode;
380        let prior_mode = state.last_mode;
381        let prior_tx = state.current_tx;
382        self.update_state(|state| {
383            state.last_mode = last_mode;
384            state.mode = mode;
385            state.operator_stack.clear();
386            state.current_tx.take();
387            state.current_anchor.take();
388        });
389        if mode != Mode::Insert {
390            self.take_count(cx);
391        }
392
393        // Sync editor settings like clip mode
394        self.sync_vim_settings(cx);
395
396        if leave_selections {
397            return;
398        }
399
400        // Adjust selections
401        self.update_active_editor(cx, |_, editor, cx| {
402            if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
403            {
404                visual_block_motion(true, editor, cx, |_, point, goal| Some((point, goal)))
405            }
406            if last_mode == Mode::Insert || last_mode == Mode::Replace {
407                if let Some(prior_tx) = prior_tx {
408                    editor.group_until_transaction(prior_tx, cx)
409                }
410            }
411
412            editor.change_selections(None, cx, |s| {
413                // we cheat with visual block mode and use multiple cursors.
414                // the cost of this cheat is we need to convert back to a single
415                // cursor whenever vim would.
416                if last_mode == Mode::VisualBlock
417                    && (mode != Mode::VisualBlock && mode != Mode::Insert)
418                {
419                    let tail = s.oldest_anchor().tail();
420                    let head = s.newest_anchor().head();
421                    s.select_anchor_ranges(vec![tail..head]);
422                } else if last_mode == Mode::Insert
423                    && prior_mode == Mode::VisualBlock
424                    && mode != Mode::VisualBlock
425                {
426                    let pos = s.first_anchor().head();
427                    s.select_anchor_ranges(vec![pos..pos])
428                }
429
430                s.move_with(|map, selection| {
431                    if last_mode.is_visual() && !mode.is_visual() {
432                        let mut point = selection.head();
433                        if !selection.reversed && !selection.is_empty() {
434                            point = movement::left(map, selection.head());
435                        }
436                        selection.collapse_to(point, selection.goal)
437                    } else if !last_mode.is_visual() && mode.is_visual() {
438                        if selection.is_empty() {
439                            selection.end = movement::right(map, selection.start);
440                        }
441                    } else if last_mode == Mode::Replace {
442                        if selection.head().column() != 0 {
443                            let point = movement::left(map, selection.head());
444                            selection.collapse_to(point, selection.goal)
445                        }
446                    }
447                });
448            })
449        });
450    }
451
452    fn push_count_digit(&mut self, number: usize, cx: &mut WindowContext) {
453        if self.active_operator().is_some() {
454            self.update_state(|state| {
455                state.post_count = Some(state.post_count.unwrap_or(0) * 10 + number)
456            })
457        } else {
458            self.update_state(|state| {
459                state.pre_count = Some(state.pre_count.unwrap_or(0) * 10 + number)
460            })
461        }
462        // update the keymap so that 0 works
463        self.sync_vim_settings(cx)
464    }
465
466    fn take_count(&mut self, cx: &mut WindowContext) -> Option<usize> {
467        if self.workspace_state.replaying {
468            return self.workspace_state.recorded_count;
469        }
470
471        let count = if self.state().post_count == None && self.state().pre_count == None {
472            return None;
473        } else {
474            Some(self.update_state(|state| {
475                state.post_count.take().unwrap_or(1) * state.pre_count.take().unwrap_or(1)
476            }))
477        };
478        if self.workspace_state.recording {
479            self.workspace_state.recorded_count = count;
480        }
481        self.sync_vim_settings(cx);
482        count
483    }
484
485    fn push_operator(&mut self, operator: Operator, cx: &mut WindowContext) {
486        if matches!(
487            operator,
488            Operator::Change | Operator::Delete | Operator::Replace
489        ) {
490            self.start_recording(cx)
491        };
492        self.update_state(|state| state.operator_stack.push(operator));
493        self.sync_vim_settings(cx);
494    }
495
496    fn maybe_pop_operator(&mut self) -> Option<Operator> {
497        self.update_state(|state| state.operator_stack.pop())
498    }
499
500    fn pop_operator(&mut self, cx: &mut WindowContext) -> Operator {
501        let popped_operator = self.update_state(|state| state.operator_stack.pop())
502            .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
503        self.sync_vim_settings(cx);
504        popped_operator
505    }
506
507    fn clear_operator(&mut self, cx: &mut WindowContext) {
508        self.take_count(cx);
509        self.update_state(|state| state.operator_stack.clear());
510        self.sync_vim_settings(cx);
511    }
512
513    fn active_operator(&self) -> Option<Operator> {
514        self.state().operator_stack.last().cloned()
515    }
516
517    fn transaction_begun(&mut self, transaction_id: TransactionId, _: &mut WindowContext) {
518        self.update_state(|state| {
519            let mode = if (state.mode == Mode::Insert
520                || state.mode == Mode::Replace
521                || state.mode == Mode::Normal)
522                && state.current_tx.is_none()
523            {
524                state.current_tx = Some(transaction_id);
525                state.last_mode
526            } else {
527                state.mode
528            };
529            if mode == Mode::VisualLine || mode == Mode::VisualBlock {
530                state.undo_modes.insert(transaction_id, mode);
531            }
532        });
533    }
534
535    fn transaction_undone(&mut self, transaction_id: &TransactionId, cx: &mut WindowContext) {
536        if !self.state().mode.is_visual() {
537            return;
538        };
539        self.update_active_editor(cx, |vim, editor, cx| {
540            let original_mode = vim.state().undo_modes.get(transaction_id);
541            editor.change_selections(None, cx, |s| match original_mode {
542                Some(Mode::VisualLine) => {
543                    s.move_with(|map, selection| {
544                        selection.collapse_to(
545                            map.prev_line_boundary(selection.start.to_point(map)).1,
546                            SelectionGoal::None,
547                        )
548                    });
549                }
550                Some(Mode::VisualBlock) => {
551                    let mut first = s.first_anchor();
552                    first.collapse_to(first.start, first.goal);
553                    s.select_anchors(vec![first]);
554                }
555                _ => {
556                    s.move_with(|_, selection| {
557                        selection.collapse_to(selection.start, selection.goal);
558                    });
559                }
560            });
561        });
562        self.switch_mode(Mode::Normal, true, cx)
563    }
564
565    fn local_selections_changed(
566        &mut self,
567        newest: Selection<editor::Anchor>,
568        is_multicursor: bool,
569        cx: &mut WindowContext,
570    ) {
571        let state = self.state();
572        if state.mode == Mode::Insert && state.current_tx.is_some() {
573            if state.current_anchor.is_none() {
574                self.update_state(|state| state.current_anchor = Some(newest));
575            } else if state.current_anchor.as_ref().unwrap() != &newest {
576                if let Some(tx_id) = self.update_state(|state| state.current_tx.take()) {
577                    self.update_active_editor(cx, |_, editor, cx| {
578                        editor.group_until_transaction(tx_id, cx)
579                    });
580                }
581            }
582        } else if state.mode == Mode::Normal && newest.start != newest.end {
583            if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
584                self.switch_mode(Mode::VisualBlock, false, cx);
585            } else {
586                self.switch_mode(Mode::Visual, false, cx)
587            }
588        } else if newest.start == newest.end
589            && !is_multicursor
590            && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&state.mode)
591        {
592            self.switch_mode(Mode::Normal, true, cx)
593        }
594    }
595
596    fn active_editor_input_ignored(text: Arc<str>, cx: &mut WindowContext) {
597        if text.is_empty() {
598            return;
599        }
600
601        match Vim::read(cx).active_operator() {
602            Some(Operator::FindForward { before }) => {
603                let find = Motion::FindForward {
604                    before,
605                    char: text.chars().next().unwrap(),
606                    mode: if VimSettings::get_global(cx).use_multiline_find {
607                        FindRange::MultiLine
608                    } else {
609                        FindRange::SingleLine
610                    },
611                    smartcase: VimSettings::get_global(cx).use_smartcase_find,
612                };
613                Vim::update(cx, |vim, _| {
614                    vim.workspace_state.last_find = Some(find.clone())
615                });
616                motion::motion(find, cx)
617            }
618            Some(Operator::FindBackward { after }) => {
619                let find = Motion::FindBackward {
620                    after,
621                    char: text.chars().next().unwrap(),
622                    mode: if VimSettings::get_global(cx).use_multiline_find {
623                        FindRange::MultiLine
624                    } else {
625                        FindRange::SingleLine
626                    },
627                    smartcase: VimSettings::get_global(cx).use_smartcase_find,
628                };
629                Vim::update(cx, |vim, _| {
630                    vim.workspace_state.last_find = Some(find.clone())
631                });
632                motion::motion(find, cx)
633            }
634            Some(Operator::Replace) => match Vim::read(cx).state().mode {
635                Mode::Normal => normal_replace(text, cx),
636                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => visual_replace(text, cx),
637                _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
638            },
639            Some(Operator::AddSurrounds { target }) => match Vim::read(cx).state().mode {
640                Mode::Normal => {
641                    if let Some(target) = target {
642                        add_surrounds(text, target, cx);
643                        Vim::update(cx, |vim, cx| vim.clear_operator(cx));
644                    }
645                }
646                _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
647            },
648            Some(Operator::ChangeSurrounds { target }) => match Vim::read(cx).state().mode {
649                Mode::Normal => {
650                    if let Some(target) = target {
651                        change_surrounds(text, target, cx);
652                        Vim::update(cx, |vim, cx| vim.clear_operator(cx));
653                    }
654                }
655                _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
656            },
657            Some(Operator::DeleteSurrounds) => match Vim::read(cx).state().mode {
658                Mode::Normal => {
659                    delete_surrounds(text, cx);
660                    Vim::update(cx, |vim, cx| vim.clear_operator(cx));
661                }
662                _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
663            },
664            _ => match Vim::read(cx).state().mode {
665                Mode::Replace => multi_replace(text, cx),
666                _ => {}
667            },
668        }
669    }
670
671    fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
672        if self.enabled == enabled {
673            return;
674        }
675        if !enabled {
676            CommandPaletteInterceptor::update_global(cx, |interceptor, _| {
677                interceptor.clear();
678            });
679            CommandPaletteFilter::update_global(cx, |filter, _| {
680                filter.hide_namespace(Self::NAMESPACE);
681            });
682            *self = Default::default();
683            return;
684        }
685
686        self.enabled = true;
687        CommandPaletteFilter::update_global(cx, |filter, _| {
688            filter.show_namespace(Self::NAMESPACE);
689        });
690        CommandPaletteInterceptor::update_global(cx, |interceptor, _| {
691            interceptor.set(Box::new(command::command_interceptor));
692        });
693
694        if let Some(active_window) = cx
695            .active_window()
696            .and_then(|window| window.downcast::<Workspace>())
697        {
698            active_window
699                .update(cx, |workspace, cx| {
700                    let active_editor = workspace.active_item_as::<Editor>(cx);
701                    if let Some(active_editor) = active_editor {
702                        self.activate_editor(active_editor, cx);
703                        self.switch_mode(Mode::Normal, false, cx);
704                    }
705                })
706                .ok();
707        }
708    }
709
710    /// Returns the state of the active editor.
711    pub fn state(&self) -> &EditorState {
712        if let Some(active_editor) = self.active_editor.as_ref() {
713            if let Some(state) = self.editor_states.get(&active_editor.entity_id()) {
714                return state;
715            }
716        }
717
718        &self.default_state
719    }
720
721    /// Updates the state of the active editor.
722    pub fn update_state<T>(&mut self, func: impl FnOnce(&mut EditorState) -> T) -> T {
723        let mut state = self.state().clone();
724        let ret = func(&mut state);
725
726        if let Some(active_editor) = self.active_editor.as_ref() {
727            self.editor_states.insert(active_editor.entity_id(), state);
728        }
729
730        ret
731    }
732
733    fn sync_vim_settings(&mut self, cx: &mut WindowContext) {
734        self.update_active_editor(cx, |vim, editor, cx| {
735            let state = vim.state();
736            editor.set_cursor_shape(state.cursor_shape(), cx);
737            editor.set_clip_at_line_ends(state.clip_at_line_ends(), cx);
738            editor.set_collapse_matches(true);
739            editor.set_input_enabled(!state.vim_controlled());
740            editor.set_autoindent(state.should_autoindent());
741            editor.selections.line_mode = matches!(state.mode, Mode::VisualLine);
742            if editor.is_focused(cx) {
743                editor.set_keymap_context_layer::<Self>(state.keymap_context_layer(), cx);
744            // disables vim if the rename editor is focused,
745            // but not if the command palette is open.
746            } else if editor.focus_handle(cx).contains_focused(cx) {
747                editor.remove_keymap_context_layer::<Self>(cx)
748            }
749        });
750    }
751
752    fn unhook_vim_settings(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
753        if editor.mode() == EditorMode::Full {
754            editor.set_cursor_shape(CursorShape::Bar, cx);
755            editor.set_clip_at_line_ends(false, cx);
756            editor.set_collapse_matches(false);
757            editor.set_input_enabled(true);
758            editor.set_autoindent(true);
759            editor.selections.line_mode = false;
760        }
761        editor.remove_keymap_context_layer::<Self>(cx)
762    }
763}
764
765impl Settings for VimModeSetting {
766    const KEY: Option<&'static str> = Some("vim_mode");
767
768    type FileContent = Option<bool>;
769
770    fn load(
771        default_value: &Self::FileContent,
772        user_values: &[&Self::FileContent],
773        _: &mut AppContext,
774    ) -> Result<Self> {
775        Ok(Self(user_values.iter().rev().find_map(|v| **v).unwrap_or(
776            default_value.ok_or_else(Self::missing_default)?,
777        )))
778    }
779}
780
781/// Controls when to use system clipboard.
782#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
783#[serde(rename_all = "snake_case")]
784pub enum UseSystemClipboard {
785    /// Don't use system clipboard.
786    Never,
787    /// Use system clipboard.
788    Always,
789    /// Use system clipboard for yank operations.
790    OnYank,
791}
792
793#[derive(Deserialize)]
794struct VimSettings {
795    // all vim uses vim clipboard
796    // vim always uses system cliupbaord
797    // some magic where yy is system and dd is not.
798    pub use_system_clipboard: UseSystemClipboard,
799    pub use_multiline_find: bool,
800    pub use_smartcase_find: bool,
801}
802
803#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
804struct VimSettingsContent {
805    pub use_system_clipboard: Option<UseSystemClipboard>,
806    pub use_multiline_find: Option<bool>,
807    pub use_smartcase_find: Option<bool>,
808}
809
810impl Settings for VimSettings {
811    const KEY: Option<&'static str> = Some("vim");
812
813    type FileContent = VimSettingsContent;
814
815    fn load(
816        default_value: &Self::FileContent,
817        user_values: &[&Self::FileContent],
818        _: &mut AppContext,
819    ) -> Result<Self> {
820        Self::load_via_json_merge(default_value, user_values)
821    }
822}