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