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