vim.rs

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