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