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 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.selections.newest::<usize>(cx).is_empty()
1363        });
1364        let editor = editor.read(cx);
1365        let editor_mode = editor.mode();
1366
1367        if editor_mode.is_full()
1368            && !newest_selection_empty
1369            && self.mode == Mode::Normal
1370            // When following someone, don't switch vim mode.
1371            && editor.leader_id().is_none()
1372        {
1373            if preserve_selection {
1374                self.switch_mode(Mode::Visual, true, window, cx);
1375            } else {
1376                self.update_editor(cx, |_, editor, cx| {
1377                    editor.set_clip_at_line_ends(false, cx);
1378                    editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1379                        s.move_with(|_, selection| {
1380                            selection.collapse_to(selection.start, selection.goal)
1381                        })
1382                    });
1383                });
1384            }
1385        }
1386
1387        cx.emit(VimEvent::Focused);
1388        self.sync_vim_settings(window, cx);
1389
1390        if VimSettings::get_global(cx).toggle_relative_line_numbers {
1391            if let Some(old_vim) = Vim::globals(cx).focused_vim() {
1392                if old_vim.entity_id() != cx.entity().entity_id() {
1393                    old_vim.update(cx, |vim, cx| {
1394                        vim.update_editor(cx, |_, editor, cx| {
1395                            editor.set_relative_line_number(None, cx)
1396                        });
1397                    });
1398
1399                    self.update_editor(cx, |vim, editor, cx| {
1400                        let is_relative = vim.mode != Mode::Insert;
1401                        editor.set_relative_line_number(Some(is_relative), cx)
1402                    });
1403                }
1404            } else {
1405                self.update_editor(cx, |vim, editor, cx| {
1406                    let is_relative = vim.mode != Mode::Insert;
1407                    editor.set_relative_line_number(Some(is_relative), cx)
1408                });
1409            }
1410        }
1411        Vim::globals(cx).focused_vim = Some(cx.entity().downgrade());
1412    }
1413
1414    fn blurred(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1415        self.stop_recording_immediately(NormalBefore.boxed_clone(), cx);
1416        self.store_visual_marks(window, cx);
1417        self.clear_operator(window, cx);
1418        self.update_editor(cx, |vim, editor, cx| {
1419            if vim.cursor_shape(cx) == CursorShape::Block {
1420                editor.set_cursor_shape(CursorShape::Hollow, cx);
1421            }
1422        });
1423    }
1424
1425    fn cursor_shape_changed(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1426        self.update_editor(cx, |vim, editor, cx| {
1427            editor.set_cursor_shape(vim.cursor_shape(cx), cx);
1428        });
1429    }
1430
1431    fn update_editor<S>(
1432        &mut self,
1433        cx: &mut Context<Self>,
1434        update: impl FnOnce(&mut Self, &mut Editor, &mut Context<Editor>) -> S,
1435    ) -> Option<S> {
1436        let editor = self.editor.upgrade()?;
1437        Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
1438    }
1439
1440    fn editor_selections(&mut self, _: &mut Window, cx: &mut Context<Self>) -> Vec<Range<Anchor>> {
1441        self.update_editor(cx, |_, editor, _| {
1442            editor
1443                .selections
1444                .disjoint_anchors_arc()
1445                .iter()
1446                .map(|selection| selection.tail()..selection.head())
1447                .collect()
1448        })
1449        .unwrap_or_default()
1450    }
1451
1452    fn editor_cursor_word(
1453        &mut self,
1454        window: &mut Window,
1455        cx: &mut Context<Self>,
1456    ) -> Option<String> {
1457        self.update_editor(cx, |_, editor, cx| {
1458            let selection = editor.selections.newest::<usize>(cx);
1459
1460            let snapshot = editor.snapshot(window, cx);
1461            let snapshot = snapshot.buffer_snapshot();
1462            let (range, kind) =
1463                snapshot.surrounding_word(selection.start, Some(CharScopeContext::Completion));
1464            if kind == Some(CharKind::Word) {
1465                let text: String = snapshot.text_for_range(range).collect();
1466                if !text.trim().is_empty() {
1467                    return Some(text);
1468                }
1469            }
1470
1471            None
1472        })
1473        .unwrap_or_default()
1474    }
1475
1476    /// When doing an action that modifies the buffer, we start recording so that `.`
1477    /// will replay the action.
1478    pub fn start_recording(&mut self, cx: &mut Context<Self>) {
1479        Vim::update_globals(cx, |globals, cx| {
1480            if !globals.dot_replaying {
1481                globals.dot_recording = true;
1482                globals.recording_actions = Default::default();
1483                globals.recorded_count = None;
1484
1485                let selections = self.editor().map(|editor| {
1486                    editor.update(cx, |editor, cx| {
1487                        (
1488                            editor.selections.oldest::<Point>(cx),
1489                            editor.selections.newest::<Point>(cx),
1490                        )
1491                    })
1492                });
1493
1494                if let Some((oldest, newest)) = selections {
1495                    globals.recorded_selection = match self.mode {
1496                        Mode::Visual if newest.end.row == newest.start.row => {
1497                            RecordedSelection::SingleLine {
1498                                cols: newest.end.column - newest.start.column,
1499                            }
1500                        }
1501                        Mode::Visual => RecordedSelection::Visual {
1502                            rows: newest.end.row - newest.start.row,
1503                            cols: newest.end.column,
1504                        },
1505                        Mode::VisualLine => RecordedSelection::VisualLine {
1506                            rows: newest.end.row - newest.start.row,
1507                        },
1508                        Mode::VisualBlock => RecordedSelection::VisualBlock {
1509                            rows: newest.end.row.abs_diff(oldest.start.row),
1510                            cols: newest.end.column.abs_diff(oldest.start.column),
1511                        },
1512                        _ => RecordedSelection::None,
1513                    }
1514                } else {
1515                    globals.recorded_selection = RecordedSelection::None;
1516                }
1517            }
1518        })
1519    }
1520
1521    pub fn stop_replaying(&mut self, cx: &mut Context<Self>) {
1522        let globals = Vim::globals(cx);
1523        globals.dot_replaying = false;
1524        if let Some(replayer) = globals.replayer.take() {
1525            replayer.stop();
1526        }
1527    }
1528
1529    /// When finishing an action that modifies the buffer, stop recording.
1530    /// as you usually call this within a keystroke handler we also ensure that
1531    /// the current action is recorded.
1532    pub fn stop_recording(&mut self, cx: &mut Context<Self>) {
1533        let globals = Vim::globals(cx);
1534        if globals.dot_recording {
1535            globals.stop_recording_after_next_action = true;
1536        }
1537        self.exit_temporary_mode = self.temp_mode;
1538    }
1539
1540    /// Stops recording actions immediately rather than waiting until after the
1541    /// next action to stop recording.
1542    ///
1543    /// This doesn't include the current action.
1544    pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>, cx: &mut Context<Self>) {
1545        let globals = Vim::globals(cx);
1546        if globals.dot_recording {
1547            globals
1548                .recording_actions
1549                .push(ReplayableAction::Action(action.boxed_clone()));
1550            globals.recorded_actions = mem::take(&mut globals.recording_actions);
1551            globals.dot_recording = false;
1552            globals.stop_recording_after_next_action = false;
1553        }
1554        self.exit_temporary_mode = self.temp_mode;
1555    }
1556
1557    /// Explicitly record one action (equivalents to start_recording and stop_recording)
1558    pub fn record_current_action(&mut self, cx: &mut Context<Self>) {
1559        self.start_recording(cx);
1560        self.stop_recording(cx);
1561    }
1562
1563    fn push_count_digit(&mut self, number: usize, window: &mut Window, cx: &mut Context<Self>) {
1564        if self.active_operator().is_some() {
1565            let post_count = Vim::globals(cx).post_count.unwrap_or(0);
1566
1567            Vim::globals(cx).post_count = Some(
1568                post_count
1569                    .checked_mul(10)
1570                    .and_then(|post_count| post_count.checked_add(number))
1571                    .filter(|post_count| *post_count < isize::MAX as usize)
1572                    .unwrap_or(post_count),
1573            )
1574        } else {
1575            let pre_count = Vim::globals(cx).pre_count.unwrap_or(0);
1576
1577            Vim::globals(cx).pre_count = Some(
1578                pre_count
1579                    .checked_mul(10)
1580                    .and_then(|pre_count| pre_count.checked_add(number))
1581                    .filter(|pre_count| *pre_count < isize::MAX as usize)
1582                    .unwrap_or(pre_count),
1583            )
1584        }
1585        // update the keymap so that 0 works
1586        self.sync_vim_settings(window, cx)
1587    }
1588
1589    fn select_register(&mut self, register: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
1590        if register.chars().count() == 1 {
1591            self.selected_register
1592                .replace(register.chars().next().unwrap());
1593        }
1594        self.operator_stack.clear();
1595        self.sync_vim_settings(window, cx);
1596    }
1597
1598    fn maybe_pop_operator(&mut self) -> Option<Operator> {
1599        self.operator_stack.pop()
1600    }
1601
1602    fn pop_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Operator {
1603        let popped_operator = self.operator_stack.pop()
1604            .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
1605        self.sync_vim_settings(window, cx);
1606        popped_operator
1607    }
1608
1609    fn clear_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1610        Vim::take_count(cx);
1611        Vim::take_forced_motion(cx);
1612        self.selected_register.take();
1613        self.operator_stack.clear();
1614        self.sync_vim_settings(window, cx);
1615    }
1616
1617    fn active_operator(&self) -> Option<Operator> {
1618        self.operator_stack.last().cloned()
1619    }
1620
1621    fn transaction_begun(
1622        &mut self,
1623        transaction_id: TransactionId,
1624        _window: &mut Window,
1625        _: &mut Context<Self>,
1626    ) {
1627        let mode = if (self.mode == Mode::Insert
1628            || self.mode == Mode::Replace
1629            || self.mode == Mode::Normal)
1630            && self.current_tx.is_none()
1631        {
1632            self.current_tx = Some(transaction_id);
1633            self.last_mode
1634        } else {
1635            self.mode
1636        };
1637        if mode == Mode::VisualLine || mode == Mode::VisualBlock {
1638            self.undo_modes.insert(transaction_id, mode);
1639        }
1640    }
1641
1642    fn transaction_undone(
1643        &mut self,
1644        transaction_id: &TransactionId,
1645        window: &mut Window,
1646        cx: &mut Context<Self>,
1647    ) {
1648        match self.mode {
1649            Mode::VisualLine | Mode::VisualBlock | Mode::Visual | Mode::HelixSelect => {
1650                self.update_editor(cx, |vim, editor, cx| {
1651                    let original_mode = vim.undo_modes.get(transaction_id);
1652                    editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1653                        match original_mode {
1654                            Some(Mode::VisualLine) => {
1655                                s.move_with(|map, selection| {
1656                                    selection.collapse_to(
1657                                        map.prev_line_boundary(selection.start.to_point(map)).1,
1658                                        SelectionGoal::None,
1659                                    )
1660                                });
1661                            }
1662                            Some(Mode::VisualBlock) => {
1663                                let mut first = s.first_anchor();
1664                                first.collapse_to(first.start, first.goal);
1665                                s.select_anchors(vec![first]);
1666                            }
1667                            _ => {
1668                                s.move_with(|map, selection| {
1669                                    selection.collapse_to(
1670                                        map.clip_at_line_end(selection.start),
1671                                        selection.goal,
1672                                    );
1673                                });
1674                            }
1675                        }
1676                    });
1677                });
1678                self.switch_mode(Mode::Normal, true, window, cx)
1679            }
1680            Mode::Normal => {
1681                self.update_editor(cx, |_, editor, cx| {
1682                    editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1683                        s.move_with(|map, selection| {
1684                            selection
1685                                .collapse_to(map.clip_at_line_end(selection.end), selection.goal)
1686                        })
1687                    })
1688                });
1689            }
1690            Mode::Insert | Mode::Replace | Mode::HelixNormal => {}
1691        }
1692    }
1693
1694    fn local_selections_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1695        let Some(editor) = self.editor() else { return };
1696
1697        if editor.read(cx).leader_id().is_some() {
1698            return;
1699        }
1700
1701        let newest = editor.read(cx).selections.newest_anchor().clone();
1702        let is_multicursor = editor.read(cx).selections.count() > 1;
1703        if self.mode == Mode::Insert && self.current_tx.is_some() {
1704            if self.current_anchor.is_none() {
1705                self.current_anchor = Some(newest);
1706            } else if self.current_anchor.as_ref().unwrap() != &newest
1707                && let Some(tx_id) = self.current_tx.take()
1708            {
1709                self.update_editor(cx, |_, editor, cx| {
1710                    editor.group_until_transaction(tx_id, cx)
1711                });
1712            }
1713        } else if self.mode == Mode::Normal && newest.start != newest.end {
1714            if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
1715                self.switch_mode(Mode::VisualBlock, false, window, cx);
1716            } else {
1717                self.switch_mode(Mode::Visual, false, window, cx)
1718            }
1719        } else if newest.start == newest.end
1720            && !is_multicursor
1721            && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&self.mode)
1722        {
1723            self.switch_mode(Mode::Normal, false, window, cx);
1724        }
1725    }
1726
1727    fn input_ignored(&mut self, text: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
1728        if text.is_empty() {
1729            return;
1730        }
1731
1732        match self.active_operator() {
1733            Some(Operator::FindForward { before, multiline }) => {
1734                let find = Motion::FindForward {
1735                    before,
1736                    char: text.chars().next().unwrap(),
1737                    mode: if multiline {
1738                        FindRange::MultiLine
1739                    } else {
1740                        FindRange::SingleLine
1741                    },
1742                    smartcase: VimSettings::get_global(cx).use_smartcase_find,
1743                };
1744                Vim::globals(cx).last_find = Some(find.clone());
1745                self.motion(find, window, cx)
1746            }
1747            Some(Operator::FindBackward { after, multiline }) => {
1748                let find = Motion::FindBackward {
1749                    after,
1750                    char: text.chars().next().unwrap(),
1751                    mode: if multiline {
1752                        FindRange::MultiLine
1753                    } else {
1754                        FindRange::SingleLine
1755                    },
1756                    smartcase: VimSettings::get_global(cx).use_smartcase_find,
1757                };
1758                Vim::globals(cx).last_find = Some(find.clone());
1759                self.motion(find, window, cx)
1760            }
1761            Some(Operator::Sneak { first_char }) => {
1762                if let Some(first_char) = first_char {
1763                    if let Some(second_char) = text.chars().next() {
1764                        let sneak = Motion::Sneak {
1765                            first_char,
1766                            second_char,
1767                            smartcase: VimSettings::get_global(cx).use_smartcase_find,
1768                        };
1769                        Vim::globals(cx).last_find = Some(sneak.clone());
1770                        self.motion(sneak, window, cx)
1771                    }
1772                } else {
1773                    let first_char = text.chars().next();
1774                    self.pop_operator(window, cx);
1775                    self.push_operator(Operator::Sneak { first_char }, window, cx);
1776                }
1777            }
1778            Some(Operator::SneakBackward { first_char }) => {
1779                if let Some(first_char) = first_char {
1780                    if let Some(second_char) = text.chars().next() {
1781                        let sneak = Motion::SneakBackward {
1782                            first_char,
1783                            second_char,
1784                            smartcase: VimSettings::get_global(cx).use_smartcase_find,
1785                        };
1786                        Vim::globals(cx).last_find = Some(sneak.clone());
1787                        self.motion(sneak, window, cx)
1788                    }
1789                } else {
1790                    let first_char = text.chars().next();
1791                    self.pop_operator(window, cx);
1792                    self.push_operator(Operator::SneakBackward { first_char }, window, cx);
1793                }
1794            }
1795            Some(Operator::Replace) => match self.mode {
1796                Mode::Normal => self.normal_replace(text, window, cx),
1797                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1798                    self.visual_replace(text, window, cx)
1799                }
1800                Mode::HelixNormal => self.helix_replace(&text, window, cx),
1801                _ => self.clear_operator(window, cx),
1802            },
1803            Some(Operator::Digraph { first_char }) => {
1804                if let Some(first_char) = first_char {
1805                    if let Some(second_char) = text.chars().next() {
1806                        self.insert_digraph(first_char, second_char, window, cx);
1807                    }
1808                } else {
1809                    let first_char = text.chars().next();
1810                    self.pop_operator(window, cx);
1811                    self.push_operator(Operator::Digraph { first_char }, window, cx);
1812                }
1813            }
1814            Some(Operator::Literal { prefix }) => {
1815                self.handle_literal_input(prefix.unwrap_or_default(), &text, window, cx)
1816            }
1817            Some(Operator::AddSurrounds { target }) => match self.mode {
1818                Mode::Normal => {
1819                    if let Some(target) = target {
1820                        self.add_surrounds(text, target, window, cx);
1821                        self.clear_operator(window, cx);
1822                    }
1823                }
1824                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1825                    self.add_surrounds(text, SurroundsType::Selection, window, cx);
1826                    self.clear_operator(window, cx);
1827                }
1828                _ => self.clear_operator(window, cx),
1829            },
1830            Some(Operator::ChangeSurrounds { target, opening }) => match self.mode {
1831                Mode::Normal => {
1832                    if let Some(target) = target {
1833                        self.change_surrounds(text, target, opening, window, cx);
1834                        self.clear_operator(window, cx);
1835                    }
1836                }
1837                _ => self.clear_operator(window, cx),
1838            },
1839            Some(Operator::DeleteSurrounds) => match self.mode {
1840                Mode::Normal => {
1841                    self.delete_surrounds(text, window, cx);
1842                    self.clear_operator(window, cx);
1843                }
1844                _ => self.clear_operator(window, cx),
1845            },
1846            Some(Operator::Mark) => self.create_mark(text, window, cx),
1847            Some(Operator::RecordRegister) => {
1848                self.record_register(text.chars().next().unwrap(), window, cx)
1849            }
1850            Some(Operator::ReplayRegister) => {
1851                self.replay_register(text.chars().next().unwrap(), window, cx)
1852            }
1853            Some(Operator::Register) => match self.mode {
1854                Mode::Insert => {
1855                    self.update_editor(cx, |_, editor, cx| {
1856                        if let Some(register) = Vim::update_globals(cx, |globals, cx| {
1857                            globals.read_register(text.chars().next(), Some(editor), cx)
1858                        }) {
1859                            editor.do_paste(
1860                                &register.text.to_string(),
1861                                register.clipboard_selections,
1862                                false,
1863                                window,
1864                                cx,
1865                            )
1866                        }
1867                    });
1868                    self.clear_operator(window, cx);
1869                }
1870                _ => {
1871                    self.select_register(text, window, cx);
1872                }
1873            },
1874            Some(Operator::Jump { line }) => self.jump(text, line, true, window, cx),
1875            _ => {
1876                if self.mode == Mode::Replace {
1877                    self.multi_replace(text, window, cx)
1878                }
1879
1880                if self.mode == Mode::Normal {
1881                    self.update_editor(cx, |_, editor, cx| {
1882                        editor.accept_edit_prediction(
1883                            &editor::actions::AcceptEditPrediction {},
1884                            window,
1885                            cx,
1886                        );
1887                    });
1888                }
1889            }
1890        }
1891    }
1892
1893    fn sync_vim_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1894        self.update_editor(cx, |vim, editor, cx| {
1895            editor.set_cursor_shape(vim.cursor_shape(cx), cx);
1896            editor.set_clip_at_line_ends(vim.clip_at_line_ends(), cx);
1897            editor.set_collapse_matches(true);
1898            editor.set_input_enabled(vim.editor_input_enabled());
1899            editor.set_autoindent(vim.should_autoindent());
1900            editor
1901                .selections
1902                .set_line_mode(matches!(vim.mode, Mode::VisualLine));
1903
1904            let hide_edit_predictions = !matches!(vim.mode, Mode::Insert | Mode::Replace);
1905            editor.set_edit_predictions_hidden_for_vim_mode(hide_edit_predictions, window, cx);
1906        });
1907        cx.notify()
1908    }
1909}
1910
1911struct VimSettings {
1912    pub default_mode: Mode,
1913    pub toggle_relative_line_numbers: bool,
1914    pub use_system_clipboard: settings::UseSystemClipboard,
1915    pub use_smartcase_find: bool,
1916    pub custom_digraphs: HashMap<String, Arc<str>>,
1917    pub highlight_on_yank_duration: u64,
1918    pub cursor_shape: CursorShapeSettings,
1919}
1920
1921/// The settings for cursor shape.
1922#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1923pub struct CursorShapeSettings {
1924    /// Cursor shape for the normal mode.
1925    ///
1926    /// Default: block
1927    pub normal: Option<CursorShape>,
1928    /// Cursor shape for the replace mode.
1929    ///
1930    /// Default: underline
1931    pub replace: Option<CursorShape>,
1932    /// Cursor shape for the visual mode.
1933    ///
1934    /// Default: block
1935    pub visual: Option<CursorShape>,
1936    /// Cursor shape for the insert mode.
1937    ///
1938    /// The default value follows the primary cursor_shape.
1939    pub insert: Option<CursorShape>,
1940}
1941
1942impl From<settings::CursorShapeSettings> for CursorShapeSettings {
1943    fn from(settings: settings::CursorShapeSettings) -> Self {
1944        Self {
1945            normal: settings.normal.map(Into::into),
1946            replace: settings.replace.map(Into::into),
1947            visual: settings.visual.map(Into::into),
1948            insert: settings.insert.map(Into::into),
1949        }
1950    }
1951}
1952
1953impl From<settings::ModeContent> for Mode {
1954    fn from(mode: ModeContent) -> Self {
1955        match mode {
1956            ModeContent::Normal => Self::Normal,
1957            ModeContent::Insert => Self::Insert,
1958        }
1959    }
1960}
1961
1962impl Settings for VimSettings {
1963    fn from_settings(content: &settings::SettingsContent) -> Self {
1964        let vim = content.vim.clone().unwrap();
1965        Self {
1966            default_mode: vim.default_mode.unwrap().into(),
1967            toggle_relative_line_numbers: vim.toggle_relative_line_numbers.unwrap(),
1968            use_system_clipboard: vim.use_system_clipboard.unwrap(),
1969            use_smartcase_find: vim.use_smartcase_find.unwrap(),
1970            custom_digraphs: vim.custom_digraphs.unwrap(),
1971            highlight_on_yank_duration: vim.highlight_on_yank_duration.unwrap(),
1972            cursor_shape: vim.cursor_shape.unwrap().into(),
1973        }
1974    }
1975}