vim.rs

   1//! Vim support for Zed.
   2
   3#[cfg(test)]
   4mod test;
   5
   6mod change_list;
   7mod command;
   8mod digraph;
   9mod insert;
  10mod mode_indicator;
  11mod motion;
  12mod normal;
  13mod object;
  14mod replace;
  15mod state;
  16mod surrounds;
  17mod visual;
  18
  19use anyhow::Result;
  20use collections::HashMap;
  21use editor::{
  22    movement::{self, FindRange},
  23    Anchor, Bias, Editor, EditorEvent, EditorMode, ToPoint,
  24};
  25use gpui::{
  26    actions, impl_actions, Action, AppContext, Entity, EventEmitter, KeyContext, KeystrokeEvent,
  27    Render, Subscription, View, ViewContext, WeakView,
  28};
  29use insert::NormalBefore;
  30use language::{CursorShape, Point, Selection, SelectionGoal, TransactionId};
  31pub use mode_indicator::ModeIndicator;
  32use motion::Motion;
  33use normal::search::SearchSubmit;
  34use schemars::JsonSchema;
  35use serde::Deserialize;
  36use serde_derive::Serialize;
  37use settings::{update_settings_file, Settings, SettingsSources, SettingsStore};
  38use state::{Mode, Operator, RecordedSelection, SearchState, VimGlobals};
  39use std::{ops::Range, sync::Arc};
  40use surrounds::SurroundsType;
  41use ui::{IntoElement, VisualContext};
  42use workspace::{self, Pane, Workspace};
  43
  44use crate::state::ReplayableAction;
  45
  46/// Whether or not to enable Vim mode.
  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
  66#[derive(Clone, Deserialize, PartialEq)]
  67struct SelectRegister(String);
  68
  69actions!(
  70    vim,
  71    [
  72        ClearOperators,
  73        Tab,
  74        Enter,
  75        Object,
  76        InnerObject,
  77        FindForward,
  78        FindBackward,
  79        OpenDefaultKeymap
  80    ]
  81);
  82
  83// in the workspace namespace so it's not filtered out when vim is disabled.
  84actions!(workspace, [ToggleVimMode]);
  85
  86impl_actions!(vim, [SwitchMode, PushOperator, Number, SelectRegister]);
  87
  88/// Initializes the `vim` crate.
  89pub fn init(cx: &mut AppContext) {
  90    VimModeSetting::register(cx);
  91    VimSettings::register(cx);
  92    VimGlobals::register(cx);
  93
  94    cx.observe_new_views(|editor: &mut Editor, cx| Vim::register(editor, cx))
  95        .detach();
  96
  97    cx.observe_new_views(|workspace: &mut Workspace, _| {
  98        workspace.register_action(|workspace, _: &ToggleVimMode, cx| {
  99            let fs = workspace.app_state().fs.clone();
 100            let currently_enabled = Vim::enabled(cx);
 101            update_settings_file::<VimModeSetting>(fs, cx, move |setting, _| {
 102                *setting = Some(!currently_enabled)
 103            })
 104        });
 105
 106        workspace.register_action(|_, _: &OpenDefaultKeymap, cx| {
 107            cx.emit(workspace::Event::OpenBundledFile {
 108                text: settings::vim_keymap(),
 109                title: "Default Vim Bindings",
 110                language: "JSON",
 111            });
 112        });
 113
 114        workspace.register_action(|workspace, _: &SearchSubmit, cx| {
 115            let Some(vim) = workspace
 116                .active_item_as::<Editor>(cx)
 117                .and_then(|editor| editor.read(cx).addon::<VimAddon>().cloned())
 118            else {
 119                return;
 120            };
 121            vim.view
 122                .update(cx, |_, cx| cx.defer(|vim, cx| vim.search_submit(cx)))
 123        });
 124    })
 125    .detach();
 126}
 127
 128#[derive(Clone)]
 129pub(crate) struct VimAddon {
 130    pub(crate) view: View<Vim>,
 131}
 132
 133impl editor::Addon for VimAddon {
 134    fn extend_key_context(&self, key_context: &mut KeyContext, cx: &AppContext) {
 135        self.view.read(cx).extend_key_context(key_context)
 136    }
 137
 138    fn to_any(&self) -> &dyn std::any::Any {
 139        self
 140    }
 141}
 142
 143/// The state pertaining to Vim mode.
 144pub(crate) struct Vim {
 145    pub(crate) mode: Mode,
 146    pub last_mode: Mode,
 147
 148    /// pre_count is the number before an operator is specified (3 in 3d2d)
 149    pre_count: Option<usize>,
 150    /// post_count is the number after an operator is specified (2 in 3d2d)
 151    post_count: Option<usize>,
 152
 153    operator_stack: Vec<Operator>,
 154    pub(crate) replacements: Vec<(Range<editor::Anchor>, String)>,
 155
 156    pub(crate) marks: HashMap<String, Vec<Anchor>>,
 157    pub(crate) stored_visual_mode: Option<(Mode, Vec<bool>)>,
 158    pub(crate) change_list: Vec<Vec<Anchor>>,
 159    pub(crate) change_list_position: Option<usize>,
 160
 161    pub(crate) current_tx: Option<TransactionId>,
 162    pub(crate) current_anchor: Option<Selection<Anchor>>,
 163    pub(crate) undo_modes: HashMap<TransactionId, Mode>,
 164
 165    selected_register: Option<char>,
 166    pub search: SearchState,
 167
 168    editor: WeakView<Editor>,
 169
 170    _subscriptions: Vec<Subscription>,
 171}
 172
 173// Hack: Vim intercepts events dispatched to a window and updates the view in response.
 174// This means it needs a VisualContext. The easiest way to satisfy that constraint is
 175// to make Vim a "View" that is just never actually rendered.
 176impl Render for Vim {
 177    fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
 178        gpui::Empty
 179    }
 180}
 181
 182enum VimEvent {
 183    Focused,
 184}
 185impl EventEmitter<VimEvent> for Vim {}
 186
 187impl Vim {
 188    /// The namespace for Vim actions.
 189    const NAMESPACE: &'static str = "vim";
 190
 191    pub fn new(cx: &mut ViewContext<Editor>) -> View<Self> {
 192        let editor = cx.view().clone();
 193
 194        cx.new_view(|cx| Vim {
 195            mode: Mode::Normal,
 196            last_mode: Mode::Normal,
 197            pre_count: None,
 198            post_count: None,
 199            operator_stack: Vec::new(),
 200            replacements: Vec::new(),
 201
 202            marks: HashMap::default(),
 203            stored_visual_mode: None,
 204            change_list: Vec::new(),
 205            change_list_position: None,
 206            current_tx: None,
 207            current_anchor: None,
 208            undo_modes: HashMap::default(),
 209
 210            selected_register: None,
 211            search: SearchState::default(),
 212
 213            editor: editor.downgrade(),
 214            _subscriptions: vec![
 215                cx.observe_keystrokes(Self::observe_keystrokes),
 216                cx.subscribe(&editor, |this, _, event, cx| {
 217                    this.handle_editor_event(event, cx)
 218                }),
 219            ],
 220        })
 221    }
 222
 223    fn register(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
 224        if !editor.use_modal_editing() {
 225            return;
 226        }
 227
 228        let mut was_enabled = Vim::enabled(cx);
 229        let mut was_toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;
 230        cx.observe_global::<SettingsStore>(move |editor, cx| {
 231            let enabled = Vim::enabled(cx);
 232            let toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;
 233            if enabled && was_enabled && (toggle != was_toggle) {
 234                if toggle {
 235                    let is_relative = editor
 236                        .addon::<VimAddon>()
 237                        .map(|vim| vim.view.read(cx).mode != Mode::Insert);
 238                    editor.set_relative_line_number(is_relative, cx)
 239                } else {
 240                    editor.set_relative_line_number(None, cx)
 241                }
 242            }
 243            was_toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;
 244            if was_enabled == enabled {
 245                return;
 246            }
 247            was_enabled = enabled;
 248            if enabled {
 249                Self::activate(editor, cx)
 250            } else {
 251                Self::deactivate(editor, cx)
 252            }
 253        })
 254        .detach();
 255        if was_enabled {
 256            Self::activate(editor, cx)
 257        }
 258    }
 259
 260    fn activate(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
 261        let vim = Vim::new(cx);
 262
 263        editor.register_addon(VimAddon { view: vim.clone() });
 264
 265        vim.update(cx, |_, cx| {
 266            Vim::action(editor, cx, |vim, action: &SwitchMode, cx| {
 267                vim.switch_mode(action.0, false, cx)
 268            });
 269
 270            Vim::action(editor, cx, |vim, action: &PushOperator, cx| {
 271                vim.push_operator(action.0.clone(), cx)
 272            });
 273
 274            Vim::action(editor, cx, |vim, _: &ClearOperators, cx| {
 275                vim.clear_operator(cx)
 276            });
 277            Vim::action(editor, cx, |vim, n: &Number, cx| {
 278                vim.push_count_digit(n.0, cx);
 279            });
 280            Vim::action(editor, cx, |vim, _: &Tab, cx| {
 281                vim.input_ignored(" ".into(), cx)
 282            });
 283            Vim::action(editor, cx, |vim, _: &Enter, cx| {
 284                vim.input_ignored("\n".into(), cx)
 285            });
 286
 287            normal::register(editor, cx);
 288            insert::register(editor, cx);
 289            motion::register(editor, cx);
 290            command::register(editor, cx);
 291            replace::register(editor, cx);
 292            object::register(editor, cx);
 293            visual::register(editor, cx);
 294            change_list::register(editor, cx);
 295
 296            cx.defer(|vim, cx| {
 297                vim.focused(false, cx);
 298            })
 299        })
 300    }
 301
 302    fn deactivate(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
 303        editor.set_cursor_shape(CursorShape::Bar, cx);
 304        editor.set_clip_at_line_ends(false, cx);
 305        editor.set_collapse_matches(false);
 306        editor.set_input_enabled(true);
 307        editor.set_autoindent(true);
 308        editor.selections.line_mode = false;
 309        editor.unregister_addon::<VimAddon>();
 310        editor.set_relative_line_number(None, cx);
 311        if let Some(vim) = Vim::globals(cx).focused_vim() {
 312            if vim.entity_id() == cx.view().entity_id() {
 313                Vim::globals(cx).focused_vim = None;
 314            }
 315        }
 316    }
 317
 318    /// Register an action on the editor.
 319    pub fn action<A: Action>(
 320        editor: &mut Editor,
 321        cx: &mut ViewContext<Vim>,
 322        f: impl Fn(&mut Vim, &A, &mut ViewContext<Vim>) + 'static,
 323    ) {
 324        let subscription = editor.register_action(cx.listener(f));
 325        cx.on_release(|_, _, _| drop(subscription)).detach();
 326    }
 327
 328    pub fn editor(&self) -> Option<View<Editor>> {
 329        self.editor.upgrade()
 330    }
 331
 332    pub fn workspace(&self, cx: &ViewContext<Self>) -> Option<View<Workspace>> {
 333        self.editor().and_then(|editor| editor.read(cx).workspace())
 334    }
 335
 336    pub fn pane(&self, cx: &ViewContext<Self>) -> Option<View<Pane>> {
 337        self.workspace(cx)
 338            .and_then(|workspace| workspace.read(cx).pane_for(&self.editor()?))
 339    }
 340
 341    pub fn enabled(cx: &mut AppContext) -> bool {
 342        VimModeSetting::get_global(cx).0
 343    }
 344
 345    /// Called whenever an keystroke is typed so vim can observe all actions
 346    /// and keystrokes accordingly.
 347    fn observe_keystrokes(&mut self, keystroke_event: &KeystrokeEvent, cx: &mut ViewContext<Self>) {
 348        if let Some(action) = keystroke_event.action.as_ref() {
 349            // Keystroke is handled by the vim system, so continue forward
 350            if action.name().starts_with("vim::") {
 351                return;
 352            }
 353        } else if cx.has_pending_keystrokes() || keystroke_event.keystroke.is_ime_in_progress() {
 354            return;
 355        }
 356
 357        if let Some(operator) = self.active_operator() {
 358            if !operator.is_waiting(self.mode) {
 359                self.clear_operator(cx);
 360                self.stop_recording_immediately(Box::new(ClearOperators), cx)
 361            }
 362        }
 363    }
 364
 365    fn handle_editor_event(&mut self, event: &EditorEvent, cx: &mut ViewContext<Self>) {
 366        match event {
 367            EditorEvent::Focused => self.focused(true, cx),
 368            EditorEvent::Blurred => self.blurred(cx),
 369            EditorEvent::SelectionsChanged { local: true } => {
 370                self.local_selections_changed(cx);
 371            }
 372            EditorEvent::InputIgnored { text } => {
 373                self.input_ignored(text.clone(), cx);
 374                Vim::globals(cx).observe_insertion(text, None)
 375            }
 376            EditorEvent::InputHandled {
 377                text,
 378                utf16_range_to_replace: range_to_replace,
 379            } => Vim::globals(cx).observe_insertion(text, range_to_replace.clone()),
 380            EditorEvent::TransactionBegun { transaction_id } => {
 381                self.transaction_begun(*transaction_id, cx)
 382            }
 383            EditorEvent::TransactionUndone { transaction_id } => {
 384                self.transaction_undone(transaction_id, cx)
 385            }
 386            EditorEvent::Edited { .. } => self.push_to_change_list(cx),
 387            EditorEvent::FocusedIn => self.sync_vim_settings(cx),
 388            _ => {}
 389        }
 390    }
 391
 392    fn push_operator(&mut self, operator: Operator, cx: &mut ViewContext<Self>) {
 393        if matches!(
 394            operator,
 395            Operator::Change
 396                | Operator::Delete
 397                | Operator::Replace
 398                | Operator::Indent
 399                | Operator::Outdent
 400                | Operator::Lowercase
 401                | Operator::Uppercase
 402                | Operator::OppositeCase
 403                | Operator::ToggleComments
 404        ) {
 405            self.start_recording(cx)
 406        };
 407        // Since these operations can only be entered with pre-operators,
 408        // we need to clear the previous operators when pushing,
 409        // so that the current stack is the most correct
 410        if matches!(
 411            operator,
 412            Operator::AddSurrounds { .. }
 413                | Operator::ChangeSurrounds { .. }
 414                | Operator::DeleteSurrounds
 415        ) {
 416            self.operator_stack.clear();
 417            if let Operator::AddSurrounds { target: None } = operator {
 418                self.start_recording(cx);
 419            }
 420        };
 421        self.operator_stack.push(operator);
 422        self.sync_vim_settings(cx);
 423    }
 424
 425    pub fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut ViewContext<Self>) {
 426        let last_mode = self.mode;
 427        let prior_mode = self.last_mode;
 428        let prior_tx = self.current_tx;
 429        self.last_mode = last_mode;
 430        self.mode = mode;
 431        self.operator_stack.clear();
 432        self.selected_register.take();
 433        if mode == Mode::Normal || mode != last_mode {
 434            self.current_tx.take();
 435            self.current_anchor.take();
 436        }
 437        if mode != Mode::Insert && mode != Mode::Replace {
 438            self.take_count(cx);
 439        }
 440
 441        // Sync editor settings like clip mode
 442        self.sync_vim_settings(cx);
 443
 444        if VimSettings::get_global(cx).toggle_relative_line_numbers {
 445            if self.mode != self.last_mode {
 446                if self.mode == Mode::Insert || self.last_mode == Mode::Insert {
 447                    self.update_editor(cx, |vim, editor, cx| {
 448                        let is_relative = vim.mode != Mode::Insert;
 449                        editor.set_relative_line_number(Some(is_relative), cx)
 450                    });
 451                }
 452            }
 453        }
 454
 455        if leave_selections {
 456            return;
 457        }
 458
 459        if !mode.is_visual() && last_mode.is_visual() {
 460            self.create_visual_marks(last_mode, cx);
 461        }
 462
 463        // Adjust selections
 464        self.update_editor(cx, |vim, editor, cx| {
 465            if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
 466            {
 467                vim.visual_block_motion(true, editor, cx, |_, point, goal| Some((point, goal)))
 468            }
 469            if last_mode == Mode::Insert || last_mode == Mode::Replace {
 470                if let Some(prior_tx) = prior_tx {
 471                    editor.group_until_transaction(prior_tx, cx)
 472                }
 473            }
 474
 475            editor.change_selections(None, cx, |s| {
 476                // we cheat with visual block mode and use multiple cursors.
 477                // the cost of this cheat is we need to convert back to a single
 478                // cursor whenever vim would.
 479                if last_mode == Mode::VisualBlock
 480                    && (mode != Mode::VisualBlock && mode != Mode::Insert)
 481                {
 482                    let tail = s.oldest_anchor().tail();
 483                    let head = s.newest_anchor().head();
 484                    s.select_anchor_ranges(vec![tail..head]);
 485                } else if last_mode == Mode::Insert
 486                    && prior_mode == Mode::VisualBlock
 487                    && mode != Mode::VisualBlock
 488                {
 489                    let pos = s.first_anchor().head();
 490                    s.select_anchor_ranges(vec![pos..pos])
 491                }
 492
 493                let snapshot = s.display_map();
 494                if let Some(pending) = s.pending.as_mut() {
 495                    if pending.selection.reversed && mode.is_visual() && !last_mode.is_visual() {
 496                        let mut end = pending.selection.end.to_point(&snapshot.buffer_snapshot);
 497                        end = snapshot
 498                            .buffer_snapshot
 499                            .clip_point(end + Point::new(0, 1), Bias::Right);
 500                        pending.selection.end = snapshot.buffer_snapshot.anchor_before(end);
 501                    }
 502                }
 503
 504                s.move_with(|map, selection| {
 505                    if last_mode.is_visual() && !mode.is_visual() {
 506                        let mut point = selection.head();
 507                        if !selection.reversed && !selection.is_empty() {
 508                            point = movement::left(map, selection.head());
 509                        }
 510                        selection.collapse_to(point, selection.goal)
 511                    } else if !last_mode.is_visual() && mode.is_visual() {
 512                        if selection.is_empty() {
 513                            selection.end = movement::right(map, selection.start);
 514                        }
 515                    }
 516                });
 517            })
 518        });
 519    }
 520
 521    fn take_count(&mut self, cx: &mut ViewContext<Self>) -> Option<usize> {
 522        let global_state = cx.global_mut::<VimGlobals>();
 523        if global_state.dot_replaying {
 524            return global_state.recorded_count;
 525        }
 526
 527        let count = if self.post_count == None && self.pre_count == None {
 528            return None;
 529        } else {
 530            Some(self.post_count.take().unwrap_or(1) * self.pre_count.take().unwrap_or(1))
 531        };
 532
 533        if global_state.dot_recording {
 534            global_state.recorded_count = count;
 535        }
 536        self.sync_vim_settings(cx);
 537        count
 538    }
 539
 540    pub fn cursor_shape(&self) -> CursorShape {
 541        match self.mode {
 542            Mode::Normal => {
 543                if self.operator_stack.is_empty() {
 544                    CursorShape::Block
 545                } else {
 546                    CursorShape::Underscore
 547                }
 548            }
 549            Mode::Replace => CursorShape::Underscore,
 550            Mode::Visual | Mode::VisualLine | Mode::VisualBlock => CursorShape::Block,
 551            Mode::Insert => CursorShape::Bar,
 552        }
 553    }
 554
 555    pub fn editor_input_enabled(&self) -> bool {
 556        match self.mode {
 557            Mode::Insert => {
 558                if let Some(operator) = self.operator_stack.last() {
 559                    !operator.is_waiting(self.mode)
 560                } else {
 561                    true
 562                }
 563            }
 564            Mode::Normal | Mode::Replace | Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
 565                false
 566            }
 567        }
 568    }
 569
 570    pub fn should_autoindent(&self) -> bool {
 571        !(self.mode == Mode::Insert && self.last_mode == Mode::VisualBlock)
 572    }
 573
 574    pub fn clip_at_line_ends(&self) -> bool {
 575        match self.mode {
 576            Mode::Insert | Mode::Visual | Mode::VisualLine | Mode::VisualBlock | Mode::Replace => {
 577                false
 578            }
 579            Mode::Normal => true,
 580        }
 581    }
 582
 583    pub fn extend_key_context(&self, context: &mut KeyContext) {
 584        let mut mode = match self.mode {
 585            Mode::Normal => "normal",
 586            Mode::Visual | Mode::VisualLine | Mode::VisualBlock => "visual",
 587            Mode::Insert => "insert",
 588            Mode::Replace => "replace",
 589        }
 590        .to_string();
 591
 592        let mut operator_id = "none";
 593
 594        let active_operator = self.active_operator();
 595        if active_operator.is_none() && self.pre_count.is_some()
 596            || active_operator.is_some() && self.post_count.is_some()
 597        {
 598            context.add("VimCount");
 599        }
 600
 601        if let Some(active_operator) = active_operator {
 602            if active_operator.is_waiting(self.mode) {
 603                mode = "waiting".to_string();
 604            } else {
 605                mode = "operator".to_string();
 606                operator_id = active_operator.id();
 607            }
 608        }
 609
 610        if mode != "waiting" && mode != "insert" && mode != "replace" {
 611            context.add("VimControl");
 612        }
 613        context.set("vim_mode", mode);
 614        context.set("vim_operator", operator_id);
 615    }
 616
 617    fn focused(&mut self, preserve_selection: bool, cx: &mut ViewContext<Self>) {
 618        let Some(editor) = self.editor() else {
 619            return;
 620        };
 621        let editor = editor.read(cx);
 622        let editor_mode = editor.mode();
 623        let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
 624
 625        if editor_mode == EditorMode::Full
 626                && !newest_selection_empty
 627                && self.mode == Mode::Normal
 628                // When following someone, don't switch vim mode.
 629                && editor.leader_peer_id().is_none()
 630        {
 631            if preserve_selection {
 632                self.switch_mode(Mode::Visual, true, cx);
 633            } else {
 634                self.update_editor(cx, |_, editor, cx| {
 635                    editor.set_clip_at_line_ends(false, cx);
 636                    editor.change_selections(None, cx, |s| {
 637                        s.move_with(|_, selection| {
 638                            selection.collapse_to(selection.start, selection.goal)
 639                        })
 640                    });
 641                });
 642            }
 643        }
 644
 645        cx.emit(VimEvent::Focused);
 646        self.sync_vim_settings(cx);
 647
 648        if VimSettings::get_global(cx).toggle_relative_line_numbers {
 649            if let Some(old_vim) = Vim::globals(cx).focused_vim() {
 650                if old_vim.entity_id() != cx.view().entity_id() {
 651                    old_vim.update(cx, |vim, cx| {
 652                        vim.update_editor(cx, |_, editor, cx| {
 653                            editor.set_relative_line_number(None, cx)
 654                        });
 655                    });
 656
 657                    self.update_editor(cx, |vim, editor, cx| {
 658                        let is_relative = vim.mode != Mode::Insert;
 659                        editor.set_relative_line_number(Some(is_relative), cx)
 660                    });
 661                }
 662            } else {
 663                self.update_editor(cx, |vim, editor, cx| {
 664                    let is_relative = vim.mode != Mode::Insert;
 665                    editor.set_relative_line_number(Some(is_relative), cx)
 666                });
 667            }
 668        }
 669        Vim::globals(cx).focused_vim = Some(cx.view().downgrade());
 670    }
 671
 672    fn blurred(&mut self, cx: &mut ViewContext<Self>) {
 673        self.stop_recording_immediately(NormalBefore.boxed_clone(), cx);
 674        self.store_visual_marks(cx);
 675        self.clear_operator(cx);
 676        self.update_editor(cx, |_, editor, cx| {
 677            editor.set_cursor_shape(language::CursorShape::Hollow, cx);
 678        });
 679    }
 680
 681    fn update_editor<S>(
 682        &mut self,
 683        cx: &mut ViewContext<Self>,
 684        update: impl FnOnce(&mut Self, &mut Editor, &mut ViewContext<Editor>) -> S,
 685    ) -> Option<S> {
 686        let editor = self.editor.upgrade()?;
 687        Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
 688    }
 689
 690    fn editor_selections(&mut self, cx: &mut ViewContext<Self>) -> Vec<Range<Anchor>> {
 691        self.update_editor(cx, |_, editor, _| {
 692            editor
 693                .selections
 694                .disjoint_anchors()
 695                .iter()
 696                .map(|selection| selection.tail()..selection.head())
 697                .collect()
 698        })
 699        .unwrap_or_default()
 700    }
 701
 702    /// When doing an action that modifies the buffer, we start recording so that `.`
 703    /// will replay the action.
 704    pub fn start_recording(&mut self, cx: &mut ViewContext<Self>) {
 705        Vim::update_globals(cx, |globals, cx| {
 706            if !globals.dot_replaying {
 707                globals.dot_recording = true;
 708                globals.recorded_actions = Default::default();
 709                globals.recorded_count = None;
 710
 711                let selections = self.editor().map(|editor| {
 712                    let editor = editor.read(cx);
 713                    (
 714                        editor.selections.oldest::<Point>(cx),
 715                        editor.selections.newest::<Point>(cx),
 716                    )
 717                });
 718
 719                if let Some((oldest, newest)) = selections {
 720                    globals.recorded_selection = match self.mode {
 721                        Mode::Visual if newest.end.row == newest.start.row => {
 722                            RecordedSelection::SingleLine {
 723                                cols: newest.end.column - newest.start.column,
 724                            }
 725                        }
 726                        Mode::Visual => RecordedSelection::Visual {
 727                            rows: newest.end.row - newest.start.row,
 728                            cols: newest.end.column,
 729                        },
 730                        Mode::VisualLine => RecordedSelection::VisualLine {
 731                            rows: newest.end.row - newest.start.row,
 732                        },
 733                        Mode::VisualBlock => RecordedSelection::VisualBlock {
 734                            rows: newest.end.row.abs_diff(oldest.start.row),
 735                            cols: newest.end.column.abs_diff(oldest.start.column),
 736                        },
 737                        _ => RecordedSelection::None,
 738                    }
 739                } else {
 740                    globals.recorded_selection = RecordedSelection::None;
 741                }
 742            }
 743        })
 744    }
 745
 746    pub fn stop_replaying(&mut self, cx: &mut ViewContext<Self>) {
 747        let globals = Vim::globals(cx);
 748        globals.dot_replaying = false;
 749        if let Some(replayer) = globals.replayer.take() {
 750            replayer.stop();
 751        }
 752    }
 753
 754    /// When finishing an action that modifies the buffer, stop recording.
 755    /// as you usually call this within a keystroke handler we also ensure that
 756    /// the current action is recorded.
 757    pub fn stop_recording(&mut self, cx: &mut ViewContext<Self>) {
 758        let globals = Vim::globals(cx);
 759        if globals.dot_recording {
 760            globals.stop_recording_after_next_action = true;
 761        }
 762    }
 763
 764    /// Stops recording actions immediately rather than waiting until after the
 765    /// next action to stop recording.
 766    ///
 767    /// This doesn't include the current action.
 768    pub fn stop_recording_immediately(
 769        &mut self,
 770        action: Box<dyn Action>,
 771        cx: &mut ViewContext<Self>,
 772    ) {
 773        let globals = Vim::globals(cx);
 774        if globals.dot_recording {
 775            globals
 776                .recorded_actions
 777                .push(ReplayableAction::Action(action.boxed_clone()));
 778            globals.dot_recording = false;
 779            globals.stop_recording_after_next_action = false;
 780        }
 781    }
 782
 783    /// Explicitly record one action (equivalents to start_recording and stop_recording)
 784    pub fn record_current_action(&mut self, cx: &mut ViewContext<Self>) {
 785        self.start_recording(cx);
 786        self.stop_recording(cx);
 787    }
 788
 789    fn push_count_digit(&mut self, number: usize, cx: &mut ViewContext<Self>) {
 790        if self.active_operator().is_some() {
 791            let post_count = self.post_count.unwrap_or(0);
 792
 793            self.post_count = Some(
 794                post_count
 795                    .checked_mul(10)
 796                    .and_then(|post_count| post_count.checked_add(number))
 797                    .unwrap_or(post_count),
 798            )
 799        } else {
 800            let pre_count = self.pre_count.unwrap_or(0);
 801
 802            self.pre_count = Some(
 803                pre_count
 804                    .checked_mul(10)
 805                    .and_then(|pre_count| pre_count.checked_add(number))
 806                    .unwrap_or(pre_count),
 807            )
 808        }
 809        // update the keymap so that 0 works
 810        self.sync_vim_settings(cx)
 811    }
 812
 813    fn select_register(&mut self, register: Arc<str>, cx: &mut ViewContext<Self>) {
 814        if register.chars().count() == 1 {
 815            self.selected_register
 816                .replace(register.chars().next().unwrap());
 817        }
 818        self.operator_stack.clear();
 819        self.sync_vim_settings(cx);
 820    }
 821
 822    fn maybe_pop_operator(&mut self) -> Option<Operator> {
 823        self.operator_stack.pop()
 824    }
 825
 826    fn pop_operator(&mut self, cx: &mut ViewContext<Self>) -> Operator {
 827        let popped_operator = self.operator_stack.pop()
 828            .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
 829        self.sync_vim_settings(cx);
 830        popped_operator
 831    }
 832
 833    fn clear_operator(&mut self, cx: &mut ViewContext<Self>) {
 834        self.take_count(cx);
 835        self.selected_register.take();
 836        self.operator_stack.clear();
 837        self.sync_vim_settings(cx);
 838    }
 839
 840    fn active_operator(&self) -> Option<Operator> {
 841        self.operator_stack.last().cloned()
 842    }
 843
 844    fn transaction_begun(&mut self, transaction_id: TransactionId, _: &mut ViewContext<Self>) {
 845        let mode = if (self.mode == Mode::Insert
 846            || self.mode == Mode::Replace
 847            || self.mode == Mode::Normal)
 848            && self.current_tx.is_none()
 849        {
 850            self.current_tx = Some(transaction_id);
 851            self.last_mode
 852        } else {
 853            self.mode
 854        };
 855        if mode == Mode::VisualLine || mode == Mode::VisualBlock {
 856            self.undo_modes.insert(transaction_id, mode);
 857        }
 858    }
 859
 860    fn transaction_undone(&mut self, transaction_id: &TransactionId, cx: &mut ViewContext<Self>) {
 861        match self.mode {
 862            Mode::VisualLine | Mode::VisualBlock | Mode::Visual => {
 863                self.update_editor(cx, |vim, editor, cx| {
 864                    let original_mode = vim.undo_modes.get(transaction_id);
 865                    editor.change_selections(None, cx, |s| match original_mode {
 866                        Some(Mode::VisualLine) => {
 867                            s.move_with(|map, selection| {
 868                                selection.collapse_to(
 869                                    map.prev_line_boundary(selection.start.to_point(map)).1,
 870                                    SelectionGoal::None,
 871                                )
 872                            });
 873                        }
 874                        Some(Mode::VisualBlock) => {
 875                            let mut first = s.first_anchor();
 876                            first.collapse_to(first.start, first.goal);
 877                            s.select_anchors(vec![first]);
 878                        }
 879                        _ => {
 880                            s.move_with(|map, selection| {
 881                                selection.collapse_to(
 882                                    map.clip_at_line_end(selection.start),
 883                                    selection.goal,
 884                                );
 885                            });
 886                        }
 887                    });
 888                });
 889                self.switch_mode(Mode::Normal, true, cx)
 890            }
 891            Mode::Normal => {
 892                self.update_editor(cx, |_, editor, cx| {
 893                    editor.change_selections(None, cx, |s| {
 894                        s.move_with(|map, selection| {
 895                            selection
 896                                .collapse_to(map.clip_at_line_end(selection.end), selection.goal)
 897                        })
 898                    })
 899                });
 900            }
 901            Mode::Insert | Mode::Replace => {}
 902        }
 903    }
 904
 905    fn local_selections_changed(&mut self, cx: &mut ViewContext<Self>) {
 906        let Some(editor) = self.editor() else { return };
 907
 908        if editor.read(cx).leader_peer_id().is_some() {
 909            return;
 910        }
 911
 912        let newest = editor.read(cx).selections.newest_anchor().clone();
 913        let is_multicursor = editor.read(cx).selections.count() > 1;
 914        if self.mode == Mode::Insert && self.current_tx.is_some() {
 915            if self.current_anchor.is_none() {
 916                self.current_anchor = Some(newest);
 917            } else if self.current_anchor.as_ref().unwrap() != &newest {
 918                if let Some(tx_id) = self.current_tx.take() {
 919                    self.update_editor(cx, |_, editor, cx| {
 920                        editor.group_until_transaction(tx_id, cx)
 921                    });
 922                }
 923            }
 924        } else if self.mode == Mode::Normal && newest.start != newest.end {
 925            if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
 926                self.switch_mode(Mode::VisualBlock, false, cx);
 927            } else {
 928                self.switch_mode(Mode::Visual, false, cx)
 929            }
 930        } else if newest.start == newest.end
 931            && !is_multicursor
 932            && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&self.mode)
 933        {
 934            self.switch_mode(Mode::Normal, true, cx);
 935        }
 936    }
 937
 938    fn input_ignored(&mut self, text: Arc<str>, cx: &mut ViewContext<Self>) {
 939        if text.is_empty() {
 940            return;
 941        }
 942
 943        match self.active_operator() {
 944            Some(Operator::FindForward { before }) => {
 945                let find = Motion::FindForward {
 946                    before,
 947                    char: text.chars().next().unwrap(),
 948                    mode: if VimSettings::get_global(cx).use_multiline_find {
 949                        FindRange::MultiLine
 950                    } else {
 951                        FindRange::SingleLine
 952                    },
 953                    smartcase: VimSettings::get_global(cx).use_smartcase_find,
 954                };
 955                Vim::globals(cx).last_find = Some(find.clone());
 956                self.motion(find, cx)
 957            }
 958            Some(Operator::FindBackward { after }) => {
 959                let find = Motion::FindBackward {
 960                    after,
 961                    char: text.chars().next().unwrap(),
 962                    mode: if VimSettings::get_global(cx).use_multiline_find {
 963                        FindRange::MultiLine
 964                    } else {
 965                        FindRange::SingleLine
 966                    },
 967                    smartcase: VimSettings::get_global(cx).use_smartcase_find,
 968                };
 969                Vim::globals(cx).last_find = Some(find.clone());
 970                self.motion(find, cx)
 971            }
 972            Some(Operator::Replace) => match self.mode {
 973                Mode::Normal => self.normal_replace(text, cx),
 974                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
 975                    self.visual_replace(text, cx)
 976                }
 977                _ => self.clear_operator(cx),
 978            },
 979            Some(Operator::Digraph { first_char }) => {
 980                if let Some(first_char) = first_char {
 981                    if let Some(second_char) = text.chars().next() {
 982                        self.insert_digraph(first_char, second_char, cx);
 983                    }
 984                } else {
 985                    let first_char = text.chars().next();
 986                    self.pop_operator(cx);
 987                    self.push_operator(Operator::Digraph { first_char }, cx);
 988                }
 989            }
 990            Some(Operator::AddSurrounds { target }) => match self.mode {
 991                Mode::Normal => {
 992                    if let Some(target) = target {
 993                        self.add_surrounds(text, target, cx);
 994                        self.clear_operator(cx);
 995                    }
 996                }
 997                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
 998                    self.add_surrounds(text, SurroundsType::Selection, cx);
 999                    self.clear_operator(cx);
1000                }
1001                _ => self.clear_operator(cx),
1002            },
1003            Some(Operator::ChangeSurrounds { target }) => match self.mode {
1004                Mode::Normal => {
1005                    if let Some(target) = target {
1006                        self.change_surrounds(text, target, cx);
1007                        self.clear_operator(cx);
1008                    }
1009                }
1010                _ => self.clear_operator(cx),
1011            },
1012            Some(Operator::DeleteSurrounds) => match self.mode {
1013                Mode::Normal => {
1014                    self.delete_surrounds(text, cx);
1015                    self.clear_operator(cx);
1016                }
1017                _ => self.clear_operator(cx),
1018            },
1019            Some(Operator::Mark) => self.create_mark(text, false, cx),
1020            Some(Operator::RecordRegister) => {
1021                self.record_register(text.chars().next().unwrap(), cx)
1022            }
1023            Some(Operator::ReplayRegister) => {
1024                self.replay_register(text.chars().next().unwrap(), cx)
1025            }
1026            Some(Operator::Register) => match self.mode {
1027                Mode::Insert => {
1028                    self.update_editor(cx, |_, editor, cx| {
1029                        if let Some(register) = Vim::update_globals(cx, |globals, cx| {
1030                            globals.read_register(text.chars().next(), Some(editor), cx)
1031                        }) {
1032                            editor.do_paste(
1033                                &register.text.to_string(),
1034                                register.clipboard_selections.clone(),
1035                                false,
1036                                cx,
1037                            )
1038                        }
1039                    });
1040                    self.clear_operator(cx);
1041                }
1042                _ => {
1043                    self.select_register(text, cx);
1044                }
1045            },
1046            Some(Operator::Jump { line }) => self.jump(text, line, cx),
1047            _ => match self.mode {
1048                Mode::Replace => self.multi_replace(text, cx),
1049                _ => {}
1050            },
1051        }
1052    }
1053
1054    fn sync_vim_settings(&mut self, cx: &mut ViewContext<Self>) {
1055        self.update_editor(cx, |vim, editor, cx| {
1056            editor.set_cursor_shape(vim.cursor_shape(), cx);
1057            editor.set_clip_at_line_ends(vim.clip_at_line_ends(), cx);
1058            editor.set_collapse_matches(true);
1059            editor.set_input_enabled(vim.editor_input_enabled());
1060            editor.set_autoindent(vim.should_autoindent());
1061            editor.selections.line_mode = matches!(vim.mode, Mode::VisualLine);
1062            editor.set_inline_completions_enabled(matches!(vim.mode, Mode::Insert | Mode::Replace));
1063        });
1064        cx.notify()
1065    }
1066}
1067
1068impl Settings for VimModeSetting {
1069    const KEY: Option<&'static str> = Some("vim_mode");
1070
1071    type FileContent = Option<bool>;
1072
1073    fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1074        Ok(Self(sources.user.copied().flatten().unwrap_or(
1075            sources.default.ok_or_else(Self::missing_default)?,
1076        )))
1077    }
1078}
1079
1080/// Controls when to use system clipboard.
1081#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
1082#[serde(rename_all = "snake_case")]
1083pub enum UseSystemClipboard {
1084    /// Don't use system clipboard.
1085    Never,
1086    /// Use system clipboard.
1087    Always,
1088    /// Use system clipboard for yank operations.
1089    OnYank,
1090}
1091
1092#[derive(Deserialize)]
1093struct VimSettings {
1094    pub toggle_relative_line_numbers: bool,
1095    pub use_system_clipboard: UseSystemClipboard,
1096    pub use_multiline_find: bool,
1097    pub use_smartcase_find: bool,
1098    pub custom_digraphs: HashMap<String, Arc<str>>,
1099}
1100
1101#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
1102struct VimSettingsContent {
1103    pub toggle_relative_line_numbers: Option<bool>,
1104    pub use_system_clipboard: Option<UseSystemClipboard>,
1105    pub use_multiline_find: Option<bool>,
1106    pub use_smartcase_find: Option<bool>,
1107    pub custom_digraphs: Option<HashMap<String, Arc<str>>>,
1108}
1109
1110impl Settings for VimSettings {
1111    const KEY: Option<&'static str> = Some("vim");
1112
1113    type FileContent = VimSettingsContent;
1114
1115    fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1116        sources.json_merge()
1117    }
1118}