vim.rs

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