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