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