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