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