vim.rs

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