vim.rs

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