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                            bracket_anchors: Vec::new(),
 774                        },
 775                        window,
 776                        cx,
 777                    )
 778                },
 779            );
 780
 781            Vim::action(editor, cx, |vim, action: &PushJump, window, cx| {
 782                vim.push_operator(Operator::Jump { line: action.line }, window, cx)
 783            });
 784
 785            Vim::action(editor, cx, |vim, action: &PushDigraph, window, cx| {
 786                vim.push_operator(
 787                    Operator::Digraph {
 788                        first_char: action.first_char,
 789                    },
 790                    window,
 791                    cx,
 792                )
 793            });
 794
 795            Vim::action(editor, cx, |vim, action: &PushLiteral, window, cx| {
 796                vim.push_operator(
 797                    Operator::Literal {
 798                        prefix: action.prefix.clone(),
 799                    },
 800                    window,
 801                    cx,
 802                )
 803            });
 804
 805            Vim::action(editor, cx, |vim, _: &PushChange, window, cx| {
 806                vim.push_operator(Operator::Change, window, cx)
 807            });
 808
 809            Vim::action(editor, cx, |vim, _: &PushDelete, window, cx| {
 810                vim.push_operator(Operator::Delete, window, cx)
 811            });
 812
 813            Vim::action(editor, cx, |vim, _: &PushYank, window, cx| {
 814                vim.push_operator(Operator::Yank, window, cx)
 815            });
 816
 817            Vim::action(editor, cx, |vim, _: &PushReplace, window, cx| {
 818                vim.push_operator(Operator::Replace, window, cx)
 819            });
 820
 821            Vim::action(editor, cx, |vim, _: &PushDeleteSurrounds, window, cx| {
 822                vim.push_operator(Operator::DeleteSurrounds, window, cx)
 823            });
 824
 825            Vim::action(editor, cx, |vim, _: &PushMark, window, cx| {
 826                vim.push_operator(Operator::Mark, window, cx)
 827            });
 828
 829            Vim::action(editor, cx, |vim, _: &PushIndent, window, cx| {
 830                vim.push_operator(Operator::Indent, window, cx)
 831            });
 832
 833            Vim::action(editor, cx, |vim, _: &PushOutdent, window, cx| {
 834                vim.push_operator(Operator::Outdent, window, cx)
 835            });
 836
 837            Vim::action(editor, cx, |vim, _: &PushAutoIndent, window, cx| {
 838                vim.push_operator(Operator::AutoIndent, window, cx)
 839            });
 840
 841            Vim::action(editor, cx, |vim, _: &PushRewrap, window, cx| {
 842                vim.push_operator(Operator::Rewrap, window, cx)
 843            });
 844
 845            Vim::action(editor, cx, |vim, _: &PushShellCommand, window, cx| {
 846                vim.push_operator(Operator::ShellCommand, window, cx)
 847            });
 848
 849            Vim::action(editor, cx, |vim, _: &PushLowercase, window, cx| {
 850                vim.push_operator(Operator::Lowercase, window, cx)
 851            });
 852
 853            Vim::action(editor, cx, |vim, _: &PushUppercase, window, cx| {
 854                vim.push_operator(Operator::Uppercase, window, cx)
 855            });
 856
 857            Vim::action(editor, cx, |vim, _: &PushOppositeCase, window, cx| {
 858                vim.push_operator(Operator::OppositeCase, window, cx)
 859            });
 860
 861            Vim::action(editor, cx, |vim, _: &PushRot13, window, cx| {
 862                vim.push_operator(Operator::Rot13, window, cx)
 863            });
 864
 865            Vim::action(editor, cx, |vim, _: &PushRot47, window, cx| {
 866                vim.push_operator(Operator::Rot47, window, cx)
 867            });
 868
 869            Vim::action(editor, cx, |vim, _: &PushRegister, window, cx| {
 870                vim.push_operator(Operator::Register, window, cx)
 871            });
 872
 873            Vim::action(editor, cx, |vim, _: &PushRecordRegister, window, cx| {
 874                vim.push_operator(Operator::RecordRegister, window, cx)
 875            });
 876
 877            Vim::action(editor, cx, |vim, _: &PushReplayRegister, window, cx| {
 878                vim.push_operator(Operator::ReplayRegister, window, cx)
 879            });
 880
 881            Vim::action(
 882                editor,
 883                cx,
 884                |vim, _: &PushReplaceWithRegister, window, cx| {
 885                    vim.push_operator(Operator::ReplaceWithRegister, window, cx)
 886                },
 887            );
 888
 889            Vim::action(editor, cx, |vim, _: &Exchange, window, cx| {
 890                if vim.mode.is_visual() {
 891                    vim.exchange_visual(window, cx)
 892                } else {
 893                    vim.push_operator(Operator::Exchange, window, cx)
 894                }
 895            });
 896
 897            Vim::action(editor, cx, |vim, _: &ClearExchange, window, cx| {
 898                vim.clear_exchange(window, cx)
 899            });
 900
 901            Vim::action(editor, cx, |vim, _: &PushToggleComments, window, cx| {
 902                vim.push_operator(Operator::ToggleComments, window, cx)
 903            });
 904
 905            Vim::action(
 906                editor,
 907                cx,
 908                |vim, _: &PushToggleBlockComments, window, cx| {
 909                    vim.push_operator(Operator::ToggleBlockComments, window, cx)
 910                },
 911            );
 912
 913            Vim::action(editor, cx, |vim, _: &ClearOperators, window, cx| {
 914                vim.clear_operator(window, cx)
 915            });
 916            Vim::action(editor, cx, |vim, n: &Number, window, cx| {
 917                vim.push_count_digit(n.0, window, cx);
 918            });
 919            Vim::action(editor, cx, |vim, _: &Tab, window, cx| {
 920                vim.input_ignored(" ".into(), window, cx)
 921            });
 922            Vim::action(
 923                editor,
 924                cx,
 925                |vim, action: &editor::actions::AcceptEditPrediction, window, cx| {
 926                    vim.update_editor(cx, |_, editor, cx| {
 927                        editor.accept_edit_prediction(action, window, cx);
 928                    });
 929                    // In non-insertion modes, predictions will be hidden and instead a jump will be
 930                    // displayed (and performed by `accept_edit_prediction`). This switches to
 931                    // insert mode so that the prediction is displayed after the jump.
 932                    match vim.mode {
 933                        Mode::Replace => {}
 934                        _ => vim.switch_mode(Mode::Insert, true, window, cx),
 935                    };
 936                },
 937            );
 938            Vim::action(editor, cx, |vim, _: &Enter, window, cx| {
 939                vim.input_ignored("\n".into(), window, cx)
 940            });
 941            Vim::action(editor, cx, |vim, _: &PushHelixMatch, window, cx| {
 942                vim.push_operator(Operator::HelixMatch, window, cx)
 943            });
 944            Vim::action(editor, cx, |vim, action: &PushHelixNext, window, cx| {
 945                vim.push_operator(
 946                    Operator::HelixNext {
 947                        around: action.around,
 948                    },
 949                    window,
 950                    cx,
 951                );
 952            });
 953            Vim::action(editor, cx, |vim, action: &PushHelixPrevious, window, cx| {
 954                vim.push_operator(
 955                    Operator::HelixPrevious {
 956                        around: action.around,
 957                    },
 958                    window,
 959                    cx,
 960                );
 961            });
 962
 963            Vim::action(
 964                editor,
 965                cx,
 966                |vim, _: &editor::actions::Paste, window, cx| match vim.mode {
 967                    Mode::Replace => vim.paste_replace(window, cx),
 968                    Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
 969                        vim.selected_register.replace('+');
 970                        vim.paste(&VimPaste::default(), window, cx);
 971                    }
 972                    _ => {
 973                        vim.update_editor(cx, |_, editor, cx| editor.paste(&Paste, window, cx));
 974                    }
 975                },
 976            );
 977
 978            normal::register(editor, cx);
 979            insert::register(editor, cx);
 980            helix::register(editor, cx);
 981            motion::register(editor, cx);
 982            command::register(editor, cx);
 983            replace::register(editor, cx);
 984            indent::register(editor, cx);
 985            rewrap::register(editor, cx);
 986            object::register(editor, cx);
 987            visual::register(editor, cx);
 988            change_list::register(editor, cx);
 989            digraph::register(editor, cx);
 990
 991            if editor.is_focused(window) {
 992                cx.defer_in(window, |vim, window, cx| {
 993                    vim.focused(false, window, cx);
 994                })
 995            }
 996        })
 997    }
 998
 999    fn deactivate(editor: &mut Editor, cx: &mut Context<Editor>) {
1000        editor.set_cursor_shape(
1001            EditorSettings::get_global(cx)
1002                .cursor_shape
1003                .unwrap_or_default(),
1004            cx,
1005        );
1006        editor.set_clip_at_line_ends(false, cx);
1007        editor.set_collapse_matches(false);
1008        editor.set_input_enabled(true);
1009        editor.set_expects_character_input(true);
1010        editor.set_autoindent(true);
1011        editor.selections.set_line_mode(false);
1012        editor.unregister_addon::<VimAddon>();
1013        editor.set_relative_line_number(None, cx);
1014        if let Some(vim) = Vim::globals(cx).focused_vim()
1015            && vim.entity_id() == cx.entity().entity_id()
1016        {
1017            Vim::globals(cx).focused_vim = None;
1018        }
1019    }
1020
1021    /// Register an action on the editor.
1022    pub fn action<A: Action>(
1023        editor: &mut Editor,
1024        cx: &mut Context<Vim>,
1025        f: impl Fn(&mut Vim, &A, &mut Window, &mut Context<Vim>) + 'static,
1026    ) {
1027        let subscription = editor.register_action(cx.listener(move |vim, action, window, cx| {
1028            if !Vim::globals(cx).dot_replaying {
1029                if vim.status_label.take().is_some() {
1030                    cx.notify();
1031                }
1032            }
1033            f(vim, action, window, cx);
1034        }));
1035        cx.on_release(|_, _| drop(subscription)).detach();
1036    }
1037
1038    pub fn editor(&self) -> Option<Entity<Editor>> {
1039        self.editor.upgrade()
1040    }
1041
1042    pub fn workspace(&self, window: &Window, cx: &App) -> Option<Entity<Workspace>> {
1043        Workspace::for_window(window, cx)
1044    }
1045
1046    pub fn pane(&self, window: &Window, cx: &Context<Self>) -> Option<Entity<Pane>> {
1047        let pane = self
1048            .workspace(window, cx)
1049            .map(|workspace| workspace.read(cx).focused_pane(window, cx))?;
1050        // `focused_pane` falls back to the center pane when a dock panel
1051        // without its own pane (e.g. the Agent panel) has focus. Guard
1052        // against that so vim search/match commands don't steal focus.
1053        if pane.read(cx).focus_handle(cx).contains_focused(window, cx) {
1054            Some(pane)
1055        } else {
1056            None
1057        }
1058    }
1059
1060    pub fn enabled(cx: &mut App) -> bool {
1061        VimModeSetting::get_global(cx).0 || HelixModeSetting::get_global(cx).0
1062    }
1063
1064    /// Called whenever an keystroke is typed so vim can observe all actions
1065    /// and keystrokes accordingly.
1066    fn observe_keystrokes(
1067        &mut self,
1068        keystroke_event: &KeystrokeEvent,
1069        window: &mut Window,
1070        cx: &mut Context<Self>,
1071    ) {
1072        if self.exit_temporary_mode {
1073            self.exit_temporary_mode = false;
1074            // Don't switch to insert mode if the action is temporary_normal.
1075            if let Some(action) = keystroke_event.action.as_ref()
1076                && action.as_any().downcast_ref::<TemporaryNormal>().is_some()
1077            {
1078                return;
1079            }
1080            self.switch_mode(Mode::Insert, false, window, cx)
1081        }
1082        if let Some(action) = keystroke_event.action.as_ref() {
1083            // Keystroke is handled by the vim system, so continue forward
1084            if action.name().starts_with("vim::") {
1085                self.update_editor(cx, |_, editor, cx| {
1086                    editor.hide_mouse_cursor(HideMouseCursorOrigin::MovementAction, cx)
1087                });
1088
1089                return;
1090            }
1091        } else if window.has_pending_keystrokes() || keystroke_event.keystroke.is_ime_in_progress()
1092        {
1093            return;
1094        }
1095
1096        if let Some(operator) = self.active_operator() {
1097            match operator {
1098                Operator::Literal { prefix } => {
1099                    self.handle_literal_keystroke(
1100                        keystroke_event,
1101                        prefix.unwrap_or_default(),
1102                        window,
1103                        cx,
1104                    );
1105                }
1106                _ if !operator.is_waiting(self.mode) => {
1107                    self.clear_operator(window, cx);
1108                    self.stop_recording_immediately(Box::new(ClearOperators), cx)
1109                }
1110                _ => {}
1111            }
1112        }
1113    }
1114
1115    fn handle_editor_event(
1116        &mut self,
1117        event: &EditorEvent,
1118        window: &mut Window,
1119        cx: &mut Context<Self>,
1120    ) {
1121        match event {
1122            EditorEvent::Focused => self.focused(true, window, cx),
1123            EditorEvent::Blurred => self.blurred(window, cx),
1124            EditorEvent::SelectionsChanged { local: true } => {
1125                self.local_selections_changed(window, cx);
1126            }
1127            EditorEvent::InputIgnored { text } => {
1128                self.input_ignored(text.clone(), window, cx);
1129                Vim::globals(cx).observe_insertion(text, None)
1130            }
1131            EditorEvent::InputHandled {
1132                text,
1133                utf16_range_to_replace: range_to_replace,
1134            } => Vim::globals(cx).observe_insertion(text, range_to_replace.clone()),
1135            EditorEvent::TransactionBegun { transaction_id } => {
1136                self.transaction_begun(*transaction_id, window, cx)
1137            }
1138            EditorEvent::TransactionUndone { transaction_id } => {
1139                self.transaction_undone(transaction_id, window, cx)
1140            }
1141            EditorEvent::Edited { .. } => self.push_to_change_list(window, cx),
1142            EditorEvent::FocusedIn => self.sync_vim_settings(window, cx),
1143            EditorEvent::CursorShapeChanged => self.cursor_shape_changed(window, cx),
1144            EditorEvent::PushedToNavHistory {
1145                anchor,
1146                is_deactivate,
1147            } => {
1148                self.update_editor(cx, |vim, editor, cx| {
1149                    let mark = if *is_deactivate {
1150                        "\"".to_string()
1151                    } else {
1152                        "'".to_string()
1153                    };
1154                    vim.set_mark(mark, vec![*anchor], editor.buffer(), window, cx);
1155                });
1156            }
1157            _ => {}
1158        }
1159    }
1160
1161    fn push_operator(&mut self, operator: Operator, window: &mut Window, cx: &mut Context<Self>) {
1162        if operator.starts_dot_recording() {
1163            self.start_recording(cx);
1164        }
1165        // Since these operations can only be entered with pre-operators,
1166        // we need to clear the previous operators when pushing,
1167        // so that the current stack is the most correct
1168        if matches!(
1169            operator,
1170            Operator::AddSurrounds { .. }
1171                | Operator::ChangeSurrounds { .. }
1172                | Operator::DeleteSurrounds
1173                | Operator::Exchange
1174        ) {
1175            self.operator_stack.clear();
1176        };
1177        self.operator_stack.push(operator);
1178        self.sync_vim_settings(window, cx);
1179    }
1180
1181    pub fn switch_mode(
1182        &mut self,
1183        mode: Mode,
1184        leave_selections: bool,
1185        window: &mut Window,
1186        cx: &mut Context<Self>,
1187    ) {
1188        if self.temp_mode && mode == Mode::Normal {
1189            self.temp_mode = false;
1190            self.switch_mode(Mode::Normal, leave_selections, window, cx);
1191            self.switch_mode(Mode::Insert, false, window, cx);
1192            return;
1193        } else if self.temp_mode
1194            && !matches!(mode, Mode::Visual | Mode::VisualLine | Mode::VisualBlock)
1195        {
1196            self.temp_mode = false;
1197        }
1198
1199        let last_mode = self.mode;
1200        let prior_mode = self.last_mode;
1201        let prior_tx = self.current_tx;
1202        self.last_mode = last_mode;
1203        self.mode = mode;
1204        self.operator_stack.clear();
1205        self.selected_register.take();
1206        self.cancel_running_command(window, cx);
1207        if mode == Mode::Normal || mode != last_mode {
1208            self.current_tx.take();
1209            self.current_anchor.take();
1210            self.update_editor(cx, |_, editor, _| {
1211                editor.clear_selection_drag_state();
1212            });
1213        }
1214        Vim::take_forced_motion(cx);
1215        if mode != Mode::Insert && mode != Mode::Replace {
1216            Vim::take_count(cx);
1217        }
1218
1219        // Sync editor settings like clip mode
1220        self.sync_vim_settings(window, cx);
1221
1222        if VimSettings::get_global(cx).toggle_relative_line_numbers
1223            && self.mode != self.last_mode
1224            && (self.mode == Mode::Insert || self.last_mode == Mode::Insert)
1225        {
1226            self.update_editor(cx, |vim, editor, cx| {
1227                let is_relative = vim.mode != Mode::Insert;
1228                editor.set_relative_line_number(Some(is_relative), cx)
1229            });
1230        }
1231        if HelixModeSetting::get_global(cx).0 {
1232            if self.mode == Mode::Normal {
1233                self.mode = Mode::HelixNormal
1234            } else if self.mode == Mode::Visual {
1235                self.mode = Mode::HelixSelect
1236            }
1237        }
1238
1239        if leave_selections {
1240            return;
1241        }
1242
1243        if !mode.is_visual() && last_mode.is_visual() && !last_mode.is_helix() {
1244            self.create_visual_marks(last_mode, window, cx);
1245        }
1246
1247        // Adjust selections
1248        self.update_editor(cx, |vim, editor, cx| {
1249            if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
1250            {
1251                vim.visual_block_motion(true, editor, window, cx, &mut |_, point, goal| {
1252                    Some((point, goal))
1253                })
1254            }
1255            if (last_mode == Mode::Insert || last_mode == Mode::Replace)
1256                && let Some(prior_tx) = prior_tx
1257            {
1258                editor.group_until_transaction(prior_tx, cx)
1259            }
1260
1261            editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1262                // we cheat with visual block mode and use multiple cursors.
1263                // the cost of this cheat is we need to convert back to a single
1264                // cursor whenever vim would.
1265                if last_mode == Mode::VisualBlock
1266                    && (mode != Mode::VisualBlock && mode != Mode::Insert)
1267                {
1268                    let tail = s.oldest_anchor().tail();
1269                    let head = s.newest_anchor().head();
1270                    s.select_anchor_ranges(vec![tail..head]);
1271                } else if last_mode == Mode::Insert
1272                    && prior_mode == Mode::VisualBlock
1273                    && mode != Mode::VisualBlock
1274                {
1275                    let pos = s.first_anchor().head();
1276                    s.select_anchor_ranges(vec![pos..pos])
1277                }
1278
1279                let mut should_extend_pending = false;
1280                if !last_mode.is_visual()
1281                    && mode.is_visual()
1282                    && let Some(pending) = s.pending_anchor()
1283                {
1284                    let snapshot = s.display_snapshot();
1285                    let is_empty = pending
1286                        .start
1287                        .cmp(&pending.end, &snapshot.buffer_snapshot())
1288                        .is_eq();
1289                    should_extend_pending = pending.reversed
1290                        && !is_empty
1291                        && vim.extended_pending_selection_id != Some(pending.id);
1292                };
1293
1294                if should_extend_pending {
1295                    let snapshot = s.display_snapshot();
1296                    s.change_with(&snapshot, |map| {
1297                        if let Some(pending) = map.pending_anchor_mut() {
1298                            let end = pending.end.to_point(&snapshot.buffer_snapshot());
1299                            let end = end.to_display_point(&snapshot);
1300                            let new_end = movement::right(&snapshot, end);
1301                            pending.end = snapshot
1302                                .buffer_snapshot()
1303                                .anchor_before(new_end.to_point(&snapshot));
1304                        }
1305                    });
1306                    vim.extended_pending_selection_id = s.pending_anchor().map(|p| p.id)
1307                }
1308
1309                s.move_with(&mut |map, selection| {
1310                    if last_mode.is_visual() && !last_mode.is_helix() && !mode.is_visual() {
1311                        let mut point = selection.head();
1312                        if !selection.reversed && !selection.is_empty() {
1313                            point = movement::left(map, selection.head());
1314                        } else if selection.is_empty() {
1315                            point = map.clip_point(point, Bias::Left);
1316                        }
1317                        selection.collapse_to(point, selection.goal)
1318                    } else if !last_mode.is_visual() && mode.is_visual() {
1319                        if selection.is_empty() {
1320                            selection.end = movement::right(map, selection.start);
1321                        }
1322                    }
1323                });
1324            })
1325        });
1326    }
1327
1328    pub fn take_count(cx: &mut App) -> Option<usize> {
1329        let global_state = cx.global_mut::<VimGlobals>();
1330        if global_state.dot_replaying {
1331            return global_state.recorded_count;
1332        }
1333
1334        let count = if global_state.post_count.is_none() && global_state.pre_count.is_none() {
1335            return None;
1336        } else {
1337            Some(
1338                global_state.post_count.take().unwrap_or(1)
1339                    * global_state.pre_count.take().unwrap_or(1),
1340            )
1341        };
1342
1343        if global_state.dot_recording {
1344            global_state.recording_count = count;
1345        }
1346        count
1347    }
1348
1349    pub fn take_forced_motion(cx: &mut App) -> bool {
1350        let global_state = cx.global_mut::<VimGlobals>();
1351        let forced_motion = global_state.forced_motion;
1352        global_state.forced_motion = false;
1353        forced_motion
1354    }
1355
1356    pub fn cursor_shape(&self, cx: &App) -> CursorShape {
1357        let cursor_shape = VimSettings::get_global(cx).cursor_shape;
1358        match self.mode {
1359            Mode::Normal => {
1360                if let Some(operator) = self.operator_stack.last() {
1361                    match operator {
1362                        // Navigation operators -> Block cursor
1363                        Operator::FindForward { .. }
1364                        | Operator::FindBackward { .. }
1365                        | Operator::Mark
1366                        | Operator::Jump { .. }
1367                        | Operator::Register
1368                        | Operator::RecordRegister
1369                        | Operator::ReplayRegister => CursorShape::Block,
1370
1371                        // All other operators -> Underline cursor
1372                        _ => CursorShape::Underline,
1373                    }
1374                } else {
1375                    cursor_shape.normal
1376                }
1377            }
1378            Mode::HelixNormal => cursor_shape.normal,
1379            Mode::Replace => cursor_shape.replace,
1380            Mode::Visual | Mode::VisualLine | Mode::VisualBlock | Mode::HelixSelect => {
1381                cursor_shape.visual
1382            }
1383            Mode::Insert => match cursor_shape.insert {
1384                InsertModeCursorShape::Explicit(shape) => shape,
1385                InsertModeCursorShape::Inherit => {
1386                    let editor_settings = EditorSettings::get_global(cx);
1387                    editor_settings.cursor_shape.unwrap_or_default()
1388                }
1389            },
1390        }
1391    }
1392
1393    fn expects_character_input(&self) -> bool {
1394        if let Some(operator) = self.operator_stack.last() {
1395            if operator.is_waiting(self.mode) {
1396                return true;
1397            }
1398        }
1399        self.editor_input_enabled()
1400    }
1401
1402    pub fn editor_input_enabled(&self) -> bool {
1403        match self.mode {
1404            Mode::Insert => {
1405                if let Some(operator) = self.operator_stack.last() {
1406                    !operator.is_waiting(self.mode)
1407                } else {
1408                    true
1409                }
1410            }
1411            Mode::Normal
1412            | Mode::HelixNormal
1413            | Mode::Replace
1414            | Mode::Visual
1415            | Mode::VisualLine
1416            | Mode::VisualBlock
1417            | Mode::HelixSelect => false,
1418        }
1419    }
1420
1421    pub fn should_autoindent(&self) -> bool {
1422        !(self.mode == Mode::Insert && self.last_mode == Mode::VisualBlock)
1423    }
1424
1425    pub fn clip_at_line_ends(&self) -> bool {
1426        match self.mode {
1427            Mode::Insert
1428            | Mode::Visual
1429            | Mode::VisualLine
1430            | Mode::VisualBlock
1431            | Mode::Replace
1432            | Mode::HelixNormal
1433            | Mode::HelixSelect => false,
1434            Mode::Normal => true,
1435        }
1436    }
1437
1438    pub fn extend_key_context(&self, context: &mut KeyContext, cx: &App) {
1439        let mut mode = match self.mode {
1440            Mode::Normal => "normal",
1441            Mode::Visual | Mode::VisualLine | Mode::VisualBlock => "visual",
1442            Mode::Insert => "insert",
1443            Mode::Replace => "replace",
1444            Mode::HelixNormal => "helix_normal",
1445            Mode::HelixSelect => "helix_select",
1446        }
1447        .to_string();
1448
1449        let mut operator_id = "none";
1450
1451        let active_operator = self.active_operator();
1452        if active_operator.is_none() && cx.global::<VimGlobals>().pre_count.is_some()
1453            || active_operator.is_some() && cx.global::<VimGlobals>().post_count.is_some()
1454        {
1455            context.add("VimCount");
1456        }
1457
1458        if let Some(active_operator) = active_operator {
1459            if active_operator.is_waiting(self.mode) {
1460                if matches!(active_operator, Operator::Literal { .. }) {
1461                    mode = "literal".to_string();
1462                } else {
1463                    mode = "waiting".to_string();
1464                }
1465            } else {
1466                operator_id = active_operator.id();
1467                mode = "operator".to_string();
1468            }
1469        }
1470
1471        if mode == "normal"
1472            || mode == "visual"
1473            || mode == "operator"
1474            || mode == "helix_normal"
1475            || mode == "helix_select"
1476        {
1477            context.add("VimControl");
1478        }
1479        context.set("vim_mode", mode);
1480        context.set("vim_operator", operator_id);
1481    }
1482
1483    fn focused(&mut self, preserve_selection: bool, window: &mut Window, cx: &mut Context<Self>) {
1484        // If editor gains focus while search bar is still open (not dismissed),
1485        // the user has explicitly navigated away - clear prior_selections so we
1486        // don't restore to the old position if they later dismiss the search.
1487        if !self.search.prior_selections.is_empty() {
1488            if let Some(pane) = self.pane(window, cx) {
1489                let search_still_open = pane
1490                    .read(cx)
1491                    .toolbar()
1492                    .read(cx)
1493                    .item_of_type::<BufferSearchBar>()
1494                    .is_some_and(|bar| !bar.read(cx).is_dismissed());
1495                if search_still_open {
1496                    self.search.prior_selections.clear();
1497                }
1498            }
1499        }
1500
1501        let Some(editor) = self.editor() else {
1502            return;
1503        };
1504        let newest_selection_empty = editor.update(cx, |editor, cx| {
1505            editor
1506                .selections
1507                .newest::<MultiBufferOffset>(&editor.display_snapshot(cx))
1508                .is_empty()
1509        });
1510        let editor = editor.read(cx);
1511        let editor_mode = editor.mode();
1512
1513        if editor_mode.is_full()
1514            && !newest_selection_empty
1515            && self.mode == Mode::Normal
1516            // When following someone, don't switch vim mode.
1517            && editor.leader_id().is_none()
1518        {
1519            if preserve_selection {
1520                self.switch_mode(Mode::Visual, true, window, cx);
1521            } else {
1522                self.update_editor(cx, |_, editor, cx| {
1523                    editor.set_clip_at_line_ends(false, cx);
1524                    editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1525                        s.move_with(&mut |_, selection| {
1526                            selection.collapse_to(selection.start, selection.goal)
1527                        })
1528                    });
1529                });
1530            }
1531        }
1532
1533        cx.emit(VimEvent::Focused);
1534        self.sync_vim_settings(window, cx);
1535
1536        if VimSettings::get_global(cx).toggle_relative_line_numbers {
1537            if let Some(old_vim) = Vim::globals(cx).focused_vim() {
1538                if old_vim.entity_id() != cx.entity().entity_id() {
1539                    old_vim.update(cx, |vim, cx| {
1540                        vim.update_editor(cx, |_, editor, cx| {
1541                            editor.set_relative_line_number(None, cx)
1542                        });
1543                    });
1544
1545                    self.update_editor(cx, |vim, editor, cx| {
1546                        let is_relative = vim.mode != Mode::Insert;
1547                        editor.set_relative_line_number(Some(is_relative), cx)
1548                    });
1549                }
1550            } else {
1551                self.update_editor(cx, |vim, editor, cx| {
1552                    let is_relative = vim.mode != Mode::Insert;
1553                    editor.set_relative_line_number(Some(is_relative), cx)
1554                });
1555            }
1556        }
1557        Vim::globals(cx).focused_vim = Some(cx.entity().downgrade());
1558    }
1559
1560    fn blurred(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1561        self.stop_recording_immediately(NormalBefore.boxed_clone(), cx);
1562        self.store_visual_marks(window, cx);
1563        self.clear_operator(window, cx);
1564        self.update_editor(cx, |vim, editor, cx| {
1565            if vim.cursor_shape(cx) == CursorShape::Block {
1566                editor.set_cursor_shape(CursorShape::Hollow, cx);
1567            }
1568        });
1569    }
1570
1571    fn cursor_shape_changed(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1572        self.update_editor(cx, |vim, editor, cx| {
1573            editor.set_cursor_shape(vim.cursor_shape(cx), cx);
1574        });
1575    }
1576
1577    fn update_editor<S>(
1578        &mut self,
1579        cx: &mut Context<Self>,
1580        update: impl FnOnce(&mut Self, &mut Editor, &mut Context<Editor>) -> S,
1581    ) -> Option<S> {
1582        let editor = self.editor.upgrade()?;
1583        Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
1584    }
1585
1586    fn editor_selections(&mut self, _: &mut Window, cx: &mut Context<Self>) -> Vec<Range<Anchor>> {
1587        self.update_editor(cx, |_, editor, _| {
1588            editor
1589                .selections
1590                .disjoint_anchors_arc()
1591                .iter()
1592                .map(|selection| selection.tail()..selection.head())
1593                .collect()
1594        })
1595        .unwrap_or_default()
1596    }
1597
1598    fn editor_cursor_word(
1599        &mut self,
1600        window: &mut Window,
1601        cx: &mut Context<Self>,
1602    ) -> Option<String> {
1603        self.update_editor(cx, |_, editor, cx| {
1604            let snapshot = &editor.snapshot(window, cx);
1605            let selection = editor
1606                .selections
1607                .newest::<MultiBufferOffset>(&snapshot.display_snapshot);
1608
1609            let snapshot = snapshot.buffer_snapshot();
1610            let (range, kind) =
1611                snapshot.surrounding_word(selection.start, Some(CharScopeContext::Completion));
1612            if kind == Some(CharKind::Word) {
1613                let text: String = snapshot.text_for_range(range).collect();
1614                if !text.trim().is_empty() {
1615                    return Some(text);
1616                }
1617            }
1618
1619            None
1620        })
1621        .unwrap_or_default()
1622    }
1623
1624    /// When doing an action that modifies the buffer, we start recording so that `.`
1625    /// will replay the action.
1626    pub fn start_recording(&mut self, cx: &mut Context<Self>) {
1627        Vim::update_globals(cx, |globals, cx| {
1628            if !globals.dot_replaying {
1629                globals.dot_recording = true;
1630                globals.recording_actions = Default::default();
1631                globals.recording_count = None;
1632                globals.recording_register_for_dot = self.selected_register;
1633
1634                let selections = self.editor().map(|editor| {
1635                    editor.update(cx, |editor, cx| {
1636                        let snapshot = editor.display_snapshot(cx);
1637
1638                        (
1639                            editor.selections.oldest::<Point>(&snapshot),
1640                            editor.selections.newest::<Point>(&snapshot),
1641                        )
1642                    })
1643                });
1644
1645                if let Some((oldest, newest)) = selections {
1646                    globals.recorded_selection = match self.mode {
1647                        Mode::Visual if newest.end.row == newest.start.row => {
1648                            RecordedSelection::SingleLine {
1649                                cols: newest.end.column - newest.start.column,
1650                            }
1651                        }
1652                        Mode::Visual => RecordedSelection::Visual {
1653                            rows: newest.end.row - newest.start.row,
1654                            cols: newest.end.column,
1655                        },
1656                        Mode::VisualLine => RecordedSelection::VisualLine {
1657                            rows: newest.end.row - newest.start.row,
1658                        },
1659                        Mode::VisualBlock => RecordedSelection::VisualBlock {
1660                            rows: newest.end.row.abs_diff(oldest.start.row),
1661                            cols: newest.end.column.abs_diff(oldest.start.column),
1662                        },
1663                        _ => RecordedSelection::None,
1664                    }
1665                } else {
1666                    globals.recorded_selection = RecordedSelection::None;
1667                }
1668            }
1669        })
1670    }
1671
1672    pub fn stop_replaying(&mut self, cx: &mut Context<Self>) {
1673        let globals = Vim::globals(cx);
1674        globals.dot_replaying = false;
1675        if let Some(replayer) = globals.replayer.take() {
1676            replayer.stop();
1677        }
1678    }
1679
1680    /// When finishing an action that modifies the buffer, stop recording.
1681    /// as you usually call this within a keystroke handler we also ensure that
1682    /// the current action is recorded.
1683    pub fn stop_recording(&mut self, cx: &mut Context<Self>) {
1684        let globals = Vim::globals(cx);
1685        if globals.dot_recording {
1686            globals.stop_recording_after_next_action = true;
1687        }
1688        self.exit_temporary_mode = self.temp_mode;
1689    }
1690
1691    /// Stops recording actions immediately rather than waiting until after the
1692    /// next action to stop recording.
1693    ///
1694    /// This doesn't include the current action.
1695    pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>, cx: &mut Context<Self>) {
1696        let globals = Vim::globals(cx);
1697        if globals.dot_recording {
1698            globals
1699                .recording_actions
1700                .push(ReplayableAction::Action(action.boxed_clone()));
1701            globals.recorded_actions = mem::take(&mut globals.recording_actions);
1702            globals.recorded_count = globals.recording_count.take();
1703            globals.dot_recording = false;
1704            globals.stop_recording_after_next_action = false;
1705        }
1706        self.exit_temporary_mode = self.temp_mode;
1707    }
1708
1709    /// Explicitly record one action (equivalents to start_recording and stop_recording)
1710    pub fn record_current_action(&mut self, cx: &mut Context<Self>) {
1711        self.start_recording(cx);
1712        self.stop_recording(cx);
1713    }
1714
1715    fn push_count_digit(&mut self, number: usize, window: &mut Window, cx: &mut Context<Self>) {
1716        if self.active_operator().is_some() {
1717            let post_count = Vim::globals(cx).post_count.unwrap_or(0);
1718
1719            Vim::globals(cx).post_count = Some(
1720                post_count
1721                    .checked_mul(10)
1722                    .and_then(|post_count| post_count.checked_add(number))
1723                    .filter(|post_count| *post_count < isize::MAX as usize)
1724                    .unwrap_or(post_count),
1725            )
1726        } else {
1727            let pre_count = Vim::globals(cx).pre_count.unwrap_or(0);
1728
1729            Vim::globals(cx).pre_count = Some(
1730                pre_count
1731                    .checked_mul(10)
1732                    .and_then(|pre_count| pre_count.checked_add(number))
1733                    .filter(|pre_count| *pre_count < isize::MAX as usize)
1734                    .unwrap_or(pre_count),
1735            )
1736        }
1737        // update the keymap so that 0 works
1738        self.sync_vim_settings(window, cx)
1739    }
1740
1741    fn select_register(&mut self, register: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
1742        if register.chars().count() == 1 {
1743            self.selected_register
1744                .replace(register.chars().next().unwrap());
1745        }
1746        self.operator_stack.clear();
1747        self.sync_vim_settings(window, cx);
1748    }
1749
1750    fn maybe_pop_operator(&mut self) -> Option<Operator> {
1751        self.operator_stack.pop()
1752    }
1753
1754    fn pop_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Operator {
1755        let popped_operator = self.operator_stack.pop()
1756            .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
1757        self.sync_vim_settings(window, cx);
1758        popped_operator
1759    }
1760
1761    fn clear_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1762        Vim::take_count(cx);
1763        Vim::take_forced_motion(cx);
1764        self.selected_register.take();
1765        self.operator_stack.clear();
1766        self.sync_vim_settings(window, cx);
1767    }
1768
1769    fn active_operator(&self) -> Option<Operator> {
1770        self.operator_stack.last().cloned()
1771    }
1772
1773    fn transaction_begun(
1774        &mut self,
1775        transaction_id: TransactionId,
1776        _window: &mut Window,
1777        _: &mut Context<Self>,
1778    ) {
1779        let mode = if (self.mode == Mode::Insert
1780            || self.mode == Mode::Replace
1781            || self.mode == Mode::Normal)
1782            && self.current_tx.is_none()
1783        {
1784            self.current_tx = Some(transaction_id);
1785            self.last_mode
1786        } else {
1787            self.mode
1788        };
1789        if mode == Mode::VisualLine || mode == Mode::VisualBlock {
1790            self.undo_modes.insert(transaction_id, mode);
1791        }
1792    }
1793
1794    fn transaction_undone(
1795        &mut self,
1796        transaction_id: &TransactionId,
1797        window: &mut Window,
1798        cx: &mut Context<Self>,
1799    ) {
1800        match self.mode {
1801            Mode::VisualLine | Mode::VisualBlock | Mode::Visual | Mode::HelixSelect => {
1802                self.update_editor(cx, |vim, editor, cx| {
1803                    let original_mode = vim.undo_modes.get(transaction_id);
1804                    editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1805                        match original_mode {
1806                            Some(Mode::VisualLine) => {
1807                                s.move_with(&mut |map, selection| {
1808                                    selection.collapse_to(
1809                                        map.prev_line_boundary(selection.start.to_point(map)).1,
1810                                        SelectionGoal::None,
1811                                    )
1812                                });
1813                            }
1814                            Some(Mode::VisualBlock) => {
1815                                let mut first = s.first_anchor();
1816                                first.collapse_to(first.start, first.goal);
1817                                s.select_anchors(vec![first]);
1818                            }
1819                            _ => {
1820                                s.move_with(&mut |map, selection| {
1821                                    selection.collapse_to(
1822                                        map.clip_at_line_end(selection.start),
1823                                        selection.goal,
1824                                    );
1825                                });
1826                            }
1827                        }
1828                    });
1829                });
1830                self.switch_mode(Mode::Normal, true, window, cx)
1831            }
1832            Mode::Normal => {
1833                self.update_editor(cx, |_, editor, cx| {
1834                    editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1835                        s.move_with(&mut |map, selection| {
1836                            selection
1837                                .collapse_to(map.clip_at_line_end(selection.end), selection.goal)
1838                        })
1839                    })
1840                });
1841            }
1842            Mode::Insert | Mode::Replace | Mode::HelixNormal => {}
1843        }
1844    }
1845
1846    fn local_selections_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1847        let Some(editor) = self.editor() else { return };
1848
1849        if editor.read(cx).leader_id().is_some() {
1850            return;
1851        }
1852
1853        let newest = editor.read(cx).selections.newest_anchor().clone();
1854        let is_multicursor = editor.read(cx).selections.count() > 1;
1855        if self.mode == Mode::Insert && self.current_tx.is_some() {
1856            if let Some(current_anchor) = &self.current_anchor {
1857                if current_anchor != &newest
1858                    && let Some(tx_id) = self.current_tx.take()
1859                {
1860                    self.update_editor(cx, |_, editor, cx| {
1861                        editor.group_until_transaction(tx_id, cx)
1862                    });
1863                }
1864            } else {
1865                self.current_anchor = Some(newest);
1866            }
1867        } else if self.mode == Mode::Normal && newest.start != newest.end {
1868            if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
1869                self.switch_mode(Mode::VisualBlock, false, window, cx);
1870            } else {
1871                self.switch_mode(Mode::Visual, false, window, cx)
1872            }
1873        } else if newest.start == newest.end
1874            && !is_multicursor
1875            && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&self.mode)
1876        {
1877            self.switch_mode(Mode::Normal, false, window, cx);
1878        }
1879    }
1880
1881    fn input_ignored(&mut self, text: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
1882        if text.is_empty() {
1883            return;
1884        }
1885
1886        match self.active_operator() {
1887            Some(Operator::FindForward { before, multiline }) => {
1888                let find = Motion::FindForward {
1889                    before,
1890                    char: text.chars().next().unwrap(),
1891                    mode: if multiline {
1892                        FindRange::MultiLine
1893                    } else {
1894                        FindRange::SingleLine
1895                    },
1896                    smartcase: VimSettings::get_global(cx).use_smartcase_find,
1897                };
1898                Vim::globals(cx).last_find = Some(find.clone());
1899                self.motion(find, window, cx)
1900            }
1901            Some(Operator::FindBackward { after, multiline }) => {
1902                let find = Motion::FindBackward {
1903                    after,
1904                    char: text.chars().next().unwrap(),
1905                    mode: if multiline {
1906                        FindRange::MultiLine
1907                    } else {
1908                        FindRange::SingleLine
1909                    },
1910                    smartcase: VimSettings::get_global(cx).use_smartcase_find,
1911                };
1912                Vim::globals(cx).last_find = Some(find.clone());
1913                self.motion(find, window, cx)
1914            }
1915            Some(Operator::Sneak { first_char }) => {
1916                if let Some(first_char) = first_char {
1917                    if let Some(second_char) = text.chars().next() {
1918                        let sneak = Motion::Sneak {
1919                            first_char,
1920                            second_char,
1921                            smartcase: VimSettings::get_global(cx).use_smartcase_find,
1922                        };
1923                        Vim::globals(cx).last_find = Some(sneak.clone());
1924                        self.motion(sneak, window, cx)
1925                    }
1926                } else {
1927                    let first_char = text.chars().next();
1928                    self.pop_operator(window, cx);
1929                    self.push_operator(Operator::Sneak { first_char }, window, cx);
1930                }
1931            }
1932            Some(Operator::SneakBackward { first_char }) => {
1933                if let Some(first_char) = first_char {
1934                    if let Some(second_char) = text.chars().next() {
1935                        let sneak = Motion::SneakBackward {
1936                            first_char,
1937                            second_char,
1938                            smartcase: VimSettings::get_global(cx).use_smartcase_find,
1939                        };
1940                        Vim::globals(cx).last_find = Some(sneak.clone());
1941                        self.motion(sneak, window, cx)
1942                    }
1943                } else {
1944                    let first_char = text.chars().next();
1945                    self.pop_operator(window, cx);
1946                    self.push_operator(Operator::SneakBackward { first_char }, window, cx);
1947                }
1948            }
1949            Some(Operator::Replace) => match self.mode {
1950                Mode::Normal => self.normal_replace(text, window, cx),
1951                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1952                    self.visual_replace(text, window, cx)
1953                }
1954                Mode::HelixNormal => self.helix_replace(&text, window, cx),
1955                _ => self.clear_operator(window, cx),
1956            },
1957            Some(Operator::Digraph { first_char }) => {
1958                if let Some(first_char) = first_char {
1959                    if let Some(second_char) = text.chars().next() {
1960                        self.insert_digraph(first_char, second_char, window, cx);
1961                    }
1962                } else {
1963                    let first_char = text.chars().next();
1964                    self.pop_operator(window, cx);
1965                    self.push_operator(Operator::Digraph { first_char }, window, cx);
1966                }
1967            }
1968            Some(Operator::Literal { prefix }) => {
1969                self.handle_literal_input(prefix.unwrap_or_default(), &text, window, cx)
1970            }
1971            Some(Operator::AddSurrounds { target }) => match self.mode {
1972                Mode::Normal => {
1973                    if let Some(target) = target {
1974                        self.add_surrounds(text, target, window, cx);
1975                        self.clear_operator(window, cx);
1976                    }
1977                }
1978                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1979                    self.add_surrounds(text, SurroundsType::Selection, window, cx);
1980                    self.clear_operator(window, cx);
1981                }
1982                _ => self.clear_operator(window, cx),
1983            },
1984            Some(Operator::ChangeSurrounds {
1985                target,
1986                opening,
1987                bracket_anchors,
1988            }) => match self.mode {
1989                Mode::Normal => {
1990                    if let Some(target) = target {
1991                        self.change_surrounds(text, target, opening, bracket_anchors, window, cx);
1992                        self.clear_operator(window, cx);
1993                    }
1994                }
1995                _ => self.clear_operator(window, cx),
1996            },
1997            Some(Operator::DeleteSurrounds) => match self.mode {
1998                Mode::Normal => {
1999                    self.delete_surrounds(text, window, cx);
2000                    self.clear_operator(window, cx);
2001                }
2002                _ => self.clear_operator(window, cx),
2003            },
2004            Some(Operator::HelixSurroundAdd) => match self.mode {
2005                Mode::HelixNormal | Mode::HelixSelect => {
2006                    self.update_editor(cx, |_, editor, cx| {
2007                        editor.change_selections(Default::default(), window, cx, |s| {
2008                            s.move_with(&mut |map, selection| {
2009                                if selection.is_empty() {
2010                                    selection.end = movement::right(map, selection.start);
2011                                }
2012                            });
2013                        });
2014                    });
2015                    self.helix_surround_add(&text, window, cx);
2016                    self.switch_mode(Mode::HelixNormal, false, window, cx);
2017                    self.clear_operator(window, cx);
2018                }
2019                _ => self.clear_operator(window, cx),
2020            },
2021            Some(Operator::HelixSurroundReplace {
2022                replaced_char: Some(old),
2023            }) => match self.mode {
2024                Mode::HelixNormal | Mode::HelixSelect => {
2025                    if let Some(new_char) = text.chars().next() {
2026                        self.helix_surround_replace(old, new_char, window, cx);
2027                    }
2028                    self.clear_operator(window, cx);
2029                }
2030                _ => self.clear_operator(window, cx),
2031            },
2032            Some(Operator::HelixSurroundReplace {
2033                replaced_char: None,
2034            }) => match self.mode {
2035                Mode::HelixNormal | Mode::HelixSelect => {
2036                    if let Some(ch) = text.chars().next() {
2037                        self.pop_operator(window, cx);
2038                        self.push_operator(
2039                            Operator::HelixSurroundReplace {
2040                                replaced_char: Some(ch),
2041                            },
2042                            window,
2043                            cx,
2044                        );
2045                    }
2046                }
2047                _ => self.clear_operator(window, cx),
2048            },
2049            Some(Operator::HelixSurroundDelete) => match self.mode {
2050                Mode::HelixNormal | Mode::HelixSelect => {
2051                    if let Some(ch) = text.chars().next() {
2052                        self.helix_surround_delete(ch, window, cx);
2053                    }
2054                    self.clear_operator(window, cx);
2055                }
2056                _ => self.clear_operator(window, cx),
2057            },
2058            Some(Operator::Mark) => self.create_mark(text, window, cx),
2059            Some(Operator::RecordRegister) => {
2060                self.record_register(text.chars().next().unwrap(), window, cx)
2061            }
2062            Some(Operator::ReplayRegister) => {
2063                self.replay_register(text.chars().next().unwrap(), window, cx)
2064            }
2065            Some(Operator::Register) => match self.mode {
2066                Mode::Insert => {
2067                    self.update_editor(cx, |_, editor, cx| {
2068                        if let Some(register) = Vim::update_globals(cx, |globals, cx| {
2069                            globals.read_register(text.chars().next(), Some(editor), cx)
2070                        }) {
2071                            editor.do_paste(
2072                                &register.text.to_string(),
2073                                register.clipboard_selections,
2074                                false,
2075                                window,
2076                                cx,
2077                            )
2078                        }
2079                    });
2080                    self.clear_operator(window, cx);
2081                }
2082                _ => {
2083                    self.select_register(text, window, cx);
2084                }
2085            },
2086            Some(Operator::Jump { line }) => self.jump(text, line, true, window, cx),
2087            _ => {
2088                if self.mode == Mode::Replace {
2089                    self.multi_replace(text, window, cx)
2090                }
2091
2092                if self.mode == Mode::Normal {
2093                    self.update_editor(cx, |_, editor, cx| {
2094                        editor.accept_edit_prediction(
2095                            &editor::actions::AcceptEditPrediction {},
2096                            window,
2097                            cx,
2098                        );
2099                    });
2100                }
2101            }
2102        }
2103    }
2104
2105    fn sync_vim_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2106        let state = self.state_for_editor_settings(cx);
2107        self.update_editor(cx, |_, editor, cx| {
2108            Vim::sync_vim_settings_to_editor(&state, editor, window, cx);
2109        });
2110        cx.notify()
2111    }
2112
2113    fn state_for_editor_settings(&self, cx: &App) -> VimEditorSettingsState {
2114        VimEditorSettingsState {
2115            cursor_shape: self.cursor_shape(cx),
2116            clip_at_line_ends: self.clip_at_line_ends(),
2117            collapse_matches: !HelixModeSetting::get_global(cx).0 && !self.search.cmd_f_search,
2118            input_enabled: self.editor_input_enabled(),
2119            expects_character_input: self.expects_character_input(),
2120            autoindent: self.should_autoindent(),
2121            cursor_offset_on_selection: self.mode.is_visual() || self.mode.is_helix(),
2122            line_mode: matches!(self.mode, Mode::VisualLine),
2123            hide_edit_predictions: !matches!(self.mode, Mode::Insert | Mode::Replace),
2124        }
2125    }
2126
2127    fn sync_vim_settings_to_editor(
2128        state: &VimEditorSettingsState,
2129        editor: &mut Editor,
2130        window: &mut Window,
2131        cx: &mut Context<Editor>,
2132    ) {
2133        editor.set_cursor_shape(state.cursor_shape, cx);
2134        editor.set_clip_at_line_ends(state.clip_at_line_ends, cx);
2135        editor.set_collapse_matches(state.collapse_matches);
2136        editor.set_input_enabled(state.input_enabled);
2137        editor.set_expects_character_input(state.expects_character_input);
2138        editor.set_autoindent(state.autoindent);
2139        editor.set_cursor_offset_on_selection(state.cursor_offset_on_selection);
2140        editor.selections.set_line_mode(state.line_mode);
2141        editor.set_edit_predictions_hidden_for_vim_mode(state.hide_edit_predictions, window, cx);
2142    }
2143
2144    fn set_status_label(&mut self, label: impl Into<SharedString>, cx: &mut Context<Editor>) {
2145        self.status_label = Some(label.into());
2146        cx.notify();
2147    }
2148}
2149
2150struct VimEditorSettingsState {
2151    cursor_shape: CursorShape,
2152    clip_at_line_ends: bool,
2153    collapse_matches: bool,
2154    input_enabled: bool,
2155    expects_character_input: bool,
2156    autoindent: bool,
2157    cursor_offset_on_selection: bool,
2158    line_mode: bool,
2159    hide_edit_predictions: bool,
2160}
2161
2162#[derive(Clone, RegisterSetting)]
2163struct VimSettings {
2164    pub default_mode: Mode,
2165    pub toggle_relative_line_numbers: bool,
2166    pub use_system_clipboard: settings::UseSystemClipboard,
2167    pub use_smartcase_find: bool,
2168    pub use_regex_search: bool,
2169    pub gdefault: bool,
2170    pub custom_digraphs: HashMap<String, Arc<str>>,
2171    pub highlight_on_yank_duration: u64,
2172    pub cursor_shape: CursorShapeSettings,
2173}
2174
2175/// Cursor shape configuration for insert mode.
2176#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2177pub enum InsertModeCursorShape {
2178    /// Inherit cursor shape from the editor's base cursor_shape setting.
2179    /// This allows users to set their preferred editor cursor and have
2180    /// it automatically apply to vim insert mode.
2181    Inherit,
2182    /// Use an explicit cursor shape for insert mode.
2183    Explicit(CursorShape),
2184}
2185
2186/// The settings for cursor shape.
2187#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2188pub struct CursorShapeSettings {
2189    /// Cursor shape for the normal mode.
2190    ///
2191    /// Default: block
2192    pub normal: CursorShape,
2193    /// Cursor shape for the replace mode.
2194    ///
2195    /// Default: underline
2196    pub replace: CursorShape,
2197    /// Cursor shape for the visual mode.
2198    ///
2199    /// Default: block
2200    pub visual: CursorShape,
2201    /// Cursor shape for the insert mode.
2202    ///
2203    /// Default: Inherit (follows editor.cursor_shape)
2204    pub insert: InsertModeCursorShape,
2205}
2206
2207impl From<settings::VimInsertModeCursorShape> for InsertModeCursorShape {
2208    fn from(shape: settings::VimInsertModeCursorShape) -> Self {
2209        match shape {
2210            settings::VimInsertModeCursorShape::Inherit => InsertModeCursorShape::Inherit,
2211            settings::VimInsertModeCursorShape::Bar => {
2212                InsertModeCursorShape::Explicit(CursorShape::Bar)
2213            }
2214            settings::VimInsertModeCursorShape::Block => {
2215                InsertModeCursorShape::Explicit(CursorShape::Block)
2216            }
2217            settings::VimInsertModeCursorShape::Underline => {
2218                InsertModeCursorShape::Explicit(CursorShape::Underline)
2219            }
2220            settings::VimInsertModeCursorShape::Hollow => {
2221                InsertModeCursorShape::Explicit(CursorShape::Hollow)
2222            }
2223        }
2224    }
2225}
2226
2227impl From<settings::CursorShapeSettings> for CursorShapeSettings {
2228    fn from(settings: settings::CursorShapeSettings) -> Self {
2229        Self {
2230            normal: settings.normal.unwrap().into(),
2231            replace: settings.replace.unwrap().into(),
2232            visual: settings.visual.unwrap().into(),
2233            insert: settings.insert.unwrap().into(),
2234        }
2235    }
2236}
2237
2238impl From<settings::ModeContent> for Mode {
2239    fn from(mode: ModeContent) -> Self {
2240        match mode {
2241            ModeContent::Normal => Self::Normal,
2242            ModeContent::Insert => Self::Insert,
2243        }
2244    }
2245}
2246
2247impl Settings for VimSettings {
2248    fn from_settings(content: &settings::SettingsContent) -> Self {
2249        let vim = content.vim.clone().unwrap();
2250        Self {
2251            default_mode: vim.default_mode.unwrap().into(),
2252            toggle_relative_line_numbers: vim.toggle_relative_line_numbers.unwrap(),
2253            use_system_clipboard: vim.use_system_clipboard.unwrap(),
2254            use_smartcase_find: vim.use_smartcase_find.unwrap(),
2255            use_regex_search: vim.use_regex_search.unwrap(),
2256            gdefault: vim.gdefault.unwrap(),
2257            custom_digraphs: vim.custom_digraphs.unwrap(),
2258            highlight_on_yank_duration: vim.highlight_on_yank_duration.unwrap(),
2259            cursor_shape: vim.cursor_shape.unwrap().into(),
2260        }
2261    }
2262}