vim.rs

   1//! Vim support for Zed.
   2
   3#[cfg(test)]
   4mod test;
   5
   6mod change_list;
   7mod command;
   8mod digraph;
   9mod helix;
  10mod indent;
  11mod insert;
  12mod mode_indicator;
  13mod motion;
  14mod normal;
  15mod object;
  16mod replace;
  17mod rewrap;
  18mod state;
  19mod surrounds;
  20mod visual;
  21
  22use crate::normal::paste::Paste as VimPaste;
  23use collections::HashMap;
  24use editor::{
  25    Anchor, Bias, Editor, EditorEvent, EditorSettings, HideMouseCursorOrigin, MultiBufferOffset,
  26    SelectionEffects,
  27    actions::Paste,
  28    display_map::ToDisplayPoint,
  29    movement::{self, FindRange},
  30};
  31use gpui::{
  32    Action, App, AppContext, Axis, Context, Entity, EventEmitter, KeyContext, KeystrokeEvent,
  33    Render, Subscription, Task, WeakEntity, Window, actions,
  34};
  35use insert::{NormalBefore, TemporaryNormal};
  36use language::{
  37    CharKind, CharScopeContext, CursorShape, Point, Selection, SelectionGoal, TransactionId,
  38};
  39pub use mode_indicator::ModeIndicator;
  40use motion::Motion;
  41use multi_buffer::ToPoint as _;
  42use normal::search::SearchSubmit;
  43use object::Object;
  44use schemars::JsonSchema;
  45use search::BufferSearchBar;
  46use serde::Deserialize;
  47use settings::RegisterSetting;
  48pub use settings::{
  49    ModeContent, Settings, SettingsStore, UseSystemClipboard, update_settings_file,
  50};
  51use state::{Mode, Operator, RecordedSelection, SearchState, VimGlobals};
  52use std::{mem, ops::Range, sync::Arc};
  53use surrounds::SurroundsType;
  54use theme_settings::ThemeSettings;
  55use ui::{IntoElement, SharedString, px};
  56use vim_mode_setting::HelixModeSetting;
  57use vim_mode_setting::VimModeSetting;
  58use workspace::{self, Pane, Workspace};
  59
  60use crate::{
  61    normal::{GoToPreviousTab, GoToTab},
  62    state::ReplayableAction,
  63};
  64
  65/// Number is used to manage vim's count. Pushing a digit
  66/// multiplies the current value by 10 and adds the digit.
  67#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
  68#[action(namespace = vim)]
  69struct Number(usize);
  70
  71#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
  72#[action(namespace = vim)]
  73struct SelectRegister(String);
  74
  75#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
  76#[action(namespace = vim)]
  77#[serde(deny_unknown_fields)]
  78struct PushObject {
  79    around: bool,
  80}
  81
  82#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
  83#[action(namespace = vim)]
  84#[serde(deny_unknown_fields)]
  85struct PushFindForward {
  86    before: bool,
  87    multiline: bool,
  88}
  89
  90#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
  91#[action(namespace = vim)]
  92#[serde(deny_unknown_fields)]
  93struct PushFindBackward {
  94    after: bool,
  95    multiline: bool,
  96}
  97
  98#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
  99#[action(namespace = vim)]
 100#[serde(deny_unknown_fields)]
 101/// Selects the next object.
 102struct PushHelixNext {
 103    around: bool,
 104}
 105
 106#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
 107#[action(namespace = vim)]
 108#[serde(deny_unknown_fields)]
 109/// Selects the previous object.
 110struct PushHelixPrevious {
 111    around: bool,
 112}
 113
 114#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
 115#[action(namespace = vim)]
 116#[serde(deny_unknown_fields)]
 117struct PushSneak {
 118    first_char: Option<char>,
 119}
 120
 121#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
 122#[action(namespace = vim)]
 123#[serde(deny_unknown_fields)]
 124struct PushSneakBackward {
 125    first_char: Option<char>,
 126}
 127
 128#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
 129#[action(namespace = vim)]
 130#[serde(deny_unknown_fields)]
 131struct PushAddSurrounds;
 132
 133#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
 134#[action(namespace = vim)]
 135#[serde(deny_unknown_fields)]
 136struct PushChangeSurrounds {
 137    target: Option<Object>,
 138}
 139
 140#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
 141#[action(namespace = vim)]
 142#[serde(deny_unknown_fields)]
 143struct PushJump {
 144    line: bool,
 145}
 146
 147#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
 148#[action(namespace = vim)]
 149#[serde(deny_unknown_fields)]
 150struct PushDigraph {
 151    first_char: Option<char>,
 152}
 153
 154#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
 155#[action(namespace = vim)]
 156#[serde(deny_unknown_fields)]
 157struct PushLiteral {
 158    prefix: Option<String>,
 159}
 160
 161actions!(
 162    vim,
 163    [
 164        /// Switches to normal mode.
 165        SwitchToNormalMode,
 166        /// Switches to insert mode.
 167        SwitchToInsertMode,
 168        /// Switches to replace mode.
 169        SwitchToReplaceMode,
 170        /// Switches to visual mode.
 171        SwitchToVisualMode,
 172        /// Switches to visual line mode.
 173        SwitchToVisualLineMode,
 174        /// Switches to visual block mode.
 175        SwitchToVisualBlockMode,
 176        /// Switches to Helix-style normal mode.
 177        SwitchToHelixNormalMode,
 178        /// Clears any pending operators.
 179        ClearOperators,
 180        /// Clears the exchange register.
 181        ClearExchange,
 182        /// Inserts a tab character.
 183        Tab,
 184        /// Inserts a newline.
 185        Enter,
 186        /// Selects inner text object.
 187        InnerObject,
 188        /// Maximizes the current pane.
 189        MaximizePane,
 190        /// Resets all pane sizes to default.
 191        ResetPaneSizes,
 192        /// Resizes the pane to the right.
 193        ResizePaneRight,
 194        /// Resizes the pane to the left.
 195        ResizePaneLeft,
 196        /// Resizes the pane upward.
 197        ResizePaneUp,
 198        /// Resizes the pane downward.
 199        ResizePaneDown,
 200        /// Starts a change operation.
 201        PushChange,
 202        /// Starts a delete operation.
 203        PushDelete,
 204        /// Exchanges text regions.
 205        Exchange,
 206        /// Starts a yank operation.
 207        PushYank,
 208        /// Starts a replace operation.
 209        PushReplace,
 210        /// Deletes surrounding characters.
 211        PushDeleteSurrounds,
 212        /// Sets a mark at the current position.
 213        PushMark,
 214        /// Toggles the marks view.
 215        ToggleMarksView,
 216        /// Starts a forced motion.
 217        PushForcedMotion,
 218        /// Starts an indent operation.
 219        PushIndent,
 220        /// Starts an outdent operation.
 221        PushOutdent,
 222        /// Starts an auto-indent operation.
 223        PushAutoIndent,
 224        /// Starts a rewrap operation.
 225        PushRewrap,
 226        /// Starts a shell command operation.
 227        PushShellCommand,
 228        /// Converts to lowercase.
 229        PushLowercase,
 230        /// Converts to uppercase.
 231        PushUppercase,
 232        /// Toggles case.
 233        PushOppositeCase,
 234        /// Applies ROT13 encoding.
 235        PushRot13,
 236        /// Applies ROT47 encoding.
 237        PushRot47,
 238        /// Toggles the registers view.
 239        ToggleRegistersView,
 240        /// Selects a register.
 241        PushRegister,
 242        /// Starts recording to a register.
 243        PushRecordRegister,
 244        /// Replays a register.
 245        PushReplayRegister,
 246        /// Replaces with register contents.
 247        PushReplaceWithRegister,
 248        /// Toggles comments.
 249        PushToggleComments,
 250        /// Selects (count) next menu item
 251        MenuSelectNext,
 252        /// Selects (count) previous menu item
 253        MenuSelectPrevious,
 254        /// Clears count or toggles project panel focus
 255        ToggleProjectPanelFocus,
 256        /// Starts a match operation.
 257        PushHelixMatch,
 258        /// Adds surrounding characters in Helix mode.
 259        PushHelixSurroundAdd,
 260        /// Replaces surrounding characters in Helix mode.
 261        PushHelixSurroundReplace,
 262        /// Deletes surrounding characters in Helix mode.
 263        PushHelixSurroundDelete,
 264    ]
 265);
 266
 267// in the workspace namespace so it's not filtered out when vim is disabled.
 268actions!(
 269    workspace,
 270    [
 271        /// Toggles Vim mode on or off.
 272        ToggleVimMode,
 273        /// Toggles Helix mode on or off.
 274        ToggleHelixMode,
 275    ]
 276);
 277
 278/// Initializes the `vim` crate.
 279pub fn init(cx: &mut App) {
 280    VimGlobals::register(cx);
 281
 282    cx.observe_new(Vim::register).detach();
 283
 284    cx.observe_new(|workspace: &mut Workspace, _, _| {
 285        workspace.register_action(|workspace, _: &ToggleVimMode, _, cx| {
 286            let fs = workspace.app_state().fs.clone();
 287            let currently_enabled = VimModeSetting::get_global(cx).0;
 288            update_settings_file(fs, cx, move |setting, _| {
 289                setting.vim_mode = Some(!currently_enabled);
 290                if let Some(helix_mode) = &mut setting.helix_mode {
 291                    *helix_mode = false;
 292                }
 293            })
 294        });
 295
 296        workspace.register_action(|workspace, _: &ToggleHelixMode, _, cx| {
 297            let fs = workspace.app_state().fs.clone();
 298            let currently_enabled = HelixModeSetting::get_global(cx).0;
 299            update_settings_file(fs, cx, move |setting, _| {
 300                setting.helix_mode = Some(!currently_enabled);
 301                if let Some(vim_mode) = &mut setting.vim_mode {
 302                    *vim_mode = false;
 303                }
 304            })
 305        });
 306
 307        workspace.register_action(|_, _: &MenuSelectNext, window, cx| {
 308            let count = Vim::take_count(cx).unwrap_or(1);
 309
 310            for _ in 0..count {
 311                window.dispatch_action(menu::SelectNext.boxed_clone(), cx);
 312            }
 313        });
 314
 315        workspace.register_action(|_, _: &MenuSelectPrevious, window, cx| {
 316            let count = Vim::take_count(cx).unwrap_or(1);
 317
 318            for _ in 0..count {
 319                window.dispatch_action(menu::SelectPrevious.boxed_clone(), cx);
 320            }
 321        });
 322
 323        workspace.register_action(|_, _: &ToggleProjectPanelFocus, window, cx| {
 324            if Vim::take_count(cx).is_none() {
 325                window.dispatch_action(zed_actions::project_panel::ToggleFocus.boxed_clone(), cx);
 326            }
 327        });
 328
 329        workspace.register_action(|workspace, n: &Number, window, cx| {
 330            let vim = workspace
 331                .focused_pane(window, cx)
 332                .read(cx)
 333                .active_item()
 334                .and_then(|item| item.act_as::<Editor>(cx))
 335                .and_then(|editor| editor.read(cx).addon::<VimAddon>().cloned());
 336            if let Some(vim) = vim {
 337                let digit = n.0;
 338                vim.entity.update(cx, |_, cx| {
 339                    cx.defer_in(window, move |vim, window, cx| {
 340                        vim.push_count_digit(digit, window, cx)
 341                    })
 342                });
 343            } else {
 344                let count = Vim::globals(cx).pre_count.unwrap_or(0);
 345                Vim::globals(cx).pre_count = Some(
 346                    count
 347                        .checked_mul(10)
 348                        .and_then(|c| c.checked_add(n.0))
 349                        .unwrap_or(count),
 350                );
 351            };
 352        });
 353
 354        workspace.register_action(|_, _: &zed_actions::vim::OpenDefaultKeymap, _, cx| {
 355            cx.emit(workspace::Event::OpenBundledFile {
 356                text: settings::vim_keymap(),
 357                title: "Default Vim Bindings",
 358                language: "JSON",
 359            });
 360        });
 361
 362        workspace.register_action(|workspace, _: &ResetPaneSizes, _, cx| {
 363            workspace.reset_pane_sizes(cx);
 364        });
 365
 366        workspace.register_action(|workspace, _: &MaximizePane, window, cx| {
 367            let pane = workspace.active_pane();
 368            let Some(size) = workspace.bounding_box_for_pane(pane) else {
 369                return;
 370            };
 371
 372            let theme = ThemeSettings::get_global(cx);
 373            let height = theme.buffer_font_size(cx) * theme.buffer_line_height.value();
 374
 375            let desired_size = if let Some(count) = Vim::take_count(cx) {
 376                height * count
 377            } else {
 378                px(10000.)
 379            };
 380            workspace.resize_pane(Axis::Vertical, desired_size - size.size.height, window, cx)
 381        });
 382
 383        workspace.register_action(|workspace, _: &ResizePaneRight, window, cx| {
 384            let count = Vim::take_count(cx).unwrap_or(1) as f32;
 385            Vim::take_forced_motion(cx);
 386            let theme = ThemeSettings::get_global(cx);
 387            let font_id = window.text_system().resolve_font(&theme.buffer_font);
 388            let Ok(width) = window
 389                .text_system()
 390                .advance(font_id, theme.buffer_font_size(cx), 'm')
 391            else {
 392                return;
 393            };
 394            workspace.resize_pane(Axis::Horizontal, width.width * count, window, cx);
 395        });
 396
 397        workspace.register_action(|workspace, _: &ResizePaneLeft, window, cx| {
 398            let count = Vim::take_count(cx).unwrap_or(1) as f32;
 399            Vim::take_forced_motion(cx);
 400            let theme = ThemeSettings::get_global(cx);
 401            let font_id = window.text_system().resolve_font(&theme.buffer_font);
 402            let Ok(width) = window
 403                .text_system()
 404                .advance(font_id, theme.buffer_font_size(cx), 'm')
 405            else {
 406                return;
 407            };
 408            workspace.resize_pane(Axis::Horizontal, -width.width * count, window, cx);
 409        });
 410
 411        workspace.register_action(|workspace, _: &ResizePaneUp, window, cx| {
 412            let count = Vim::take_count(cx).unwrap_or(1) as f32;
 413            Vim::take_forced_motion(cx);
 414            let theme = ThemeSettings::get_global(cx);
 415            let height = theme.buffer_font_size(cx) * theme.buffer_line_height.value();
 416            workspace.resize_pane(Axis::Vertical, height * count, window, cx);
 417        });
 418
 419        workspace.register_action(|workspace, _: &ResizePaneDown, window, cx| {
 420            let count = Vim::take_count(cx).unwrap_or(1) as f32;
 421            Vim::take_forced_motion(cx);
 422            let theme = ThemeSettings::get_global(cx);
 423            let height = theme.buffer_font_size(cx) * theme.buffer_line_height.value();
 424            workspace.resize_pane(Axis::Vertical, -height * count, window, cx);
 425        });
 426
 427        workspace.register_action(|workspace, _: &SearchSubmit, window, cx| {
 428            let vim = workspace
 429                .focused_pane(window, cx)
 430                .read(cx)
 431                .active_item()
 432                .and_then(|item| item.act_as::<Editor>(cx))
 433                .and_then(|editor| editor.read(cx).addon::<VimAddon>().cloned());
 434            let Some(vim) = vim else { return };
 435            vim.entity.update(cx, |_, cx| {
 436                cx.defer_in(window, |vim, window, cx| vim.search_submit(window, cx))
 437            })
 438        });
 439        workspace.register_action(|_, _: &GoToTab, window, cx| {
 440            let count = Vim::take_count(cx);
 441            Vim::take_forced_motion(cx);
 442
 443            if let Some(tab_index) = count {
 444                // <count>gt goes to tab <count> (1-based).
 445                let zero_based_index = tab_index.saturating_sub(1);
 446                window.dispatch_action(
 447                    workspace::pane::ActivateItem(zero_based_index).boxed_clone(),
 448                    cx,
 449                );
 450            } else {
 451                // If no count is provided, go to the next tab.
 452                window.dispatch_action(
 453                    workspace::pane::ActivateNextItem::default().boxed_clone(),
 454                    cx,
 455                );
 456            }
 457        });
 458
 459        workspace.register_action(|workspace, _: &GoToPreviousTab, window, cx| {
 460            let count = Vim::take_count(cx);
 461            Vim::take_forced_motion(cx);
 462
 463            if let Some(count) = count {
 464                // gT with count goes back that many tabs with wraparound (not the same as gt!).
 465                let pane = workspace.active_pane().read(cx);
 466                let item_count = pane.items().count();
 467                if item_count > 0 {
 468                    let current_index = pane.active_item_index();
 469                    let target_index = (current_index as isize - count as isize)
 470                        .rem_euclid(item_count as isize)
 471                        as usize;
 472                    window.dispatch_action(
 473                        workspace::pane::ActivateItem(target_index).boxed_clone(),
 474                        cx,
 475                    );
 476                }
 477            } else {
 478                // No count provided, go to the previous tab.
 479                window.dispatch_action(
 480                    workspace::pane::ActivatePreviousItem::default().boxed_clone(),
 481                    cx,
 482                );
 483            }
 484        });
 485    })
 486    .detach();
 487}
 488
 489#[derive(Clone)]
 490pub(crate) struct VimAddon {
 491    pub(crate) entity: Entity<Vim>,
 492}
 493
 494impl editor::Addon for VimAddon {
 495    fn extend_key_context(&self, key_context: &mut KeyContext, cx: &App) {
 496        self.entity.read(cx).extend_key_context(key_context, cx)
 497    }
 498
 499    fn to_any(&self) -> &dyn std::any::Any {
 500        self
 501    }
 502}
 503
 504/// The state pertaining to Vim mode.
 505pub(crate) struct Vim {
 506    pub(crate) mode: Mode,
 507    pub last_mode: Mode,
 508    pub temp_mode: bool,
 509    pub status_label: Option<SharedString>,
 510    pub exit_temporary_mode: bool,
 511
 512    operator_stack: Vec<Operator>,
 513    pub(crate) replacements: Vec<(Range<editor::Anchor>, String)>,
 514
 515    pub(crate) stored_visual_mode: Option<(Mode, Vec<bool>)>,
 516
 517    pub(crate) current_tx: Option<TransactionId>,
 518    pub(crate) current_anchor: Option<Selection<Anchor>>,
 519    pub(crate) undo_modes: HashMap<TransactionId, Mode>,
 520    pub(crate) undo_last_line_tx: Option<TransactionId>,
 521    extended_pending_selection_id: Option<usize>,
 522
 523    selected_register: Option<char>,
 524    pub search: SearchState,
 525
 526    editor: WeakEntity<Editor>,
 527
 528    last_command: Option<String>,
 529    running_command: Option<Task<()>>,
 530    _subscriptions: Vec<Subscription>,
 531}
 532
 533// Hack: Vim intercepts events dispatched to a window and updates the view in response.
 534// This means it needs a VisualContext. The easiest way to satisfy that constraint is
 535// to make Vim a "View" that is just never actually rendered.
 536impl Render for Vim {
 537    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 538        gpui::Empty
 539    }
 540}
 541
 542enum VimEvent {
 543    Focused,
 544}
 545impl EventEmitter<VimEvent> for Vim {}
 546
 547impl Vim {
 548    /// The namespace for Vim actions.
 549    const NAMESPACE: &'static str = "vim";
 550
 551    pub fn new(window: &mut Window, cx: &mut Context<Editor>) -> Entity<Self> {
 552        let editor = cx.entity();
 553
 554        let initial_vim_mode = VimSettings::get_global(cx).default_mode;
 555        let (mode, last_mode) = if HelixModeSetting::get_global(cx).0 {
 556            let initial_helix_mode = match initial_vim_mode {
 557                Mode::Normal => Mode::HelixNormal,
 558                Mode::Insert => Mode::Insert,
 559                // Otherwise, we panic with a note that we should never get there due to the
 560                // possible values of VimSettings::get_global(cx).default_mode being either Mode::Normal or Mode::Insert.
 561                _ => unreachable!("Invalid default mode"),
 562            };
 563            (initial_helix_mode, Mode::HelixNormal)
 564        } else {
 565            (initial_vim_mode, Mode::Normal)
 566        };
 567
 568        cx.new(|cx| Vim {
 569            mode,
 570            last_mode,
 571            temp_mode: false,
 572            exit_temporary_mode: false,
 573            operator_stack: Vec::new(),
 574            replacements: Vec::new(),
 575
 576            stored_visual_mode: None,
 577            current_tx: None,
 578            undo_last_line_tx: None,
 579            current_anchor: None,
 580            extended_pending_selection_id: None,
 581            undo_modes: HashMap::default(),
 582
 583            status_label: None,
 584            selected_register: None,
 585            search: SearchState::default(),
 586
 587            last_command: None,
 588            running_command: None,
 589
 590            editor: editor.downgrade(),
 591            _subscriptions: vec![
 592                cx.observe_keystrokes(Self::observe_keystrokes),
 593                cx.subscribe_in(&editor, window, |this, _, event, window, cx| {
 594                    this.handle_editor_event(event, window, cx)
 595                }),
 596            ],
 597        })
 598    }
 599
 600    fn register(editor: &mut Editor, window: Option<&mut Window>, cx: &mut Context<Editor>) {
 601        let Some(window) = window else {
 602            return;
 603        };
 604
 605        if !editor.use_modal_editing() {
 606            return;
 607        }
 608
 609        let mut was_enabled = Vim::enabled(cx);
 610        let mut was_helix_enabled = HelixModeSetting::get_global(cx).0;
 611        let mut was_toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;
 612        cx.observe_global_in::<SettingsStore>(window, move |editor, window, cx| {
 613            let enabled = Vim::enabled(cx);
 614            let helix_enabled = HelixModeSetting::get_global(cx).0;
 615            let toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;
 616            if enabled && was_enabled && (toggle != was_toggle) {
 617                if toggle {
 618                    let is_relative = editor
 619                        .addon::<VimAddon>()
 620                        .map(|vim| vim.entity.read(cx).mode != Mode::Insert);
 621                    editor.set_relative_line_number(is_relative, cx)
 622                } else {
 623                    editor.set_relative_line_number(None, cx)
 624                }
 625            }
 626            let helix_changed = was_helix_enabled != helix_enabled;
 627            was_toggle = toggle;
 628            was_helix_enabled = helix_enabled;
 629
 630            let state_changed = (was_enabled != enabled) || (was_enabled && helix_changed);
 631            if !state_changed {
 632                return;
 633            }
 634            if was_enabled {
 635                Self::deactivate(editor, cx);
 636            }
 637            was_enabled = enabled;
 638            if enabled {
 639                Self::activate(editor, window, cx);
 640            }
 641        })
 642        .detach();
 643        if was_enabled {
 644            Self::activate(editor, window, cx)
 645        }
 646    }
 647
 648    fn activate(editor: &mut Editor, window: &mut Window, cx: &mut Context<Editor>) {
 649        let vim = Vim::new(window, cx);
 650        let state = vim.update(cx, |vim, cx| {
 651            if !editor.use_modal_editing() {
 652                vim.mode = Mode::Insert;
 653            }
 654
 655            vim.state_for_editor_settings(cx)
 656        });
 657
 658        Vim::sync_vim_settings_to_editor(&state, editor, window, cx);
 659
 660        editor.register_addon(VimAddon {
 661            entity: vim.clone(),
 662        });
 663
 664        vim.update(cx, |_, cx| {
 665            Vim::action(editor, cx, |vim, _: &SwitchToNormalMode, window, cx| {
 666                vim.switch_mode(Mode::Normal, false, window, cx)
 667            });
 668
 669            Vim::action(editor, cx, |vim, _: &SwitchToInsertMode, window, cx| {
 670                vim.switch_mode(Mode::Insert, false, window, cx)
 671            });
 672
 673            Vim::action(editor, cx, |vim, _: &SwitchToReplaceMode, window, cx| {
 674                vim.switch_mode(Mode::Replace, false, window, cx)
 675            });
 676
 677            Vim::action(editor, cx, |vim, _: &SwitchToVisualMode, window, cx| {
 678                vim.switch_mode(Mode::Visual, false, window, cx)
 679            });
 680
 681            Vim::action(editor, cx, |vim, _: &SwitchToVisualLineMode, window, cx| {
 682                vim.switch_mode(Mode::VisualLine, false, window, cx)
 683            });
 684
 685            Vim::action(
 686                editor,
 687                cx,
 688                |vim, _: &SwitchToVisualBlockMode, window, cx| {
 689                    vim.switch_mode(Mode::VisualBlock, false, window, cx)
 690                },
 691            );
 692
 693            Vim::action(
 694                editor,
 695                cx,
 696                |vim, _: &SwitchToHelixNormalMode, window, cx| {
 697                    vim.switch_mode(Mode::HelixNormal, true, window, cx)
 698                },
 699            );
 700            Vim::action(editor, cx, |_, _: &PushForcedMotion, _, cx| {
 701                Vim::globals(cx).forced_motion = true;
 702            });
 703            Vim::action(editor, cx, |vim, action: &PushObject, window, cx| {
 704                vim.push_operator(
 705                    Operator::Object {
 706                        around: action.around,
 707                    },
 708                    window,
 709                    cx,
 710                )
 711            });
 712
 713            Vim::action(editor, cx, |vim, action: &PushFindForward, window, cx| {
 714                vim.push_operator(
 715                    Operator::FindForward {
 716                        before: action.before,
 717                        multiline: action.multiline,
 718                    },
 719                    window,
 720                    cx,
 721                )
 722            });
 723
 724            Vim::action(editor, cx, |vim, action: &PushFindBackward, window, cx| {
 725                vim.push_operator(
 726                    Operator::FindBackward {
 727                        after: action.after,
 728                        multiline: action.multiline,
 729                    },
 730                    window,
 731                    cx,
 732                )
 733            });
 734
 735            Vim::action(editor, cx, |vim, action: &PushSneak, window, cx| {
 736                vim.push_operator(
 737                    Operator::Sneak {
 738                        first_char: action.first_char,
 739                    },
 740                    window,
 741                    cx,
 742                )
 743            });
 744
 745            Vim::action(editor, cx, |vim, action: &PushSneakBackward, window, cx| {
 746                vim.push_operator(
 747                    Operator::SneakBackward {
 748                        first_char: action.first_char,
 749                    },
 750                    window,
 751                    cx,
 752                )
 753            });
 754
 755            Vim::action(editor, cx, |vim, _: &PushAddSurrounds, window, cx| {
 756                vim.push_operator(Operator::AddSurrounds { target: None }, window, cx)
 757            });
 758
 759            Vim::action(
 760                editor,
 761                cx,
 762                |vim, action: &PushChangeSurrounds, window, cx| {
 763                    vim.push_operator(
 764                        Operator::ChangeSurrounds {
 765                            target: action.target,
 766                            opening: false,
 767                        },
 768                        window,
 769                        cx,
 770                    )
 771                },
 772            );
 773
 774            Vim::action(editor, cx, |vim, action: &PushJump, window, cx| {
 775                vim.push_operator(Operator::Jump { line: action.line }, window, cx)
 776            });
 777
 778            Vim::action(editor, cx, |vim, action: &PushDigraph, window, cx| {
 779                vim.push_operator(
 780                    Operator::Digraph {
 781                        first_char: action.first_char,
 782                    },
 783                    window,
 784                    cx,
 785                )
 786            });
 787
 788            Vim::action(editor, cx, |vim, action: &PushLiteral, window, cx| {
 789                vim.push_operator(
 790                    Operator::Literal {
 791                        prefix: action.prefix.clone(),
 792                    },
 793                    window,
 794                    cx,
 795                )
 796            });
 797
 798            Vim::action(editor, cx, |vim, _: &PushChange, window, cx| {
 799                vim.push_operator(Operator::Change, window, cx)
 800            });
 801
 802            Vim::action(editor, cx, |vim, _: &PushDelete, window, cx| {
 803                vim.push_operator(Operator::Delete, window, cx)
 804            });
 805
 806            Vim::action(editor, cx, |vim, _: &PushYank, window, cx| {
 807                vim.push_operator(Operator::Yank, window, cx)
 808            });
 809
 810            Vim::action(editor, cx, |vim, _: &PushReplace, window, cx| {
 811                vim.push_operator(Operator::Replace, window, cx)
 812            });
 813
 814            Vim::action(editor, cx, |vim, _: &PushDeleteSurrounds, window, cx| {
 815                vim.push_operator(Operator::DeleteSurrounds, window, cx)
 816            });
 817
 818            Vim::action(editor, cx, |vim, _: &PushMark, window, cx| {
 819                vim.push_operator(Operator::Mark, window, cx)
 820            });
 821
 822            Vim::action(editor, cx, |vim, _: &PushIndent, window, cx| {
 823                vim.push_operator(Operator::Indent, window, cx)
 824            });
 825
 826            Vim::action(editor, cx, |vim, _: &PushOutdent, window, cx| {
 827                vim.push_operator(Operator::Outdent, window, cx)
 828            });
 829
 830            Vim::action(editor, cx, |vim, _: &PushAutoIndent, window, cx| {
 831                vim.push_operator(Operator::AutoIndent, window, cx)
 832            });
 833
 834            Vim::action(editor, cx, |vim, _: &PushRewrap, window, cx| {
 835                vim.push_operator(Operator::Rewrap, window, cx)
 836            });
 837
 838            Vim::action(editor, cx, |vim, _: &PushShellCommand, window, cx| {
 839                vim.push_operator(Operator::ShellCommand, window, cx)
 840            });
 841
 842            Vim::action(editor, cx, |vim, _: &PushLowercase, window, cx| {
 843                vim.push_operator(Operator::Lowercase, window, cx)
 844            });
 845
 846            Vim::action(editor, cx, |vim, _: &PushUppercase, window, cx| {
 847                vim.push_operator(Operator::Uppercase, window, cx)
 848            });
 849
 850            Vim::action(editor, cx, |vim, _: &PushOppositeCase, window, cx| {
 851                vim.push_operator(Operator::OppositeCase, window, cx)
 852            });
 853
 854            Vim::action(editor, cx, |vim, _: &PushRot13, window, cx| {
 855                vim.push_operator(Operator::Rot13, window, cx)
 856            });
 857
 858            Vim::action(editor, cx, |vim, _: &PushRot47, window, cx| {
 859                vim.push_operator(Operator::Rot47, window, cx)
 860            });
 861
 862            Vim::action(editor, cx, |vim, _: &PushRegister, window, cx| {
 863                vim.push_operator(Operator::Register, window, cx)
 864            });
 865
 866            Vim::action(editor, cx, |vim, _: &PushRecordRegister, window, cx| {
 867                vim.push_operator(Operator::RecordRegister, window, cx)
 868            });
 869
 870            Vim::action(editor, cx, |vim, _: &PushReplayRegister, window, cx| {
 871                vim.push_operator(Operator::ReplayRegister, window, cx)
 872            });
 873
 874            Vim::action(
 875                editor,
 876                cx,
 877                |vim, _: &PushReplaceWithRegister, window, cx| {
 878                    vim.push_operator(Operator::ReplaceWithRegister, window, cx)
 879                },
 880            );
 881
 882            Vim::action(editor, cx, |vim, _: &Exchange, window, cx| {
 883                if vim.mode.is_visual() {
 884                    vim.exchange_visual(window, cx)
 885                } else {
 886                    vim.push_operator(Operator::Exchange, window, cx)
 887                }
 888            });
 889
 890            Vim::action(editor, cx, |vim, _: &ClearExchange, window, cx| {
 891                vim.clear_exchange(window, cx)
 892            });
 893
 894            Vim::action(editor, cx, |vim, _: &PushToggleComments, window, cx| {
 895                vim.push_operator(Operator::ToggleComments, window, cx)
 896            });
 897
 898            Vim::action(editor, cx, |vim, _: &ClearOperators, window, cx| {
 899                vim.clear_operator(window, cx)
 900            });
 901            Vim::action(editor, cx, |vim, n: &Number, window, cx| {
 902                vim.push_count_digit(n.0, window, cx);
 903            });
 904            Vim::action(editor, cx, |vim, _: &Tab, window, cx| {
 905                vim.input_ignored(" ".into(), window, cx)
 906            });
 907            Vim::action(
 908                editor,
 909                cx,
 910                |vim, action: &editor::actions::AcceptEditPrediction, window, cx| {
 911                    vim.update_editor(cx, |_, editor, cx| {
 912                        editor.accept_edit_prediction(action, window, cx);
 913                    });
 914                    // In non-insertion modes, predictions will be hidden and instead a jump will be
 915                    // displayed (and performed by `accept_edit_prediction`). This switches to
 916                    // insert mode so that the prediction is displayed after the jump.
 917                    match vim.mode {
 918                        Mode::Replace => {}
 919                        _ => vim.switch_mode(Mode::Insert, true, window, cx),
 920                    };
 921                },
 922            );
 923            Vim::action(editor, cx, |vim, _: &Enter, window, cx| {
 924                vim.input_ignored("\n".into(), window, cx)
 925            });
 926            Vim::action(editor, cx, |vim, _: &PushHelixMatch, window, cx| {
 927                vim.push_operator(Operator::HelixMatch, window, cx)
 928            });
 929            Vim::action(editor, cx, |vim, action: &PushHelixNext, window, cx| {
 930                vim.push_operator(
 931                    Operator::HelixNext {
 932                        around: action.around,
 933                    },
 934                    window,
 935                    cx,
 936                );
 937            });
 938            Vim::action(editor, cx, |vim, action: &PushHelixPrevious, window, cx| {
 939                vim.push_operator(
 940                    Operator::HelixPrevious {
 941                        around: action.around,
 942                    },
 943                    window,
 944                    cx,
 945                );
 946            });
 947
 948            Vim::action(
 949                editor,
 950                cx,
 951                |vim, _: &editor::actions::Paste, window, cx| match vim.mode {
 952                    Mode::Replace => vim.paste_replace(window, cx),
 953                    Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
 954                        vim.selected_register.replace('+');
 955                        vim.paste(&VimPaste::default(), window, cx);
 956                    }
 957                    _ => {
 958                        vim.update_editor(cx, |_, editor, cx| editor.paste(&Paste, window, cx));
 959                    }
 960                },
 961            );
 962
 963            normal::register(editor, cx);
 964            insert::register(editor, cx);
 965            helix::register(editor, cx);
 966            motion::register(editor, cx);
 967            command::register(editor, cx);
 968            replace::register(editor, cx);
 969            indent::register(editor, cx);
 970            rewrap::register(editor, cx);
 971            object::register(editor, cx);
 972            visual::register(editor, cx);
 973            change_list::register(editor, cx);
 974            digraph::register(editor, cx);
 975
 976            if editor.is_focused(window) {
 977                cx.defer_in(window, |vim, window, cx| {
 978                    vim.focused(false, window, cx);
 979                })
 980            }
 981        })
 982    }
 983
 984    fn deactivate(editor: &mut Editor, cx: &mut Context<Editor>) {
 985        editor.set_cursor_shape(
 986            EditorSettings::get_global(cx)
 987                .cursor_shape
 988                .unwrap_or_default(),
 989            cx,
 990        );
 991        editor.set_clip_at_line_ends(false, cx);
 992        editor.set_collapse_matches(false);
 993        editor.set_input_enabled(true);
 994        editor.set_expects_character_input(true);
 995        editor.set_autoindent(true);
 996        editor.selections.set_line_mode(false);
 997        editor.unregister_addon::<VimAddon>();
 998        editor.set_relative_line_number(None, cx);
 999        if let Some(vim) = Vim::globals(cx).focused_vim()
1000            && vim.entity_id() == cx.entity().entity_id()
1001        {
1002            Vim::globals(cx).focused_vim = None;
1003        }
1004    }
1005
1006    /// Register an action on the editor.
1007    pub fn action<A: Action>(
1008        editor: &mut Editor,
1009        cx: &mut Context<Vim>,
1010        f: impl Fn(&mut Vim, &A, &mut Window, &mut Context<Vim>) + 'static,
1011    ) {
1012        let subscription = editor.register_action(cx.listener(move |vim, action, window, cx| {
1013            if !Vim::globals(cx).dot_replaying {
1014                if vim.status_label.take().is_some() {
1015                    cx.notify();
1016                }
1017            }
1018            f(vim, action, window, cx);
1019        }));
1020        cx.on_release(|_, _| drop(subscription)).detach();
1021    }
1022
1023    pub fn editor(&self) -> Option<Entity<Editor>> {
1024        self.editor.upgrade()
1025    }
1026
1027    pub fn workspace(&self, window: &Window, cx: &App) -> Option<Entity<Workspace>> {
1028        Workspace::for_window(window, cx)
1029    }
1030
1031    pub fn pane(&self, window: &Window, cx: &Context<Self>) -> Option<Entity<Pane>> {
1032        self.workspace(window, cx)
1033            .map(|workspace| workspace.read(cx).focused_pane(window, cx))
1034    }
1035
1036    pub fn enabled(cx: &mut App) -> bool {
1037        VimModeSetting::get_global(cx).0 || HelixModeSetting::get_global(cx).0
1038    }
1039
1040    /// Called whenever an keystroke is typed so vim can observe all actions
1041    /// and keystrokes accordingly.
1042    fn observe_keystrokes(
1043        &mut self,
1044        keystroke_event: &KeystrokeEvent,
1045        window: &mut Window,
1046        cx: &mut Context<Self>,
1047    ) {
1048        if self.exit_temporary_mode {
1049            self.exit_temporary_mode = false;
1050            // Don't switch to insert mode if the action is temporary_normal.
1051            if let Some(action) = keystroke_event.action.as_ref()
1052                && action.as_any().downcast_ref::<TemporaryNormal>().is_some()
1053            {
1054                return;
1055            }
1056            self.switch_mode(Mode::Insert, false, window, cx)
1057        }
1058        if let Some(action) = keystroke_event.action.as_ref() {
1059            // Keystroke is handled by the vim system, so continue forward
1060            if action.name().starts_with("vim::") {
1061                self.update_editor(cx, |_, editor, cx| {
1062                    editor.hide_mouse_cursor(HideMouseCursorOrigin::MovementAction, cx)
1063                });
1064
1065                return;
1066            }
1067        } else if window.has_pending_keystrokes() || keystroke_event.keystroke.is_ime_in_progress()
1068        {
1069            return;
1070        }
1071
1072        if let Some(operator) = self.active_operator() {
1073            match operator {
1074                Operator::Literal { prefix } => {
1075                    self.handle_literal_keystroke(
1076                        keystroke_event,
1077                        prefix.unwrap_or_default(),
1078                        window,
1079                        cx,
1080                    );
1081                }
1082                _ if !operator.is_waiting(self.mode) => {
1083                    self.clear_operator(window, cx);
1084                    self.stop_recording_immediately(Box::new(ClearOperators), cx)
1085                }
1086                _ => {}
1087            }
1088        }
1089    }
1090
1091    fn handle_editor_event(
1092        &mut self,
1093        event: &EditorEvent,
1094        window: &mut Window,
1095        cx: &mut Context<Self>,
1096    ) {
1097        match event {
1098            EditorEvent::Focused => self.focused(true, window, cx),
1099            EditorEvent::Blurred => self.blurred(window, cx),
1100            EditorEvent::SelectionsChanged { local: true } => {
1101                self.local_selections_changed(window, cx);
1102            }
1103            EditorEvent::InputIgnored { text } => {
1104                self.input_ignored(text.clone(), window, cx);
1105                Vim::globals(cx).observe_insertion(text, None)
1106            }
1107            EditorEvent::InputHandled {
1108                text,
1109                utf16_range_to_replace: range_to_replace,
1110            } => Vim::globals(cx).observe_insertion(text, range_to_replace.clone()),
1111            EditorEvent::TransactionBegun { transaction_id } => {
1112                self.transaction_begun(*transaction_id, window, cx)
1113            }
1114            EditorEvent::TransactionUndone { transaction_id } => {
1115                self.transaction_undone(transaction_id, window, cx)
1116            }
1117            EditorEvent::Edited { .. } => self.push_to_change_list(window, cx),
1118            EditorEvent::FocusedIn => self.sync_vim_settings(window, cx),
1119            EditorEvent::CursorShapeChanged => self.cursor_shape_changed(window, cx),
1120            EditorEvent::PushedToNavHistory {
1121                anchor,
1122                is_deactivate,
1123            } => {
1124                self.update_editor(cx, |vim, editor, cx| {
1125                    let mark = if *is_deactivate {
1126                        "\"".to_string()
1127                    } else {
1128                        "'".to_string()
1129                    };
1130                    vim.set_mark(mark, vec![*anchor], editor.buffer(), window, cx);
1131                });
1132            }
1133            _ => {}
1134        }
1135    }
1136
1137    fn push_operator(&mut self, operator: Operator, window: &mut Window, cx: &mut Context<Self>) {
1138        if operator.starts_dot_recording() {
1139            self.start_recording(cx);
1140        }
1141        // Since these operations can only be entered with pre-operators,
1142        // we need to clear the previous operators when pushing,
1143        // so that the current stack is the most correct
1144        if matches!(
1145            operator,
1146            Operator::AddSurrounds { .. }
1147                | Operator::ChangeSurrounds { .. }
1148                | Operator::DeleteSurrounds
1149                | Operator::Exchange
1150        ) {
1151            self.operator_stack.clear();
1152        };
1153        self.operator_stack.push(operator);
1154        self.sync_vim_settings(window, cx);
1155    }
1156
1157    pub fn switch_mode(
1158        &mut self,
1159        mode: Mode,
1160        leave_selections: bool,
1161        window: &mut Window,
1162        cx: &mut Context<Self>,
1163    ) {
1164        if self.temp_mode && mode == Mode::Normal {
1165            self.temp_mode = false;
1166            self.switch_mode(Mode::Normal, leave_selections, window, cx);
1167            self.switch_mode(Mode::Insert, false, window, cx);
1168            return;
1169        } else if self.temp_mode
1170            && !matches!(mode, Mode::Visual | Mode::VisualLine | Mode::VisualBlock)
1171        {
1172            self.temp_mode = false;
1173        }
1174
1175        let last_mode = self.mode;
1176        let prior_mode = self.last_mode;
1177        let prior_tx = self.current_tx;
1178        self.last_mode = last_mode;
1179        self.mode = mode;
1180        self.operator_stack.clear();
1181        self.selected_register.take();
1182        self.cancel_running_command(window, cx);
1183        if mode == Mode::Normal || mode != last_mode {
1184            self.current_tx.take();
1185            self.current_anchor.take();
1186            self.update_editor(cx, |_, editor, _| {
1187                editor.clear_selection_drag_state();
1188            });
1189        }
1190        Vim::take_forced_motion(cx);
1191        if mode != Mode::Insert && mode != Mode::Replace {
1192            Vim::take_count(cx);
1193        }
1194
1195        // Sync editor settings like clip mode
1196        self.sync_vim_settings(window, cx);
1197
1198        if VimSettings::get_global(cx).toggle_relative_line_numbers
1199            && self.mode != self.last_mode
1200            && (self.mode == Mode::Insert || self.last_mode == Mode::Insert)
1201        {
1202            self.update_editor(cx, |vim, editor, cx| {
1203                let is_relative = vim.mode != Mode::Insert;
1204                editor.set_relative_line_number(Some(is_relative), cx)
1205            });
1206        }
1207        if HelixModeSetting::get_global(cx).0 {
1208            if self.mode == Mode::Normal {
1209                self.mode = Mode::HelixNormal
1210            } else if self.mode == Mode::Visual {
1211                self.mode = Mode::HelixSelect
1212            }
1213        }
1214
1215        if leave_selections {
1216            return;
1217        }
1218
1219        if !mode.is_visual() && last_mode.is_visual() && !last_mode.is_helix() {
1220            self.create_visual_marks(last_mode, window, cx);
1221        }
1222
1223        // Adjust selections
1224        self.update_editor(cx, |vim, editor, cx| {
1225            if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
1226            {
1227                vim.visual_block_motion(true, editor, window, cx, &mut |_, point, goal| {
1228                    Some((point, goal))
1229                })
1230            }
1231            if (last_mode == Mode::Insert || last_mode == Mode::Replace)
1232                && let Some(prior_tx) = prior_tx
1233            {
1234                editor.group_until_transaction(prior_tx, cx)
1235            }
1236
1237            editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1238                // we cheat with visual block mode and use multiple cursors.
1239                // the cost of this cheat is we need to convert back to a single
1240                // cursor whenever vim would.
1241                if last_mode == Mode::VisualBlock
1242                    && (mode != Mode::VisualBlock && mode != Mode::Insert)
1243                {
1244                    let tail = s.oldest_anchor().tail();
1245                    let head = s.newest_anchor().head();
1246                    s.select_anchor_ranges(vec![tail..head]);
1247                } else if last_mode == Mode::Insert
1248                    && prior_mode == Mode::VisualBlock
1249                    && mode != Mode::VisualBlock
1250                {
1251                    let pos = s.first_anchor().head();
1252                    s.select_anchor_ranges(vec![pos..pos])
1253                }
1254
1255                let mut should_extend_pending = false;
1256                if !last_mode.is_visual()
1257                    && mode.is_visual()
1258                    && let Some(pending) = s.pending_anchor()
1259                {
1260                    let snapshot = s.display_snapshot();
1261                    let is_empty = pending
1262                        .start
1263                        .cmp(&pending.end, &snapshot.buffer_snapshot())
1264                        .is_eq();
1265                    should_extend_pending = pending.reversed
1266                        && !is_empty
1267                        && vim.extended_pending_selection_id != Some(pending.id);
1268                };
1269
1270                if should_extend_pending {
1271                    let snapshot = s.display_snapshot();
1272                    s.change_with(&snapshot, |map| {
1273                        if let Some(pending) = map.pending_anchor_mut() {
1274                            let end = pending.end.to_point(&snapshot.buffer_snapshot());
1275                            let end = end.to_display_point(&snapshot);
1276                            let new_end = movement::right(&snapshot, end);
1277                            pending.end = snapshot
1278                                .buffer_snapshot()
1279                                .anchor_before(new_end.to_point(&snapshot));
1280                        }
1281                    });
1282                    vim.extended_pending_selection_id = s.pending_anchor().map(|p| p.id)
1283                }
1284
1285                s.move_with(&mut |map, selection| {
1286                    if last_mode.is_visual() && !last_mode.is_helix() && !mode.is_visual() {
1287                        let mut point = selection.head();
1288                        if !selection.reversed && !selection.is_empty() {
1289                            point = movement::left(map, selection.head());
1290                        } else if selection.is_empty() {
1291                            point = map.clip_point(point, Bias::Left);
1292                        }
1293                        selection.collapse_to(point, selection.goal)
1294                    } else if !last_mode.is_visual() && mode.is_visual() {
1295                        if selection.is_empty() {
1296                            selection.end = movement::right(map, selection.start);
1297                        }
1298                    }
1299                });
1300            })
1301        });
1302    }
1303
1304    pub fn take_count(cx: &mut App) -> Option<usize> {
1305        let global_state = cx.global_mut::<VimGlobals>();
1306        if global_state.dot_replaying {
1307            return global_state.recorded_count;
1308        }
1309
1310        let count = if global_state.post_count.is_none() && global_state.pre_count.is_none() {
1311            return None;
1312        } else {
1313            Some(
1314                global_state.post_count.take().unwrap_or(1)
1315                    * global_state.pre_count.take().unwrap_or(1),
1316            )
1317        };
1318
1319        if global_state.dot_recording {
1320            global_state.recording_count = count;
1321        }
1322        count
1323    }
1324
1325    pub fn take_forced_motion(cx: &mut App) -> bool {
1326        let global_state = cx.global_mut::<VimGlobals>();
1327        let forced_motion = global_state.forced_motion;
1328        global_state.forced_motion = false;
1329        forced_motion
1330    }
1331
1332    pub fn cursor_shape(&self, cx: &App) -> CursorShape {
1333        let cursor_shape = VimSettings::get_global(cx).cursor_shape;
1334        match self.mode {
1335            Mode::Normal => {
1336                if let Some(operator) = self.operator_stack.last() {
1337                    match operator {
1338                        // Navigation operators -> Block cursor
1339                        Operator::FindForward { .. }
1340                        | Operator::FindBackward { .. }
1341                        | Operator::Mark
1342                        | Operator::Jump { .. }
1343                        | Operator::Register
1344                        | Operator::RecordRegister
1345                        | Operator::ReplayRegister => CursorShape::Block,
1346
1347                        // All other operators -> Underline cursor
1348                        _ => CursorShape::Underline,
1349                    }
1350                } else {
1351                    cursor_shape.normal
1352                }
1353            }
1354            Mode::HelixNormal => cursor_shape.normal,
1355            Mode::Replace => cursor_shape.replace,
1356            Mode::Visual | Mode::VisualLine | Mode::VisualBlock | Mode::HelixSelect => {
1357                cursor_shape.visual
1358            }
1359            Mode::Insert => match cursor_shape.insert {
1360                InsertModeCursorShape::Explicit(shape) => shape,
1361                InsertModeCursorShape::Inherit => {
1362                    let editor_settings = EditorSettings::get_global(cx);
1363                    editor_settings.cursor_shape.unwrap_or_default()
1364                }
1365            },
1366        }
1367    }
1368
1369    fn expects_character_input(&self) -> bool {
1370        if let Some(operator) = self.operator_stack.last() {
1371            if operator.is_waiting(self.mode) {
1372                return true;
1373            }
1374        }
1375        self.editor_input_enabled()
1376    }
1377
1378    pub fn editor_input_enabled(&self) -> bool {
1379        match self.mode {
1380            Mode::Insert => {
1381                if let Some(operator) = self.operator_stack.last() {
1382                    !operator.is_waiting(self.mode)
1383                } else {
1384                    true
1385                }
1386            }
1387            Mode::Normal
1388            | Mode::HelixNormal
1389            | Mode::Replace
1390            | Mode::Visual
1391            | Mode::VisualLine
1392            | Mode::VisualBlock
1393            | Mode::HelixSelect => false,
1394        }
1395    }
1396
1397    pub fn should_autoindent(&self) -> bool {
1398        !(self.mode == Mode::Insert && self.last_mode == Mode::VisualBlock)
1399    }
1400
1401    pub fn clip_at_line_ends(&self) -> bool {
1402        match self.mode {
1403            Mode::Insert
1404            | Mode::Visual
1405            | Mode::VisualLine
1406            | Mode::VisualBlock
1407            | Mode::Replace
1408            | Mode::HelixNormal
1409            | Mode::HelixSelect => false,
1410            Mode::Normal => true,
1411        }
1412    }
1413
1414    pub fn extend_key_context(&self, context: &mut KeyContext, cx: &App) {
1415        let mut mode = match self.mode {
1416            Mode::Normal => "normal",
1417            Mode::Visual | Mode::VisualLine | Mode::VisualBlock => "visual",
1418            Mode::Insert => "insert",
1419            Mode::Replace => "replace",
1420            Mode::HelixNormal => "helix_normal",
1421            Mode::HelixSelect => "helix_select",
1422        }
1423        .to_string();
1424
1425        let mut operator_id = "none";
1426
1427        let active_operator = self.active_operator();
1428        if active_operator.is_none() && cx.global::<VimGlobals>().pre_count.is_some()
1429            || active_operator.is_some() && cx.global::<VimGlobals>().post_count.is_some()
1430        {
1431            context.add("VimCount");
1432        }
1433
1434        if let Some(active_operator) = active_operator {
1435            if active_operator.is_waiting(self.mode) {
1436                if matches!(active_operator, Operator::Literal { .. }) {
1437                    mode = "literal".to_string();
1438                } else {
1439                    mode = "waiting".to_string();
1440                }
1441            } else {
1442                operator_id = active_operator.id();
1443                mode = "operator".to_string();
1444            }
1445        }
1446
1447        if mode == "normal"
1448            || mode == "visual"
1449            || mode == "operator"
1450            || mode == "helix_normal"
1451            || mode == "helix_select"
1452        {
1453            context.add("VimControl");
1454        }
1455        context.set("vim_mode", mode);
1456        context.set("vim_operator", operator_id);
1457    }
1458
1459    fn focused(&mut self, preserve_selection: bool, window: &mut Window, cx: &mut Context<Self>) {
1460        // If editor gains focus while search bar is still open (not dismissed),
1461        // the user has explicitly navigated away - clear prior_selections so we
1462        // don't restore to the old position if they later dismiss the search.
1463        if !self.search.prior_selections.is_empty() {
1464            if let Some(pane) = self.pane(window, cx) {
1465                let search_still_open = pane
1466                    .read(cx)
1467                    .toolbar()
1468                    .read(cx)
1469                    .item_of_type::<BufferSearchBar>()
1470                    .is_some_and(|bar| !bar.read(cx).is_dismissed());
1471                if search_still_open {
1472                    self.search.prior_selections.clear();
1473                }
1474            }
1475        }
1476
1477        let Some(editor) = self.editor() else {
1478            return;
1479        };
1480        let newest_selection_empty = editor.update(cx, |editor, cx| {
1481            editor
1482                .selections
1483                .newest::<MultiBufferOffset>(&editor.display_snapshot(cx))
1484                .is_empty()
1485        });
1486        let editor = editor.read(cx);
1487        let editor_mode = editor.mode();
1488
1489        if editor_mode.is_full()
1490            && !newest_selection_empty
1491            && self.mode == Mode::Normal
1492            // When following someone, don't switch vim mode.
1493            && editor.leader_id().is_none()
1494        {
1495            if preserve_selection {
1496                self.switch_mode(Mode::Visual, true, window, cx);
1497            } else {
1498                self.update_editor(cx, |_, editor, cx| {
1499                    editor.set_clip_at_line_ends(false, cx);
1500                    editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1501                        s.move_with(&mut |_, selection| {
1502                            selection.collapse_to(selection.start, selection.goal)
1503                        })
1504                    });
1505                });
1506            }
1507        }
1508
1509        cx.emit(VimEvent::Focused);
1510        self.sync_vim_settings(window, cx);
1511
1512        if VimSettings::get_global(cx).toggle_relative_line_numbers {
1513            if let Some(old_vim) = Vim::globals(cx).focused_vim() {
1514                if old_vim.entity_id() != cx.entity().entity_id() {
1515                    old_vim.update(cx, |vim, cx| {
1516                        vim.update_editor(cx, |_, editor, cx| {
1517                            editor.set_relative_line_number(None, cx)
1518                        });
1519                    });
1520
1521                    self.update_editor(cx, |vim, editor, cx| {
1522                        let is_relative = vim.mode != Mode::Insert;
1523                        editor.set_relative_line_number(Some(is_relative), cx)
1524                    });
1525                }
1526            } else {
1527                self.update_editor(cx, |vim, editor, cx| {
1528                    let is_relative = vim.mode != Mode::Insert;
1529                    editor.set_relative_line_number(Some(is_relative), cx)
1530                });
1531            }
1532        }
1533        Vim::globals(cx).focused_vim = Some(cx.entity().downgrade());
1534    }
1535
1536    fn blurred(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1537        self.stop_recording_immediately(NormalBefore.boxed_clone(), cx);
1538        self.store_visual_marks(window, cx);
1539        self.clear_operator(window, cx);
1540        self.update_editor(cx, |vim, editor, cx| {
1541            if vim.cursor_shape(cx) == CursorShape::Block {
1542                editor.set_cursor_shape(CursorShape::Hollow, cx);
1543            }
1544        });
1545    }
1546
1547    fn cursor_shape_changed(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1548        self.update_editor(cx, |vim, editor, cx| {
1549            editor.set_cursor_shape(vim.cursor_shape(cx), cx);
1550        });
1551    }
1552
1553    fn update_editor<S>(
1554        &mut self,
1555        cx: &mut Context<Self>,
1556        update: impl FnOnce(&mut Self, &mut Editor, &mut Context<Editor>) -> S,
1557    ) -> Option<S> {
1558        let editor = self.editor.upgrade()?;
1559        Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
1560    }
1561
1562    fn editor_selections(&mut self, _: &mut Window, cx: &mut Context<Self>) -> Vec<Range<Anchor>> {
1563        self.update_editor(cx, |_, editor, _| {
1564            editor
1565                .selections
1566                .disjoint_anchors_arc()
1567                .iter()
1568                .map(|selection| selection.tail()..selection.head())
1569                .collect()
1570        })
1571        .unwrap_or_default()
1572    }
1573
1574    fn editor_cursor_word(
1575        &mut self,
1576        window: &mut Window,
1577        cx: &mut Context<Self>,
1578    ) -> Option<String> {
1579        self.update_editor(cx, |_, editor, cx| {
1580            let snapshot = &editor.snapshot(window, cx);
1581            let selection = editor
1582                .selections
1583                .newest::<MultiBufferOffset>(&snapshot.display_snapshot);
1584
1585            let snapshot = snapshot.buffer_snapshot();
1586            let (range, kind) =
1587                snapshot.surrounding_word(selection.start, Some(CharScopeContext::Completion));
1588            if kind == Some(CharKind::Word) {
1589                let text: String = snapshot.text_for_range(range).collect();
1590                if !text.trim().is_empty() {
1591                    return Some(text);
1592                }
1593            }
1594
1595            None
1596        })
1597        .unwrap_or_default()
1598    }
1599
1600    /// When doing an action that modifies the buffer, we start recording so that `.`
1601    /// will replay the action.
1602    pub fn start_recording(&mut self, cx: &mut Context<Self>) {
1603        Vim::update_globals(cx, |globals, cx| {
1604            if !globals.dot_replaying {
1605                globals.dot_recording = true;
1606                globals.recording_actions = Default::default();
1607                globals.recording_count = None;
1608                globals.recording_register_for_dot = self.selected_register;
1609
1610                let selections = self.editor().map(|editor| {
1611                    editor.update(cx, |editor, cx| {
1612                        let snapshot = editor.display_snapshot(cx);
1613
1614                        (
1615                            editor.selections.oldest::<Point>(&snapshot),
1616                            editor.selections.newest::<Point>(&snapshot),
1617                        )
1618                    })
1619                });
1620
1621                if let Some((oldest, newest)) = selections {
1622                    globals.recorded_selection = match self.mode {
1623                        Mode::Visual if newest.end.row == newest.start.row => {
1624                            RecordedSelection::SingleLine {
1625                                cols: newest.end.column - newest.start.column,
1626                            }
1627                        }
1628                        Mode::Visual => RecordedSelection::Visual {
1629                            rows: newest.end.row - newest.start.row,
1630                            cols: newest.end.column,
1631                        },
1632                        Mode::VisualLine => RecordedSelection::VisualLine {
1633                            rows: newest.end.row - newest.start.row,
1634                        },
1635                        Mode::VisualBlock => RecordedSelection::VisualBlock {
1636                            rows: newest.end.row.abs_diff(oldest.start.row),
1637                            cols: newest.end.column.abs_diff(oldest.start.column),
1638                        },
1639                        _ => RecordedSelection::None,
1640                    }
1641                } else {
1642                    globals.recorded_selection = RecordedSelection::None;
1643                }
1644            }
1645        })
1646    }
1647
1648    pub fn stop_replaying(&mut self, cx: &mut Context<Self>) {
1649        let globals = Vim::globals(cx);
1650        globals.dot_replaying = false;
1651        if let Some(replayer) = globals.replayer.take() {
1652            replayer.stop();
1653        }
1654    }
1655
1656    /// When finishing an action that modifies the buffer, stop recording.
1657    /// as you usually call this within a keystroke handler we also ensure that
1658    /// the current action is recorded.
1659    pub fn stop_recording(&mut self, cx: &mut Context<Self>) {
1660        let globals = Vim::globals(cx);
1661        if globals.dot_recording {
1662            globals.stop_recording_after_next_action = true;
1663        }
1664        self.exit_temporary_mode = self.temp_mode;
1665    }
1666
1667    /// Stops recording actions immediately rather than waiting until after the
1668    /// next action to stop recording.
1669    ///
1670    /// This doesn't include the current action.
1671    pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>, cx: &mut Context<Self>) {
1672        let globals = Vim::globals(cx);
1673        if globals.dot_recording {
1674            globals
1675                .recording_actions
1676                .push(ReplayableAction::Action(action.boxed_clone()));
1677            globals.recorded_actions = mem::take(&mut globals.recording_actions);
1678            globals.recorded_count = globals.recording_count.take();
1679            globals.dot_recording = false;
1680            globals.stop_recording_after_next_action = false;
1681        }
1682        self.exit_temporary_mode = self.temp_mode;
1683    }
1684
1685    /// Explicitly record one action (equivalents to start_recording and stop_recording)
1686    pub fn record_current_action(&mut self, cx: &mut Context<Self>) {
1687        self.start_recording(cx);
1688        self.stop_recording(cx);
1689    }
1690
1691    fn push_count_digit(&mut self, number: usize, window: &mut Window, cx: &mut Context<Self>) {
1692        if self.active_operator().is_some() {
1693            let post_count = Vim::globals(cx).post_count.unwrap_or(0);
1694
1695            Vim::globals(cx).post_count = Some(
1696                post_count
1697                    .checked_mul(10)
1698                    .and_then(|post_count| post_count.checked_add(number))
1699                    .filter(|post_count| *post_count < isize::MAX as usize)
1700                    .unwrap_or(post_count),
1701            )
1702        } else {
1703            let pre_count = Vim::globals(cx).pre_count.unwrap_or(0);
1704
1705            Vim::globals(cx).pre_count = Some(
1706                pre_count
1707                    .checked_mul(10)
1708                    .and_then(|pre_count| pre_count.checked_add(number))
1709                    .filter(|pre_count| *pre_count < isize::MAX as usize)
1710                    .unwrap_or(pre_count),
1711            )
1712        }
1713        // update the keymap so that 0 works
1714        self.sync_vim_settings(window, cx)
1715    }
1716
1717    fn select_register(&mut self, register: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
1718        if register.chars().count() == 1 {
1719            self.selected_register
1720                .replace(register.chars().next().unwrap());
1721        }
1722        self.operator_stack.clear();
1723        self.sync_vim_settings(window, cx);
1724    }
1725
1726    fn maybe_pop_operator(&mut self) -> Option<Operator> {
1727        self.operator_stack.pop()
1728    }
1729
1730    fn pop_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Operator {
1731        let popped_operator = self.operator_stack.pop()
1732            .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
1733        self.sync_vim_settings(window, cx);
1734        popped_operator
1735    }
1736
1737    fn clear_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1738        Vim::take_count(cx);
1739        Vim::take_forced_motion(cx);
1740        self.selected_register.take();
1741        self.operator_stack.clear();
1742        self.sync_vim_settings(window, cx);
1743    }
1744
1745    fn active_operator(&self) -> Option<Operator> {
1746        self.operator_stack.last().cloned()
1747    }
1748
1749    fn transaction_begun(
1750        &mut self,
1751        transaction_id: TransactionId,
1752        _window: &mut Window,
1753        _: &mut Context<Self>,
1754    ) {
1755        let mode = if (self.mode == Mode::Insert
1756            || self.mode == Mode::Replace
1757            || self.mode == Mode::Normal)
1758            && self.current_tx.is_none()
1759        {
1760            self.current_tx = Some(transaction_id);
1761            self.last_mode
1762        } else {
1763            self.mode
1764        };
1765        if mode == Mode::VisualLine || mode == Mode::VisualBlock {
1766            self.undo_modes.insert(transaction_id, mode);
1767        }
1768    }
1769
1770    fn transaction_undone(
1771        &mut self,
1772        transaction_id: &TransactionId,
1773        window: &mut Window,
1774        cx: &mut Context<Self>,
1775    ) {
1776        match self.mode {
1777            Mode::VisualLine | Mode::VisualBlock | Mode::Visual | Mode::HelixSelect => {
1778                self.update_editor(cx, |vim, editor, cx| {
1779                    let original_mode = vim.undo_modes.get(transaction_id);
1780                    editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1781                        match original_mode {
1782                            Some(Mode::VisualLine) => {
1783                                s.move_with(&mut |map, selection| {
1784                                    selection.collapse_to(
1785                                        map.prev_line_boundary(selection.start.to_point(map)).1,
1786                                        SelectionGoal::None,
1787                                    )
1788                                });
1789                            }
1790                            Some(Mode::VisualBlock) => {
1791                                let mut first = s.first_anchor();
1792                                first.collapse_to(first.start, first.goal);
1793                                s.select_anchors(vec![first]);
1794                            }
1795                            _ => {
1796                                s.move_with(&mut |map, selection| {
1797                                    selection.collapse_to(
1798                                        map.clip_at_line_end(selection.start),
1799                                        selection.goal,
1800                                    );
1801                                });
1802                            }
1803                        }
1804                    });
1805                });
1806                self.switch_mode(Mode::Normal, true, window, cx)
1807            }
1808            Mode::Normal => {
1809                self.update_editor(cx, |_, editor, cx| {
1810                    editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1811                        s.move_with(&mut |map, selection| {
1812                            selection
1813                                .collapse_to(map.clip_at_line_end(selection.end), selection.goal)
1814                        })
1815                    })
1816                });
1817            }
1818            Mode::Insert | Mode::Replace | Mode::HelixNormal => {}
1819        }
1820    }
1821
1822    fn local_selections_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1823        let Some(editor) = self.editor() else { return };
1824
1825        if editor.read(cx).leader_id().is_some() {
1826            return;
1827        }
1828
1829        let newest = editor.read(cx).selections.newest_anchor().clone();
1830        let is_multicursor = editor.read(cx).selections.count() > 1;
1831        if self.mode == Mode::Insert && self.current_tx.is_some() {
1832            if let Some(current_anchor) = &self.current_anchor {
1833                if current_anchor != &newest
1834                    && let Some(tx_id) = self.current_tx.take()
1835                {
1836                    self.update_editor(cx, |_, editor, cx| {
1837                        editor.group_until_transaction(tx_id, cx)
1838                    });
1839                }
1840            } else {
1841                self.current_anchor = Some(newest);
1842            }
1843        } else if self.mode == Mode::Normal && newest.start != newest.end {
1844            if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
1845                self.switch_mode(Mode::VisualBlock, false, window, cx);
1846            } else {
1847                self.switch_mode(Mode::Visual, false, window, cx)
1848            }
1849        } else if newest.start == newest.end
1850            && !is_multicursor
1851            && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&self.mode)
1852        {
1853            self.switch_mode(Mode::Normal, false, window, cx);
1854        }
1855    }
1856
1857    fn input_ignored(&mut self, text: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
1858        if text.is_empty() {
1859            return;
1860        }
1861
1862        match self.active_operator() {
1863            Some(Operator::FindForward { before, multiline }) => {
1864                let find = Motion::FindForward {
1865                    before,
1866                    char: text.chars().next().unwrap(),
1867                    mode: if multiline {
1868                        FindRange::MultiLine
1869                    } else {
1870                        FindRange::SingleLine
1871                    },
1872                    smartcase: VimSettings::get_global(cx).use_smartcase_find,
1873                };
1874                Vim::globals(cx).last_find = Some(find.clone());
1875                self.motion(find, window, cx)
1876            }
1877            Some(Operator::FindBackward { after, multiline }) => {
1878                let find = Motion::FindBackward {
1879                    after,
1880                    char: text.chars().next().unwrap(),
1881                    mode: if multiline {
1882                        FindRange::MultiLine
1883                    } else {
1884                        FindRange::SingleLine
1885                    },
1886                    smartcase: VimSettings::get_global(cx).use_smartcase_find,
1887                };
1888                Vim::globals(cx).last_find = Some(find.clone());
1889                self.motion(find, window, cx)
1890            }
1891            Some(Operator::Sneak { first_char }) => {
1892                if let Some(first_char) = first_char {
1893                    if let Some(second_char) = text.chars().next() {
1894                        let sneak = Motion::Sneak {
1895                            first_char,
1896                            second_char,
1897                            smartcase: VimSettings::get_global(cx).use_smartcase_find,
1898                        };
1899                        Vim::globals(cx).last_find = Some(sneak.clone());
1900                        self.motion(sneak, window, cx)
1901                    }
1902                } else {
1903                    let first_char = text.chars().next();
1904                    self.pop_operator(window, cx);
1905                    self.push_operator(Operator::Sneak { first_char }, window, cx);
1906                }
1907            }
1908            Some(Operator::SneakBackward { first_char }) => {
1909                if let Some(first_char) = first_char {
1910                    if let Some(second_char) = text.chars().next() {
1911                        let sneak = Motion::SneakBackward {
1912                            first_char,
1913                            second_char,
1914                            smartcase: VimSettings::get_global(cx).use_smartcase_find,
1915                        };
1916                        Vim::globals(cx).last_find = Some(sneak.clone());
1917                        self.motion(sneak, window, cx)
1918                    }
1919                } else {
1920                    let first_char = text.chars().next();
1921                    self.pop_operator(window, cx);
1922                    self.push_operator(Operator::SneakBackward { first_char }, window, cx);
1923                }
1924            }
1925            Some(Operator::Replace) => match self.mode {
1926                Mode::Normal => self.normal_replace(text, window, cx),
1927                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1928                    self.visual_replace(text, window, cx)
1929                }
1930                Mode::HelixNormal => self.helix_replace(&text, window, cx),
1931                _ => self.clear_operator(window, cx),
1932            },
1933            Some(Operator::Digraph { first_char }) => {
1934                if let Some(first_char) = first_char {
1935                    if let Some(second_char) = text.chars().next() {
1936                        self.insert_digraph(first_char, second_char, window, cx);
1937                    }
1938                } else {
1939                    let first_char = text.chars().next();
1940                    self.pop_operator(window, cx);
1941                    self.push_operator(Operator::Digraph { first_char }, window, cx);
1942                }
1943            }
1944            Some(Operator::Literal { prefix }) => {
1945                self.handle_literal_input(prefix.unwrap_or_default(), &text, window, cx)
1946            }
1947            Some(Operator::AddSurrounds { target }) => match self.mode {
1948                Mode::Normal => {
1949                    if let Some(target) = target {
1950                        self.add_surrounds(text, target, window, cx);
1951                        self.clear_operator(window, cx);
1952                    }
1953                }
1954                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1955                    self.add_surrounds(text, SurroundsType::Selection, window, cx);
1956                    self.clear_operator(window, cx);
1957                }
1958                _ => self.clear_operator(window, cx),
1959            },
1960            Some(Operator::ChangeSurrounds { target, opening }) => match self.mode {
1961                Mode::Normal => {
1962                    if let Some(target) = target {
1963                        self.change_surrounds(text, target, opening, window, cx);
1964                        self.clear_operator(window, cx);
1965                    }
1966                }
1967                _ => self.clear_operator(window, cx),
1968            },
1969            Some(Operator::DeleteSurrounds) => match self.mode {
1970                Mode::Normal => {
1971                    self.delete_surrounds(text, window, cx);
1972                    self.clear_operator(window, cx);
1973                }
1974                _ => self.clear_operator(window, cx),
1975            },
1976            Some(Operator::HelixSurroundAdd) => match self.mode {
1977                Mode::HelixNormal | Mode::HelixSelect => {
1978                    self.update_editor(cx, |_, editor, cx| {
1979                        editor.change_selections(Default::default(), window, cx, |s| {
1980                            s.move_with(&mut |map, selection| {
1981                                if selection.is_empty() {
1982                                    selection.end = movement::right(map, selection.start);
1983                                }
1984                            });
1985                        });
1986                    });
1987                    self.helix_surround_add(&text, window, cx);
1988                    self.switch_mode(Mode::HelixNormal, false, window, cx);
1989                    self.clear_operator(window, cx);
1990                }
1991                _ => self.clear_operator(window, cx),
1992            },
1993            Some(Operator::HelixSurroundReplace {
1994                replaced_char: Some(old),
1995            }) => match self.mode {
1996                Mode::HelixNormal | Mode::HelixSelect => {
1997                    if let Some(new_char) = text.chars().next() {
1998                        self.helix_surround_replace(old, new_char, window, cx);
1999                    }
2000                    self.clear_operator(window, cx);
2001                }
2002                _ => self.clear_operator(window, cx),
2003            },
2004            Some(Operator::HelixSurroundReplace {
2005                replaced_char: None,
2006            }) => match self.mode {
2007                Mode::HelixNormal | Mode::HelixSelect => {
2008                    if let Some(ch) = text.chars().next() {
2009                        self.pop_operator(window, cx);
2010                        self.push_operator(
2011                            Operator::HelixSurroundReplace {
2012                                replaced_char: Some(ch),
2013                            },
2014                            window,
2015                            cx,
2016                        );
2017                    }
2018                }
2019                _ => self.clear_operator(window, cx),
2020            },
2021            Some(Operator::HelixSurroundDelete) => match self.mode {
2022                Mode::HelixNormal | Mode::HelixSelect => {
2023                    if let Some(ch) = text.chars().next() {
2024                        self.helix_surround_delete(ch, window, cx);
2025                    }
2026                    self.clear_operator(window, cx);
2027                }
2028                _ => self.clear_operator(window, cx),
2029            },
2030            Some(Operator::Mark) => self.create_mark(text, window, cx),
2031            Some(Operator::RecordRegister) => {
2032                self.record_register(text.chars().next().unwrap(), window, cx)
2033            }
2034            Some(Operator::ReplayRegister) => {
2035                self.replay_register(text.chars().next().unwrap(), window, cx)
2036            }
2037            Some(Operator::Register) => match self.mode {
2038                Mode::Insert => {
2039                    self.update_editor(cx, |_, editor, cx| {
2040                        if let Some(register) = Vim::update_globals(cx, |globals, cx| {
2041                            globals.read_register(text.chars().next(), Some(editor), cx)
2042                        }) {
2043                            editor.do_paste(
2044                                &register.text.to_string(),
2045                                register.clipboard_selections,
2046                                false,
2047                                window,
2048                                cx,
2049                            )
2050                        }
2051                    });
2052                    self.clear_operator(window, cx);
2053                }
2054                _ => {
2055                    self.select_register(text, window, cx);
2056                }
2057            },
2058            Some(Operator::Jump { line }) => self.jump(text, line, true, window, cx),
2059            _ => {
2060                if self.mode == Mode::Replace {
2061                    self.multi_replace(text, window, cx)
2062                }
2063
2064                if self.mode == Mode::Normal {
2065                    self.update_editor(cx, |_, editor, cx| {
2066                        editor.accept_edit_prediction(
2067                            &editor::actions::AcceptEditPrediction {},
2068                            window,
2069                            cx,
2070                        );
2071                    });
2072                }
2073            }
2074        }
2075    }
2076
2077    fn sync_vim_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2078        let state = self.state_for_editor_settings(cx);
2079        self.update_editor(cx, |_, editor, cx| {
2080            Vim::sync_vim_settings_to_editor(&state, editor, window, cx);
2081        });
2082        cx.notify()
2083    }
2084
2085    fn state_for_editor_settings(&self, cx: &App) -> VimEditorSettingsState {
2086        VimEditorSettingsState {
2087            cursor_shape: self.cursor_shape(cx),
2088            clip_at_line_ends: self.clip_at_line_ends(),
2089            collapse_matches: !HelixModeSetting::get_global(cx).0,
2090            input_enabled: self.editor_input_enabled(),
2091            expects_character_input: self.expects_character_input(),
2092            autoindent: self.should_autoindent(),
2093            cursor_offset_on_selection: self.mode.is_visual() || self.mode.is_helix(),
2094            line_mode: matches!(self.mode, Mode::VisualLine),
2095            hide_edit_predictions: !matches!(self.mode, Mode::Insert | Mode::Replace),
2096        }
2097    }
2098
2099    fn sync_vim_settings_to_editor(
2100        state: &VimEditorSettingsState,
2101        editor: &mut Editor,
2102        window: &mut Window,
2103        cx: &mut Context<Editor>,
2104    ) {
2105        editor.set_cursor_shape(state.cursor_shape, cx);
2106        editor.set_clip_at_line_ends(state.clip_at_line_ends, cx);
2107        editor.set_collapse_matches(state.collapse_matches);
2108        editor.set_input_enabled(state.input_enabled);
2109        editor.set_expects_character_input(state.expects_character_input);
2110        editor.set_autoindent(state.autoindent);
2111        editor.set_cursor_offset_on_selection(state.cursor_offset_on_selection);
2112        editor.selections.set_line_mode(state.line_mode);
2113        editor.set_edit_predictions_hidden_for_vim_mode(state.hide_edit_predictions, window, cx);
2114    }
2115
2116    fn set_status_label(&mut self, label: impl Into<SharedString>, cx: &mut Context<Editor>) {
2117        self.status_label = Some(label.into());
2118        cx.notify();
2119    }
2120}
2121
2122struct VimEditorSettingsState {
2123    cursor_shape: CursorShape,
2124    clip_at_line_ends: bool,
2125    collapse_matches: bool,
2126    input_enabled: bool,
2127    expects_character_input: bool,
2128    autoindent: bool,
2129    cursor_offset_on_selection: bool,
2130    line_mode: bool,
2131    hide_edit_predictions: bool,
2132}
2133
2134#[derive(Clone, RegisterSetting)]
2135struct VimSettings {
2136    pub default_mode: Mode,
2137    pub toggle_relative_line_numbers: bool,
2138    pub use_system_clipboard: settings::UseSystemClipboard,
2139    pub use_smartcase_find: bool,
2140    pub gdefault: bool,
2141    pub custom_digraphs: HashMap<String, Arc<str>>,
2142    pub highlight_on_yank_duration: u64,
2143    pub cursor_shape: CursorShapeSettings,
2144}
2145
2146/// Cursor shape configuration for insert mode.
2147#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2148pub enum InsertModeCursorShape {
2149    /// Inherit cursor shape from the editor's base cursor_shape setting.
2150    /// This allows users to set their preferred editor cursor and have
2151    /// it automatically apply to vim insert mode.
2152    Inherit,
2153    /// Use an explicit cursor shape for insert mode.
2154    Explicit(CursorShape),
2155}
2156
2157/// The settings for cursor shape.
2158#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2159pub struct CursorShapeSettings {
2160    /// Cursor shape for the normal mode.
2161    ///
2162    /// Default: block
2163    pub normal: CursorShape,
2164    /// Cursor shape for the replace mode.
2165    ///
2166    /// Default: underline
2167    pub replace: CursorShape,
2168    /// Cursor shape for the visual mode.
2169    ///
2170    /// Default: block
2171    pub visual: CursorShape,
2172    /// Cursor shape for the insert mode.
2173    ///
2174    /// Default: Inherit (follows editor.cursor_shape)
2175    pub insert: InsertModeCursorShape,
2176}
2177
2178impl From<settings::VimInsertModeCursorShape> for InsertModeCursorShape {
2179    fn from(shape: settings::VimInsertModeCursorShape) -> Self {
2180        match shape {
2181            settings::VimInsertModeCursorShape::Inherit => InsertModeCursorShape::Inherit,
2182            settings::VimInsertModeCursorShape::Bar => {
2183                InsertModeCursorShape::Explicit(CursorShape::Bar)
2184            }
2185            settings::VimInsertModeCursorShape::Block => {
2186                InsertModeCursorShape::Explicit(CursorShape::Block)
2187            }
2188            settings::VimInsertModeCursorShape::Underline => {
2189                InsertModeCursorShape::Explicit(CursorShape::Underline)
2190            }
2191            settings::VimInsertModeCursorShape::Hollow => {
2192                InsertModeCursorShape::Explicit(CursorShape::Hollow)
2193            }
2194        }
2195    }
2196}
2197
2198impl From<settings::CursorShapeSettings> for CursorShapeSettings {
2199    fn from(settings: settings::CursorShapeSettings) -> Self {
2200        Self {
2201            normal: settings.normal.unwrap().into(),
2202            replace: settings.replace.unwrap().into(),
2203            visual: settings.visual.unwrap().into(),
2204            insert: settings.insert.unwrap().into(),
2205        }
2206    }
2207}
2208
2209impl From<settings::ModeContent> for Mode {
2210    fn from(mode: ModeContent) -> Self {
2211        match mode {
2212            ModeContent::Normal => Self::Normal,
2213            ModeContent::Insert => Self::Insert,
2214        }
2215    }
2216}
2217
2218impl Settings for VimSettings {
2219    fn from_settings(content: &settings::SettingsContent) -> Self {
2220        let vim = content.vim.clone().unwrap();
2221        Self {
2222            default_mode: vim.default_mode.unwrap().into(),
2223            toggle_relative_line_numbers: vim.toggle_relative_line_numbers.unwrap(),
2224            use_system_clipboard: vim.use_system_clipboard.unwrap(),
2225            use_smartcase_find: vim.use_smartcase_find.unwrap(),
2226            gdefault: vim.gdefault.unwrap(),
2227            custom_digraphs: vim.custom_digraphs.unwrap(),
2228            highlight_on_yank_duration: vim.highlight_on_yank_duration.unwrap(),
2229            cursor_shape: vim.cursor_shape.unwrap().into(),
2230        }
2231    }
2232}