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