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