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