vim.rs

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