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