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