vim.rs

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