1//! Vim support for Zed.
   2
   3#[cfg(test)]
   4mod test;
   5
   6mod change_list;
   7mod command;
   8mod digraph;
   9mod helix;
  10mod indent;
  11mod insert;
  12mod mode_indicator;
  13mod motion;
  14mod normal;
  15mod object;
  16mod replace;
  17mod rewrap;
  18mod state;
  19mod surrounds;
  20mod visual;
  21
  22use collections::HashMap;
  23use editor::{
  24    Anchor, Bias, Editor, EditorEvent, EditorSettings, HideMouseCursorOrigin, SelectionEffects,
  25    ToPoint,
  26    movement::{self, FindRange},
  27};
  28use gpui::{
  29    Action, App, AppContext, Axis, Context, Entity, EventEmitter, KeyContext, KeystrokeEvent,
  30    Render, Subscription, Task, WeakEntity, Window, actions,
  31};
  32use insert::{NormalBefore, TemporaryNormal};
  33use language::{
  34    CharKind, CharScopeContext, CursorShape, Point, Selection, SelectionGoal, TransactionId,
  35};
  36pub use mode_indicator::ModeIndicator;
  37use motion::Motion;
  38use normal::search::SearchSubmit;
  39use object::Object;
  40use schemars::JsonSchema;
  41use serde::Deserialize;
  42pub use settings::{
  43    ModeContent, Settings, SettingsStore, UseSystemClipboard, update_settings_file,
  44};
  45use state::{Mode, Operator, RecordedSelection, SearchState, VimGlobals};
  46use std::{mem, ops::Range, sync::Arc};
  47use surrounds::SurroundsType;
  48use theme::ThemeSettings;
  49use ui::{IntoElement, SharedString, px};
  50use vim_mode_setting::HelixModeSetting;
  51use vim_mode_setting::VimModeSetting;
  52use workspace::{self, Pane, Workspace};
  53
  54use crate::{
  55    normal::{GoToPreviousTab, GoToTab},
  56    state::ReplayableAction,
  57};
  58
  59/// Number is used to manage vim's count. Pushing a digit
  60/// multiplies the current value by 10 and adds the digit.
  61#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
  62#[action(namespace = vim)]
  63struct Number(usize);
  64
  65#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
  66#[action(namespace = vim)]
  67struct SelectRegister(String);
  68
  69#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
  70#[action(namespace = vim)]
  71#[serde(deny_unknown_fields)]
  72struct PushObject {
  73    around: bool,
  74}
  75
  76#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
  77#[action(namespace = vim)]
  78#[serde(deny_unknown_fields)]
  79struct PushFindForward {
  80    before: bool,
  81    multiline: bool,
  82}
  83
  84#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
  85#[action(namespace = vim)]
  86#[serde(deny_unknown_fields)]
  87struct PushFindBackward {
  88    after: bool,
  89    multiline: bool,
  90}
  91
  92#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
  93#[action(namespace = vim)]
  94#[serde(deny_unknown_fields)]
  95/// Selects the next object.
  96struct PushHelixNext {
  97    around: bool,
  98}
  99
 100#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
 101#[action(namespace = vim)]
 102#[serde(deny_unknown_fields)]
 103/// Selects the previous object.
 104struct PushHelixPrevious {
 105    around: bool,
 106}
 107
 108#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
 109#[action(namespace = vim)]
 110#[serde(deny_unknown_fields)]
 111struct PushSneak {
 112    first_char: Option<char>,
 113}
 114
 115#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
 116#[action(namespace = vim)]
 117#[serde(deny_unknown_fields)]
 118struct PushSneakBackward {
 119    first_char: Option<char>,
 120}
 121
 122#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
 123#[action(namespace = vim)]
 124#[serde(deny_unknown_fields)]
 125struct PushAddSurrounds;
 126
 127#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
 128#[action(namespace = vim)]
 129#[serde(deny_unknown_fields)]
 130struct PushChangeSurrounds {
 131    target: Option<Object>,
 132}
 133
 134#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
 135#[action(namespace = vim)]
 136#[serde(deny_unknown_fields)]
 137struct PushJump {
 138    line: bool,
 139}
 140
 141#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
 142#[action(namespace = vim)]
 143#[serde(deny_unknown_fields)]
 144struct PushDigraph {
 145    first_char: Option<char>,
 146}
 147
 148#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
 149#[action(namespace = vim)]
 150#[serde(deny_unknown_fields)]
 151struct PushLiteral {
 152    prefix: Option<String>,
 153}
 154
 155actions!(
 156    vim,
 157    [
 158        /// Switches to normal mode.
 159        SwitchToNormalMode,
 160        /// Switches to insert mode.
 161        SwitchToInsertMode,
 162        /// Switches to replace mode.
 163        SwitchToReplaceMode,
 164        /// Switches to visual mode.
 165        SwitchToVisualMode,
 166        /// Switches to visual line mode.
 167        SwitchToVisualLineMode,
 168        /// Switches to visual block mode.
 169        SwitchToVisualBlockMode,
 170        /// Switches to Helix-style normal mode.
 171        SwitchToHelixNormalMode,
 172        /// Clears any pending operators.
 173        ClearOperators,
 174        /// Clears the exchange register.
 175        ClearExchange,
 176        /// Inserts a tab character.
 177        Tab,
 178        /// Inserts a newline.
 179        Enter,
 180        /// Selects inner text object.
 181        InnerObject,
 182        /// Maximizes the current pane.
 183        MaximizePane,
 184        /// Opens the default keymap file.
 185        OpenDefaultKeymap,
 186        /// Resets all pane sizes to default.
 187        ResetPaneSizes,
 188        /// Resizes the pane to the right.
 189        ResizePaneRight,
 190        /// Resizes the pane to the left.
 191        ResizePaneLeft,
 192        /// Resizes the pane upward.
 193        ResizePaneUp,
 194        /// Resizes the pane downward.
 195        ResizePaneDown,
 196        /// Starts a change operation.
 197        PushChange,
 198        /// Starts a delete operation.
 199        PushDelete,
 200        /// Exchanges text regions.
 201        Exchange,
 202        /// Starts a yank operation.
 203        PushYank,
 204        /// Starts a replace operation.
 205        PushReplace,
 206        /// Deletes surrounding characters.
 207        PushDeleteSurrounds,
 208        /// Sets a mark at the current position.
 209        PushMark,
 210        /// Toggles the marks view.
 211        ToggleMarksView,
 212        /// Starts a forced motion.
 213        PushForcedMotion,
 214        /// Starts an indent operation.
 215        PushIndent,
 216        /// Starts an outdent operation.
 217        PushOutdent,
 218        /// Starts an auto-indent operation.
 219        PushAutoIndent,
 220        /// Starts a rewrap operation.
 221        PushRewrap,
 222        /// Starts a shell command operation.
 223        PushShellCommand,
 224        /// Converts to lowercase.
 225        PushLowercase,
 226        /// Converts to uppercase.
 227        PushUppercase,
 228        /// Toggles case.
 229        PushOppositeCase,
 230        /// Applies ROT13 encoding.
 231        PushRot13,
 232        /// Applies ROT47 encoding.
 233        PushRot47,
 234        /// Toggles the registers view.
 235        ToggleRegistersView,
 236        /// Selects a register.
 237        PushRegister,
 238        /// Starts recording to a register.
 239        PushRecordRegister,
 240        /// Replays a register.
 241        PushReplayRegister,
 242        /// Replaces with register contents.
 243        PushReplaceWithRegister,
 244        /// Toggles comments.
 245        PushToggleComments,
 246        /// Selects (count) next menu item
 247        MenuSelectNext,
 248        /// Selects (count) previous menu item
 249        MenuSelectPrevious,
 250        /// Clears count or toggles project panel focus
 251        ToggleProjectPanelFocus,
 252        /// Starts a match operation.
 253        PushHelixMatch,
 254    ]
 255);
 256
 257// in the workspace namespace so it's not filtered out when vim is disabled.
 258actions!(
 259    workspace,
 260    [
 261        /// Toggles Vim mode on or off.
 262        ToggleVimMode,
 263        /// Toggles Helix mode on or off.
 264        ToggleHelixMode,
 265    ]
 266);
 267
 268/// Initializes the `vim` crate.
 269pub fn init(cx: &mut App) {
 270    vim_mode_setting::init(cx);
 271    VimSettings::register(cx);
 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, false, 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            normal::register(editor, cx);
 923            insert::register(editor, cx);
 924            helix::register(editor, cx);
 925            motion::register(editor, cx);
 926            command::register(editor, cx);
 927            replace::register(editor, cx);
 928            indent::register(editor, cx);
 929            rewrap::register(editor, cx);
 930            object::register(editor, cx);
 931            visual::register(editor, cx);
 932            change_list::register(editor, cx);
 933            digraph::register(editor, cx);
 934
 935            cx.defer_in(window, |vim, window, cx| {
 936                vim.focused(false, window, cx);
 937            })
 938        })
 939    }
 940
 941    fn deactivate(editor: &mut Editor, cx: &mut Context<Editor>) {
 942        editor.set_cursor_shape(CursorShape::Bar, cx);
 943        editor.set_clip_at_line_ends(false, cx);
 944        editor.set_collapse_matches(false);
 945        editor.set_input_enabled(true);
 946        editor.set_autoindent(true);
 947        editor.selections.set_line_mode(false);
 948        editor.unregister_addon::<VimAddon>();
 949        editor.set_relative_line_number(None, cx);
 950        if let Some(vim) = Vim::globals(cx).focused_vim()
 951            && vim.entity_id() == cx.entity().entity_id()
 952        {
 953            Vim::globals(cx).focused_vim = None;
 954        }
 955    }
 956
 957    /// Register an action on the editor.
 958    pub fn action<A: Action>(
 959        editor: &mut Editor,
 960        cx: &mut Context<Vim>,
 961        f: impl Fn(&mut Vim, &A, &mut Window, &mut Context<Vim>) + 'static,
 962    ) {
 963        let subscription = editor.register_action(cx.listener(f));
 964        cx.on_release(|_, _| drop(subscription)).detach();
 965    }
 966
 967    pub fn editor(&self) -> Option<Entity<Editor>> {
 968        self.editor.upgrade()
 969    }
 970
 971    pub fn workspace(&self, window: &mut Window) -> Option<Entity<Workspace>> {
 972        window.root::<Workspace>().flatten()
 973    }
 974
 975    pub fn pane(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Entity<Pane>> {
 976        self.workspace(window)
 977            .map(|workspace| workspace.read(cx).focused_pane(window, cx))
 978    }
 979
 980    pub fn enabled(cx: &mut App) -> bool {
 981        VimModeSetting::get_global(cx).0 || HelixModeSetting::get_global(cx).0
 982    }
 983
 984    /// Called whenever an keystroke is typed so vim can observe all actions
 985    /// and keystrokes accordingly.
 986    fn observe_keystrokes(
 987        &mut self,
 988        keystroke_event: &KeystrokeEvent,
 989        window: &mut Window,
 990        cx: &mut Context<Self>,
 991    ) {
 992        if self.exit_temporary_mode {
 993            self.exit_temporary_mode = false;
 994            // Don't switch to insert mode if the action is temporary_normal.
 995            if let Some(action) = keystroke_event.action.as_ref()
 996                && action.as_any().downcast_ref::<TemporaryNormal>().is_some()
 997            {
 998                return;
 999            }
1000            self.switch_mode(Mode::Insert, false, window, cx)
1001        }
1002        if let Some(action) = keystroke_event.action.as_ref() {
1003            // Keystroke is handled by the vim system, so continue forward
1004            if action.name().starts_with("vim::") {
1005                self.update_editor(cx, |_, editor, cx| {
1006                    editor.hide_mouse_cursor(HideMouseCursorOrigin::MovementAction, cx)
1007                });
1008
1009                return;
1010            }
1011        } else if window.has_pending_keystrokes() || keystroke_event.keystroke.is_ime_in_progress()
1012        {
1013            return;
1014        }
1015
1016        if let Some(operator) = self.active_operator() {
1017            match operator {
1018                Operator::Literal { prefix } => {
1019                    self.handle_literal_keystroke(
1020                        keystroke_event,
1021                        prefix.unwrap_or_default(),
1022                        window,
1023                        cx,
1024                    );
1025                }
1026                _ if !operator.is_waiting(self.mode) => {
1027                    self.clear_operator(window, cx);
1028                    self.stop_recording_immediately(Box::new(ClearOperators), cx)
1029                }
1030                _ => {}
1031            }
1032        }
1033    }
1034
1035    fn handle_editor_event(
1036        &mut self,
1037        event: &EditorEvent,
1038        window: &mut Window,
1039        cx: &mut Context<Self>,
1040    ) {
1041        match event {
1042            EditorEvent::Focused => self.focused(true, window, cx),
1043            EditorEvent::Blurred => self.blurred(window, cx),
1044            EditorEvent::SelectionsChanged { local: true } => {
1045                self.local_selections_changed(window, cx);
1046            }
1047            EditorEvent::InputIgnored { text } => {
1048                self.input_ignored(text.clone(), window, cx);
1049                Vim::globals(cx).observe_insertion(text, None)
1050            }
1051            EditorEvent::InputHandled {
1052                text,
1053                utf16_range_to_replace: range_to_replace,
1054            } => Vim::globals(cx).observe_insertion(text, range_to_replace.clone()),
1055            EditorEvent::TransactionBegun { transaction_id } => {
1056                self.transaction_begun(*transaction_id, window, cx)
1057            }
1058            EditorEvent::TransactionUndone { transaction_id } => {
1059                self.transaction_undone(transaction_id, window, cx)
1060            }
1061            EditorEvent::Edited { .. } => self.push_to_change_list(window, cx),
1062            EditorEvent::FocusedIn => self.sync_vim_settings(window, cx),
1063            EditorEvent::CursorShapeChanged => self.cursor_shape_changed(window, cx),
1064            EditorEvent::PushedToNavHistory {
1065                anchor,
1066                is_deactivate,
1067            } => {
1068                self.update_editor(cx, |vim, editor, cx| {
1069                    let mark = if *is_deactivate {
1070                        "\"".to_string()
1071                    } else {
1072                        "'".to_string()
1073                    };
1074                    vim.set_mark(mark, vec![*anchor], editor.buffer(), window, cx);
1075                });
1076            }
1077            _ => {}
1078        }
1079    }
1080
1081    fn push_operator(&mut self, operator: Operator, window: &mut Window, cx: &mut Context<Self>) {
1082        if operator.starts_dot_recording() {
1083            self.start_recording(cx);
1084        }
1085        // Since these operations can only be entered with pre-operators,
1086        // we need to clear the previous operators when pushing,
1087        // so that the current stack is the most correct
1088        if matches!(
1089            operator,
1090            Operator::AddSurrounds { .. }
1091                | Operator::ChangeSurrounds { .. }
1092                | Operator::DeleteSurrounds
1093                | Operator::Exchange
1094        ) {
1095            self.operator_stack.clear();
1096        };
1097        self.operator_stack.push(operator);
1098        self.sync_vim_settings(window, cx);
1099    }
1100
1101    pub fn switch_mode(
1102        &mut self,
1103        mode: Mode,
1104        leave_selections: bool,
1105        window: &mut Window,
1106        cx: &mut Context<Self>,
1107    ) {
1108        if self.temp_mode && mode == Mode::Normal {
1109            self.temp_mode = false;
1110            self.switch_mode(Mode::Normal, leave_selections, window, cx);
1111            self.switch_mode(Mode::Insert, false, window, cx);
1112            return;
1113        } else if self.temp_mode
1114            && !matches!(mode, Mode::Visual | Mode::VisualLine | Mode::VisualBlock)
1115        {
1116            self.temp_mode = false;
1117        }
1118
1119        let last_mode = self.mode;
1120        let prior_mode = self.last_mode;
1121        let prior_tx = self.current_tx;
1122        self.status_label.take();
1123        self.last_mode = last_mode;
1124        self.mode = mode;
1125        self.operator_stack.clear();
1126        self.selected_register.take();
1127        self.cancel_running_command(window, cx);
1128        if mode == Mode::Normal || mode != last_mode {
1129            self.current_tx.take();
1130            self.current_anchor.take();
1131            self.update_editor(cx, |_, editor, _| {
1132                editor.clear_selection_drag_state();
1133            });
1134        }
1135        Vim::take_forced_motion(cx);
1136        if mode != Mode::Insert && mode != Mode::Replace {
1137            Vim::take_count(cx);
1138        }
1139
1140        // Sync editor settings like clip mode
1141        self.sync_vim_settings(window, cx);
1142
1143        if VimSettings::get_global(cx).toggle_relative_line_numbers
1144            && self.mode != self.last_mode
1145            && (self.mode == Mode::Insert || self.last_mode == Mode::Insert)
1146        {
1147            self.update_editor(cx, |vim, editor, cx| {
1148                let is_relative = vim.mode != Mode::Insert;
1149                editor.set_relative_line_number(Some(is_relative), cx)
1150            });
1151        }
1152        if HelixModeSetting::get_global(cx).0 {
1153            if self.mode == Mode::Normal {
1154                self.mode = Mode::HelixNormal
1155            } else if self.mode == Mode::Visual {
1156                self.mode = Mode::HelixSelect
1157            }
1158        }
1159
1160        if leave_selections {
1161            return;
1162        }
1163
1164        if !mode.is_visual() && last_mode.is_visual() {
1165            self.create_visual_marks(last_mode, window, cx);
1166        }
1167
1168        // Adjust selections
1169        self.update_editor(cx, |vim, editor, cx| {
1170            if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
1171            {
1172                vim.visual_block_motion(true, editor, window, cx, |_, point, goal| {
1173                    Some((point, goal))
1174                })
1175            }
1176            if (last_mode == Mode::Insert || last_mode == Mode::Replace)
1177                && let Some(prior_tx) = prior_tx
1178            {
1179                editor.group_until_transaction(prior_tx, cx)
1180            }
1181
1182            editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1183                // we cheat with visual block mode and use multiple cursors.
1184                // the cost of this cheat is we need to convert back to a single
1185                // cursor whenever vim would.
1186                if last_mode == Mode::VisualBlock
1187                    && (mode != Mode::VisualBlock && mode != Mode::Insert)
1188                {
1189                    let tail = s.oldest_anchor().tail();
1190                    let head = s.newest_anchor().head();
1191                    s.select_anchor_ranges(vec![tail..head]);
1192                } else if last_mode == Mode::Insert
1193                    && prior_mode == Mode::VisualBlock
1194                    && mode != Mode::VisualBlock
1195                {
1196                    let pos = s.first_anchor().head();
1197                    s.select_anchor_ranges(vec![pos..pos])
1198                }
1199
1200                let snapshot = s.display_map();
1201                if let Some(pending) = s.pending_anchor_mut()
1202                    && pending.reversed
1203                    && mode.is_visual()
1204                    && !last_mode.is_visual()
1205                {
1206                    let mut end = pending.end.to_point(&snapshot.buffer_snapshot());
1207                    end = snapshot
1208                        .buffer_snapshot()
1209                        .clip_point(end + Point::new(0, 1), Bias::Right);
1210                    pending.end = snapshot.buffer_snapshot().anchor_before(end);
1211                }
1212
1213                s.move_with(|map, selection| {
1214                    if last_mode.is_visual() && !mode.is_visual() {
1215                        let mut point = selection.head();
1216                        if !selection.reversed && !selection.is_empty() {
1217                            point = movement::left(map, selection.head());
1218                        } else if selection.is_empty() {
1219                            point = map.clip_point(point, Bias::Left);
1220                        }
1221                        selection.collapse_to(point, selection.goal)
1222                    } else if !last_mode.is_visual() && mode.is_visual() && selection.is_empty() {
1223                        selection.end = movement::right(map, selection.start);
1224                    }
1225                });
1226            })
1227        });
1228    }
1229
1230    pub fn take_count(cx: &mut App) -> Option<usize> {
1231        let global_state = cx.global_mut::<VimGlobals>();
1232        if global_state.dot_replaying {
1233            return global_state.recorded_count;
1234        }
1235
1236        let count = if global_state.post_count.is_none() && global_state.pre_count.is_none() {
1237            return None;
1238        } else {
1239            Some(
1240                global_state.post_count.take().unwrap_or(1)
1241                    * global_state.pre_count.take().unwrap_or(1),
1242            )
1243        };
1244
1245        if global_state.dot_recording {
1246            global_state.recorded_count = count;
1247        }
1248        count
1249    }
1250
1251    pub fn take_forced_motion(cx: &mut App) -> bool {
1252        let global_state = cx.global_mut::<VimGlobals>();
1253        let forced_motion = global_state.forced_motion;
1254        global_state.forced_motion = false;
1255        forced_motion
1256    }
1257
1258    pub fn cursor_shape(&self, cx: &mut App) -> CursorShape {
1259        let cursor_shape = VimSettings::get_global(cx).cursor_shape;
1260        match self.mode {
1261            Mode::Normal => {
1262                if let Some(operator) = self.operator_stack.last() {
1263                    match operator {
1264                        // Navigation operators -> Block cursor
1265                        Operator::FindForward { .. }
1266                        | Operator::FindBackward { .. }
1267                        | Operator::Mark
1268                        | Operator::Jump { .. }
1269                        | Operator::Register
1270                        | Operator::RecordRegister
1271                        | Operator::ReplayRegister => CursorShape::Block,
1272
1273                        // All other operators -> Underline cursor
1274                        _ => CursorShape::Underline,
1275                    }
1276                } else {
1277                    cursor_shape.normal.unwrap_or(CursorShape::Block)
1278                }
1279            }
1280            Mode::HelixNormal => cursor_shape.normal.unwrap_or(CursorShape::Block),
1281            Mode::Replace => cursor_shape.replace.unwrap_or(CursorShape::Underline),
1282            Mode::Visual | Mode::VisualLine | Mode::VisualBlock | Mode::HelixSelect => {
1283                cursor_shape.visual.unwrap_or(CursorShape::Block)
1284            }
1285            Mode::Insert => cursor_shape.insert.unwrap_or({
1286                let editor_settings = EditorSettings::get_global(cx);
1287                editor_settings.cursor_shape.unwrap_or_default()
1288            }),
1289        }
1290    }
1291
1292    pub fn editor_input_enabled(&self) -> bool {
1293        match self.mode {
1294            Mode::Insert => {
1295                if let Some(operator) = self.operator_stack.last() {
1296                    !operator.is_waiting(self.mode)
1297                } else {
1298                    true
1299                }
1300            }
1301            Mode::Normal
1302            | Mode::HelixNormal
1303            | Mode::Replace
1304            | Mode::Visual
1305            | Mode::VisualLine
1306            | Mode::VisualBlock
1307            | Mode::HelixSelect => false,
1308        }
1309    }
1310
1311    pub fn should_autoindent(&self) -> bool {
1312        !(self.mode == Mode::Insert && self.last_mode == Mode::VisualBlock)
1313    }
1314
1315    pub fn clip_at_line_ends(&self) -> bool {
1316        match self.mode {
1317            Mode::Insert
1318            | Mode::Visual
1319            | Mode::VisualLine
1320            | Mode::VisualBlock
1321            | Mode::Replace
1322            | Mode::HelixNormal
1323            | Mode::HelixSelect => false,
1324            Mode::Normal => true,
1325        }
1326    }
1327
1328    pub fn extend_key_context(&self, context: &mut KeyContext, cx: &App) {
1329        let mut mode = match self.mode {
1330            Mode::Normal => "normal",
1331            Mode::Visual | Mode::VisualLine | Mode::VisualBlock => "visual",
1332            Mode::Insert => "insert",
1333            Mode::Replace => "replace",
1334            Mode::HelixNormal => "helix_normal",
1335            Mode::HelixSelect => "helix_select",
1336        }
1337        .to_string();
1338
1339        let mut operator_id = "none";
1340
1341        let active_operator = self.active_operator();
1342        if active_operator.is_none() && cx.global::<VimGlobals>().pre_count.is_some()
1343            || active_operator.is_some() && cx.global::<VimGlobals>().post_count.is_some()
1344        {
1345            context.add("VimCount");
1346        }
1347
1348        if let Some(active_operator) = active_operator {
1349            if active_operator.is_waiting(self.mode) {
1350                if matches!(active_operator, Operator::Literal { .. }) {
1351                    mode = "literal".to_string();
1352                } else {
1353                    mode = "waiting".to_string();
1354                }
1355            } else {
1356                operator_id = active_operator.id();
1357                mode = "operator".to_string();
1358            }
1359        }
1360
1361        if mode == "normal"
1362            || mode == "visual"
1363            || mode == "operator"
1364            || mode == "helix_normal"
1365            || mode == "helix_select"
1366        {
1367            context.add("VimControl");
1368        }
1369        context.set("vim_mode", mode);
1370        context.set("vim_operator", operator_id);
1371    }
1372
1373    fn focused(&mut self, preserve_selection: bool, window: &mut Window, cx: &mut Context<Self>) {
1374        let Some(editor) = self.editor() else {
1375            return;
1376        };
1377        let newest_selection_empty = editor.update(cx, |editor, cx| {
1378            editor
1379                .selections
1380                .newest::<usize>(&editor.display_snapshot(cx))
1381                .is_empty()
1382        });
1383        let editor = editor.read(cx);
1384        let editor_mode = editor.mode();
1385
1386        if editor_mode.is_full()
1387            && !newest_selection_empty
1388            && self.mode == Mode::Normal
1389            // When following someone, don't switch vim mode.
1390            && editor.leader_id().is_none()
1391        {
1392            if preserve_selection {
1393                self.switch_mode(Mode::Visual, true, window, cx);
1394            } else {
1395                self.update_editor(cx, |_, editor, cx| {
1396                    editor.set_clip_at_line_ends(false, cx);
1397                    editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1398                        s.move_with(|_, selection| {
1399                            selection.collapse_to(selection.start, selection.goal)
1400                        })
1401                    });
1402                });
1403            }
1404        }
1405
1406        cx.emit(VimEvent::Focused);
1407        self.sync_vim_settings(window, cx);
1408
1409        if VimSettings::get_global(cx).toggle_relative_line_numbers {
1410            if let Some(old_vim) = Vim::globals(cx).focused_vim() {
1411                if old_vim.entity_id() != cx.entity().entity_id() {
1412                    old_vim.update(cx, |vim, cx| {
1413                        vim.update_editor(cx, |_, editor, cx| {
1414                            editor.set_relative_line_number(None, cx)
1415                        });
1416                    });
1417
1418                    self.update_editor(cx, |vim, editor, cx| {
1419                        let is_relative = vim.mode != Mode::Insert;
1420                        editor.set_relative_line_number(Some(is_relative), cx)
1421                    });
1422                }
1423            } else {
1424                self.update_editor(cx, |vim, editor, cx| {
1425                    let is_relative = vim.mode != Mode::Insert;
1426                    editor.set_relative_line_number(Some(is_relative), cx)
1427                });
1428            }
1429        }
1430        Vim::globals(cx).focused_vim = Some(cx.entity().downgrade());
1431    }
1432
1433    fn blurred(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1434        self.stop_recording_immediately(NormalBefore.boxed_clone(), cx);
1435        self.store_visual_marks(window, cx);
1436        self.clear_operator(window, cx);
1437        self.update_editor(cx, |vim, editor, cx| {
1438            if vim.cursor_shape(cx) == CursorShape::Block {
1439                editor.set_cursor_shape(CursorShape::Hollow, cx);
1440            }
1441        });
1442    }
1443
1444    fn cursor_shape_changed(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1445        self.update_editor(cx, |vim, editor, cx| {
1446            editor.set_cursor_shape(vim.cursor_shape(cx), cx);
1447        });
1448    }
1449
1450    fn update_editor<S>(
1451        &mut self,
1452        cx: &mut Context<Self>,
1453        update: impl FnOnce(&mut Self, &mut Editor, &mut Context<Editor>) -> S,
1454    ) -> Option<S> {
1455        let editor = self.editor.upgrade()?;
1456        Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
1457    }
1458
1459    fn editor_selections(&mut self, _: &mut Window, cx: &mut Context<Self>) -> Vec<Range<Anchor>> {
1460        self.update_editor(cx, |_, editor, _| {
1461            editor
1462                .selections
1463                .disjoint_anchors_arc()
1464                .iter()
1465                .map(|selection| selection.tail()..selection.head())
1466                .collect()
1467        })
1468        .unwrap_or_default()
1469    }
1470
1471    fn editor_cursor_word(
1472        &mut self,
1473        window: &mut Window,
1474        cx: &mut Context<Self>,
1475    ) -> Option<String> {
1476        self.update_editor(cx, |_, editor, cx| {
1477            let snapshot = &editor.snapshot(window, cx);
1478            let selection = editor
1479                .selections
1480                .newest::<usize>(&snapshot.display_snapshot);
1481
1482            let snapshot = snapshot.buffer_snapshot();
1483            let (range, kind) =
1484                snapshot.surrounding_word(selection.start, Some(CharScopeContext::Completion));
1485            if kind == Some(CharKind::Word) {
1486                let text: String = snapshot.text_for_range(range).collect();
1487                if !text.trim().is_empty() {
1488                    return Some(text);
1489                }
1490            }
1491
1492            None
1493        })
1494        .unwrap_or_default()
1495    }
1496
1497    /// When doing an action that modifies the buffer, we start recording so that `.`
1498    /// will replay the action.
1499    pub fn start_recording(&mut self, cx: &mut Context<Self>) {
1500        Vim::update_globals(cx, |globals, cx| {
1501            if !globals.dot_replaying {
1502                globals.dot_recording = true;
1503                globals.recording_actions = Default::default();
1504                globals.recorded_count = None;
1505
1506                let selections = self.editor().map(|editor| {
1507                    editor.update(cx, |editor, cx| {
1508                        let snapshot = editor.display_snapshot(cx);
1509
1510                        (
1511                            editor.selections.oldest::<Point>(&snapshot),
1512                            editor.selections.newest::<Point>(&snapshot),
1513                        )
1514                    })
1515                });
1516
1517                if let Some((oldest, newest)) = selections {
1518                    globals.recorded_selection = match self.mode {
1519                        Mode::Visual if newest.end.row == newest.start.row => {
1520                            RecordedSelection::SingleLine {
1521                                cols: newest.end.column - newest.start.column,
1522                            }
1523                        }
1524                        Mode::Visual => RecordedSelection::Visual {
1525                            rows: newest.end.row - newest.start.row,
1526                            cols: newest.end.column,
1527                        },
1528                        Mode::VisualLine => RecordedSelection::VisualLine {
1529                            rows: newest.end.row - newest.start.row,
1530                        },
1531                        Mode::VisualBlock => RecordedSelection::VisualBlock {
1532                            rows: newest.end.row.abs_diff(oldest.start.row),
1533                            cols: newest.end.column.abs_diff(oldest.start.column),
1534                        },
1535                        _ => RecordedSelection::None,
1536                    }
1537                } else {
1538                    globals.recorded_selection = RecordedSelection::None;
1539                }
1540            }
1541        })
1542    }
1543
1544    pub fn stop_replaying(&mut self, cx: &mut Context<Self>) {
1545        let globals = Vim::globals(cx);
1546        globals.dot_replaying = false;
1547        if let Some(replayer) = globals.replayer.take() {
1548            replayer.stop();
1549        }
1550    }
1551
1552    /// When finishing an action that modifies the buffer, stop recording.
1553    /// as you usually call this within a keystroke handler we also ensure that
1554    /// the current action is recorded.
1555    pub fn stop_recording(&mut self, cx: &mut Context<Self>) {
1556        let globals = Vim::globals(cx);
1557        if globals.dot_recording {
1558            globals.stop_recording_after_next_action = true;
1559        }
1560        self.exit_temporary_mode = self.temp_mode;
1561    }
1562
1563    /// Stops recording actions immediately rather than waiting until after the
1564    /// next action to stop recording.
1565    ///
1566    /// This doesn't include the current action.
1567    pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>, cx: &mut Context<Self>) {
1568        let globals = Vim::globals(cx);
1569        if globals.dot_recording {
1570            globals
1571                .recording_actions
1572                .push(ReplayableAction::Action(action.boxed_clone()));
1573            globals.recorded_actions = mem::take(&mut globals.recording_actions);
1574            globals.dot_recording = false;
1575            globals.stop_recording_after_next_action = false;
1576        }
1577        self.exit_temporary_mode = self.temp_mode;
1578    }
1579
1580    /// Explicitly record one action (equivalents to start_recording and stop_recording)
1581    pub fn record_current_action(&mut self, cx: &mut Context<Self>) {
1582        self.start_recording(cx);
1583        self.stop_recording(cx);
1584    }
1585
1586    fn push_count_digit(&mut self, number: usize, window: &mut Window, cx: &mut Context<Self>) {
1587        if self.active_operator().is_some() {
1588            let post_count = Vim::globals(cx).post_count.unwrap_or(0);
1589
1590            Vim::globals(cx).post_count = Some(
1591                post_count
1592                    .checked_mul(10)
1593                    .and_then(|post_count| post_count.checked_add(number))
1594                    .filter(|post_count| *post_count < isize::MAX as usize)
1595                    .unwrap_or(post_count),
1596            )
1597        } else {
1598            let pre_count = Vim::globals(cx).pre_count.unwrap_or(0);
1599
1600            Vim::globals(cx).pre_count = Some(
1601                pre_count
1602                    .checked_mul(10)
1603                    .and_then(|pre_count| pre_count.checked_add(number))
1604                    .filter(|pre_count| *pre_count < isize::MAX as usize)
1605                    .unwrap_or(pre_count),
1606            )
1607        }
1608        // update the keymap so that 0 works
1609        self.sync_vim_settings(window, cx)
1610    }
1611
1612    fn select_register(&mut self, register: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
1613        if register.chars().count() == 1 {
1614            self.selected_register
1615                .replace(register.chars().next().unwrap());
1616        }
1617        self.operator_stack.clear();
1618        self.sync_vim_settings(window, cx);
1619    }
1620
1621    fn maybe_pop_operator(&mut self) -> Option<Operator> {
1622        self.operator_stack.pop()
1623    }
1624
1625    fn pop_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Operator {
1626        let popped_operator = self.operator_stack.pop()
1627            .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
1628        self.sync_vim_settings(window, cx);
1629        popped_operator
1630    }
1631
1632    fn clear_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1633        Vim::take_count(cx);
1634        Vim::take_forced_motion(cx);
1635        self.selected_register.take();
1636        self.operator_stack.clear();
1637        self.sync_vim_settings(window, cx);
1638    }
1639
1640    fn active_operator(&self) -> Option<Operator> {
1641        self.operator_stack.last().cloned()
1642    }
1643
1644    fn transaction_begun(
1645        &mut self,
1646        transaction_id: TransactionId,
1647        _window: &mut Window,
1648        _: &mut Context<Self>,
1649    ) {
1650        let mode = if (self.mode == Mode::Insert
1651            || self.mode == Mode::Replace
1652            || self.mode == Mode::Normal)
1653            && self.current_tx.is_none()
1654        {
1655            self.current_tx = Some(transaction_id);
1656            self.last_mode
1657        } else {
1658            self.mode
1659        };
1660        if mode == Mode::VisualLine || mode == Mode::VisualBlock {
1661            self.undo_modes.insert(transaction_id, mode);
1662        }
1663    }
1664
1665    fn transaction_undone(
1666        &mut self,
1667        transaction_id: &TransactionId,
1668        window: &mut Window,
1669        cx: &mut Context<Self>,
1670    ) {
1671        match self.mode {
1672            Mode::VisualLine | Mode::VisualBlock | Mode::Visual | Mode::HelixSelect => {
1673                self.update_editor(cx, |vim, editor, cx| {
1674                    let original_mode = vim.undo_modes.get(transaction_id);
1675                    editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1676                        match original_mode {
1677                            Some(Mode::VisualLine) => {
1678                                s.move_with(|map, selection| {
1679                                    selection.collapse_to(
1680                                        map.prev_line_boundary(selection.start.to_point(map)).1,
1681                                        SelectionGoal::None,
1682                                    )
1683                                });
1684                            }
1685                            Some(Mode::VisualBlock) => {
1686                                let mut first = s.first_anchor();
1687                                first.collapse_to(first.start, first.goal);
1688                                s.select_anchors(vec![first]);
1689                            }
1690                            _ => {
1691                                s.move_with(|map, selection| {
1692                                    selection.collapse_to(
1693                                        map.clip_at_line_end(selection.start),
1694                                        selection.goal,
1695                                    );
1696                                });
1697                            }
1698                        }
1699                    });
1700                });
1701                self.switch_mode(Mode::Normal, true, window, cx)
1702            }
1703            Mode::Normal => {
1704                self.update_editor(cx, |_, editor, cx| {
1705                    editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1706                        s.move_with(|map, selection| {
1707                            selection
1708                                .collapse_to(map.clip_at_line_end(selection.end), selection.goal)
1709                        })
1710                    })
1711                });
1712            }
1713            Mode::Insert | Mode::Replace | Mode::HelixNormal => {}
1714        }
1715    }
1716
1717    fn local_selections_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1718        let Some(editor) = self.editor() else { return };
1719
1720        if editor.read(cx).leader_id().is_some() {
1721            return;
1722        }
1723
1724        let newest = editor.read(cx).selections.newest_anchor().clone();
1725        let is_multicursor = editor.read(cx).selections.count() > 1;
1726        if self.mode == Mode::Insert && self.current_tx.is_some() {
1727            if self.current_anchor.is_none() {
1728                self.current_anchor = Some(newest);
1729            } else if self.current_anchor.as_ref().unwrap() != &newest
1730                && let Some(tx_id) = self.current_tx.take()
1731            {
1732                self.update_editor(cx, |_, editor, cx| {
1733                    editor.group_until_transaction(tx_id, cx)
1734                });
1735            }
1736        } else if self.mode == Mode::Normal && newest.start != newest.end {
1737            if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
1738                self.switch_mode(Mode::VisualBlock, false, window, cx);
1739            } else {
1740                self.switch_mode(Mode::Visual, false, window, cx)
1741            }
1742        } else if newest.start == newest.end
1743            && !is_multicursor
1744            && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&self.mode)
1745        {
1746            self.switch_mode(Mode::Normal, false, window, cx);
1747        }
1748    }
1749
1750    fn input_ignored(&mut self, text: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
1751        if text.is_empty() {
1752            return;
1753        }
1754
1755        match self.active_operator() {
1756            Some(Operator::FindForward { before, multiline }) => {
1757                let find = Motion::FindForward {
1758                    before,
1759                    char: text.chars().next().unwrap(),
1760                    mode: if multiline {
1761                        FindRange::MultiLine
1762                    } else {
1763                        FindRange::SingleLine
1764                    },
1765                    smartcase: VimSettings::get_global(cx).use_smartcase_find,
1766                };
1767                Vim::globals(cx).last_find = Some(find.clone());
1768                self.motion(find, window, cx)
1769            }
1770            Some(Operator::FindBackward { after, multiline }) => {
1771                let find = Motion::FindBackward {
1772                    after,
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::Sneak { first_char }) => {
1785                if let Some(first_char) = first_char {
1786                    if let Some(second_char) = text.chars().next() {
1787                        let sneak = Motion::Sneak {
1788                            first_char,
1789                            second_char,
1790                            smartcase: VimSettings::get_global(cx).use_smartcase_find,
1791                        };
1792                        Vim::globals(cx).last_find = Some(sneak.clone());
1793                        self.motion(sneak, window, cx)
1794                    }
1795                } else {
1796                    let first_char = text.chars().next();
1797                    self.pop_operator(window, cx);
1798                    self.push_operator(Operator::Sneak { first_char }, window, cx);
1799                }
1800            }
1801            Some(Operator::SneakBackward { first_char }) => {
1802                if let Some(first_char) = first_char {
1803                    if let Some(second_char) = text.chars().next() {
1804                        let sneak = Motion::SneakBackward {
1805                            first_char,
1806                            second_char,
1807                            smartcase: VimSettings::get_global(cx).use_smartcase_find,
1808                        };
1809                        Vim::globals(cx).last_find = Some(sneak.clone());
1810                        self.motion(sneak, window, cx)
1811                    }
1812                } else {
1813                    let first_char = text.chars().next();
1814                    self.pop_operator(window, cx);
1815                    self.push_operator(Operator::SneakBackward { first_char }, window, cx);
1816                }
1817            }
1818            Some(Operator::Replace) => match self.mode {
1819                Mode::Normal => self.normal_replace(text, window, cx),
1820                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1821                    self.visual_replace(text, window, cx)
1822                }
1823                Mode::HelixNormal => self.helix_replace(&text, window, cx),
1824                _ => self.clear_operator(window, cx),
1825            },
1826            Some(Operator::Digraph { first_char }) => {
1827                if let Some(first_char) = first_char {
1828                    if let Some(second_char) = text.chars().next() {
1829                        self.insert_digraph(first_char, second_char, window, cx);
1830                    }
1831                } else {
1832                    let first_char = text.chars().next();
1833                    self.pop_operator(window, cx);
1834                    self.push_operator(Operator::Digraph { first_char }, window, cx);
1835                }
1836            }
1837            Some(Operator::Literal { prefix }) => {
1838                self.handle_literal_input(prefix.unwrap_or_default(), &text, window, cx)
1839            }
1840            Some(Operator::AddSurrounds { target }) => match self.mode {
1841                Mode::Normal => {
1842                    if let Some(target) = target {
1843                        self.add_surrounds(text, target, window, cx);
1844                        self.clear_operator(window, cx);
1845                    }
1846                }
1847                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1848                    self.add_surrounds(text, SurroundsType::Selection, window, cx);
1849                    self.clear_operator(window, cx);
1850                }
1851                _ => self.clear_operator(window, cx),
1852            },
1853            Some(Operator::ChangeSurrounds { target, opening }) => match self.mode {
1854                Mode::Normal => {
1855                    if let Some(target) = target {
1856                        self.change_surrounds(text, target, opening, window, cx);
1857                        self.clear_operator(window, cx);
1858                    }
1859                }
1860                _ => self.clear_operator(window, cx),
1861            },
1862            Some(Operator::DeleteSurrounds) => match self.mode {
1863                Mode::Normal => {
1864                    self.delete_surrounds(text, window, cx);
1865                    self.clear_operator(window, cx);
1866                }
1867                _ => self.clear_operator(window, cx),
1868            },
1869            Some(Operator::Mark) => self.create_mark(text, window, cx),
1870            Some(Operator::RecordRegister) => {
1871                self.record_register(text.chars().next().unwrap(), window, cx)
1872            }
1873            Some(Operator::ReplayRegister) => {
1874                self.replay_register(text.chars().next().unwrap(), window, cx)
1875            }
1876            Some(Operator::Register) => match self.mode {
1877                Mode::Insert => {
1878                    self.update_editor(cx, |_, editor, cx| {
1879                        if let Some(register) = Vim::update_globals(cx, |globals, cx| {
1880                            globals.read_register(text.chars().next(), Some(editor), cx)
1881                        }) {
1882                            editor.do_paste(
1883                                ®ister.text.to_string(),
1884                                register.clipboard_selections,
1885                                false,
1886                                window,
1887                                cx,
1888                            )
1889                        }
1890                    });
1891                    self.clear_operator(window, cx);
1892                }
1893                _ => {
1894                    self.select_register(text, window, cx);
1895                }
1896            },
1897            Some(Operator::Jump { line }) => self.jump(text, line, true, window, cx),
1898            _ => {
1899                if self.mode == Mode::Replace {
1900                    self.multi_replace(text, window, cx)
1901                }
1902
1903                if self.mode == Mode::Normal {
1904                    self.update_editor(cx, |_, editor, cx| {
1905                        editor.accept_edit_prediction(
1906                            &editor::actions::AcceptEditPrediction {},
1907                            window,
1908                            cx,
1909                        );
1910                    });
1911                }
1912            }
1913        }
1914    }
1915
1916    fn sync_vim_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1917        self.update_editor(cx, |vim, editor, cx| {
1918            editor.set_cursor_shape(vim.cursor_shape(cx), cx);
1919            editor.set_clip_at_line_ends(vim.clip_at_line_ends(), cx);
1920            editor.set_collapse_matches(true);
1921            editor.set_input_enabled(vim.editor_input_enabled());
1922            editor.set_autoindent(vim.should_autoindent());
1923            editor
1924                .selections
1925                .set_line_mode(matches!(vim.mode, Mode::VisualLine));
1926
1927            let hide_edit_predictions = !matches!(vim.mode, Mode::Insert | Mode::Replace);
1928            editor.set_edit_predictions_hidden_for_vim_mode(hide_edit_predictions, window, cx);
1929        });
1930        cx.notify()
1931    }
1932}
1933
1934struct VimSettings {
1935    pub default_mode: Mode,
1936    pub toggle_relative_line_numbers: bool,
1937    pub use_system_clipboard: settings::UseSystemClipboard,
1938    pub use_smartcase_find: bool,
1939    pub custom_digraphs: HashMap<String, Arc<str>>,
1940    pub highlight_on_yank_duration: u64,
1941    pub cursor_shape: CursorShapeSettings,
1942}
1943
1944/// The settings for cursor shape.
1945#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1946pub struct CursorShapeSettings {
1947    /// Cursor shape for the normal mode.
1948    ///
1949    /// Default: block
1950    pub normal: Option<CursorShape>,
1951    /// Cursor shape for the replace mode.
1952    ///
1953    /// Default: underline
1954    pub replace: Option<CursorShape>,
1955    /// Cursor shape for the visual mode.
1956    ///
1957    /// Default: block
1958    pub visual: Option<CursorShape>,
1959    /// Cursor shape for the insert mode.
1960    ///
1961    /// The default value follows the primary cursor_shape.
1962    pub insert: Option<CursorShape>,
1963}
1964
1965impl From<settings::CursorShapeSettings> for CursorShapeSettings {
1966    fn from(settings: settings::CursorShapeSettings) -> Self {
1967        Self {
1968            normal: settings.normal.map(Into::into),
1969            replace: settings.replace.map(Into::into),
1970            visual: settings.visual.map(Into::into),
1971            insert: settings.insert.map(Into::into),
1972        }
1973    }
1974}
1975
1976impl From<settings::ModeContent> for Mode {
1977    fn from(mode: ModeContent) -> Self {
1978        match mode {
1979            ModeContent::Normal => Self::Normal,
1980            ModeContent::Insert => Self::Insert,
1981        }
1982    }
1983}
1984
1985impl Settings for VimSettings {
1986    fn from_settings(content: &settings::SettingsContent) -> Self {
1987        let vim = content.vim.clone().unwrap();
1988        Self {
1989            default_mode: vim.default_mode.unwrap().into(),
1990            toggle_relative_line_numbers: vim.toggle_relative_line_numbers.unwrap(),
1991            use_system_clipboard: vim.use_system_clipboard.unwrap(),
1992            use_smartcase_find: vim.use_smartcase_find.unwrap(),
1993            custom_digraphs: vim.custom_digraphs.unwrap(),
1994            highlight_on_yank_duration: vim.highlight_on_yank_duration.unwrap(),
1995            cursor_shape: vim.cursor_shape.unwrap().into(),
1996        }
1997    }
1998}