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