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