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    movement::{self, FindRange},
  26    Anchor, Bias, Editor, EditorEvent, EditorMode, ToPoint,
  27};
  28use gpui::{
  29    actions, impl_actions, Action, AppContext, Axis, Entity, EventEmitter, KeyContext,
  30    KeystrokeEvent, Render, Subscription, View, ViewContext, WeakView,
  31};
  32use insert::{NormalBefore, TemporaryNormal};
  33use language::{CursorShape, Point, Selection, SelectionGoal, TransactionId};
  34pub use mode_indicator::ModeIndicator;
  35use motion::Motion;
  36use normal::search::SearchSubmit;
  37use schemars::JsonSchema;
  38use serde::Deserialize;
  39use serde_derive::Serialize;
  40use settings::{update_settings_file, Settings, SettingsSources, SettingsStore};
  41use state::{Mode, Operator, RecordedSelection, SearchState, VimGlobals};
  42use std::{mem, ops::Range, sync::Arc};
  43use surrounds::SurroundsType;
  44use theme::ThemeSettings;
  45use ui::{px, IntoElement, VisualContext};
  46use vim_mode_setting::VimModeSetting;
  47use workspace::{self, Pane, ResizeIntent, Workspace};
  48
  49use crate::state::ReplayableAction;
  50
  51/// Used to resize the current pane
  52#[derive(Clone, Deserialize, PartialEq)]
  53pub struct ResizePane(pub ResizeIntent);
  54
  55/// An Action to Switch between modes
  56#[derive(Clone, Deserialize, PartialEq)]
  57pub struct SwitchMode(pub Mode);
  58
  59/// PushOperator is used to put vim into a "minor" mode,
  60/// where it's waiting for a specific next set of keystrokes.
  61/// For example 'd' needs a motion to complete.
  62#[derive(Clone, Deserialize, PartialEq)]
  63pub struct PushOperator(pub Operator);
  64
  65/// Number is used to manage vim's count. Pushing a digit
  66/// multiplis the current value by 10 and adds the digit.
  67#[derive(Clone, Deserialize, PartialEq)]
  68struct Number(usize);
  69
  70#[derive(Clone, Deserialize, PartialEq)]
  71struct SelectRegister(String);
  72
  73actions!(
  74    vim,
  75    [
  76        ClearOperators,
  77        Tab,
  78        Enter,
  79        Object,
  80        InnerObject,
  81        FindForward,
  82        FindBackward,
  83        OpenDefaultKeymap,
  84        MaximizePane,
  85        ResetPaneSizes,
  86    ]
  87);
  88
  89// in the workspace namespace so it's not filtered out when vim is disabled.
  90actions!(workspace, [ToggleVimMode]);
  91
  92impl_actions!(
  93    vim,
  94    [ResizePane, SwitchMode, PushOperator, Number, SelectRegister]
  95);
  96
  97/// Initializes the `vim` crate.
  98pub fn init(cx: &mut AppContext) {
  99    vim_mode_setting::init(cx);
 100    VimSettings::register(cx);
 101    VimGlobals::register(cx);
 102
 103    cx.observe_new_views(|editor: &mut Editor, cx| Vim::register(editor, cx))
 104        .detach();
 105
 106    cx.observe_new_views(|workspace: &mut Workspace, _| {
 107        workspace.register_action(|workspace, _: &ToggleVimMode, cx| {
 108            let fs = workspace.app_state().fs.clone();
 109            let currently_enabled = Vim::enabled(cx);
 110            update_settings_file::<VimModeSetting>(fs, cx, move |setting, _| {
 111                *setting = Some(!currently_enabled)
 112            })
 113        });
 114
 115        workspace.register_action(|_, _: &OpenDefaultKeymap, cx| {
 116            cx.emit(workspace::Event::OpenBundledFile {
 117                text: settings::vim_keymap(),
 118                title: "Default Vim Bindings",
 119                language: "JSON",
 120            });
 121        });
 122
 123        workspace.register_action(|workspace, _: &ResetPaneSizes, cx| {
 124            workspace.reset_pane_sizes(cx);
 125        });
 126
 127        workspace.register_action(|workspace, _: &MaximizePane, cx| {
 128            let pane = workspace.active_pane();
 129            let Some(size) = workspace.bounding_box_for_pane(&pane) else {
 130                return;
 131            };
 132
 133            let theme = ThemeSettings::get_global(cx);
 134            let height = theme.buffer_font_size(cx) * theme.buffer_line_height.value();
 135
 136            let desired_size = if let Some(count) = Vim::take_count(cx) {
 137                height * count
 138            } else {
 139                px(10000.)
 140            };
 141            workspace.resize_pane(Axis::Vertical, desired_size - size.size.height, cx)
 142        });
 143
 144        workspace.register_action(|workspace, action: &ResizePane, cx| {
 145            let count = Vim::take_count(cx).unwrap_or(1) as f32;
 146            let theme = ThemeSettings::get_global(cx);
 147            let Ok(font_id) = cx.text_system().font_id(&theme.buffer_font) else {
 148                return;
 149            };
 150            let Ok(width) = cx
 151                .text_system()
 152                .advance(font_id, theme.buffer_font_size(cx), 'm')
 153            else {
 154                return;
 155            };
 156            let height = theme.buffer_font_size(cx) * theme.buffer_line_height.value();
 157
 158            let (axis, amount) = match action.0 {
 159                ResizeIntent::Lengthen => (Axis::Vertical, height),
 160                ResizeIntent::Shorten => (Axis::Vertical, height * -1.),
 161                ResizeIntent::Widen => (Axis::Horizontal, width.width),
 162                ResizeIntent::Narrow => (Axis::Horizontal, width.width * -1.),
 163            };
 164
 165            workspace.resize_pane(axis, amount * count, cx);
 166        });
 167
 168        workspace.register_action(|workspace, _: &SearchSubmit, cx| {
 169            let vim = workspace
 170                .focused_pane(cx)
 171                .read(cx)
 172                .active_item()
 173                .and_then(|item| item.act_as::<Editor>(cx))
 174                .and_then(|editor| editor.read(cx).addon::<VimAddon>().cloned());
 175            let Some(vim) = vim else { return };
 176            vim.view
 177                .update(cx, |_, cx| cx.defer(|vim, cx| vim.search_submit(cx)))
 178        });
 179    })
 180    .detach();
 181}
 182
 183#[derive(Clone)]
 184pub(crate) struct VimAddon {
 185    pub(crate) view: View<Vim>,
 186}
 187
 188impl editor::Addon for VimAddon {
 189    fn extend_key_context(&self, key_context: &mut KeyContext, cx: &AppContext) {
 190        self.view.read(cx).extend_key_context(key_context, cx)
 191    }
 192
 193    fn to_any(&self) -> &dyn std::any::Any {
 194        self
 195    }
 196}
 197
 198/// The state pertaining to Vim mode.
 199pub(crate) struct Vim {
 200    pub(crate) mode: Mode,
 201    pub last_mode: Mode,
 202    pub temp_mode: bool,
 203    pub exit_temporary_mode: bool,
 204
 205    operator_stack: Vec<Operator>,
 206    pub(crate) replacements: Vec<(Range<editor::Anchor>, String)>,
 207
 208    pub(crate) marks: HashMap<String, Vec<Anchor>>,
 209    pub(crate) stored_visual_mode: Option<(Mode, Vec<bool>)>,
 210    pub(crate) change_list: Vec<Vec<Anchor>>,
 211    pub(crate) change_list_position: Option<usize>,
 212
 213    pub(crate) current_tx: Option<TransactionId>,
 214    pub(crate) current_anchor: Option<Selection<Anchor>>,
 215    pub(crate) undo_modes: HashMap<TransactionId, Mode>,
 216
 217    selected_register: Option<char>,
 218    pub search: SearchState,
 219
 220    editor: WeakView<Editor>,
 221
 222    _subscriptions: Vec<Subscription>,
 223}
 224
 225// Hack: Vim intercepts events dispatched to a window and updates the view in response.
 226// This means it needs a VisualContext. The easiest way to satisfy that constraint is
 227// to make Vim a "View" that is just never actually rendered.
 228impl Render for Vim {
 229    fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
 230        gpui::Empty
 231    }
 232}
 233
 234enum VimEvent {
 235    Focused,
 236}
 237impl EventEmitter<VimEvent> for Vim {}
 238
 239impl Vim {
 240    /// The namespace for Vim actions.
 241    const NAMESPACE: &'static str = "vim";
 242
 243    pub fn new(cx: &mut ViewContext<Editor>) -> View<Self> {
 244        let editor = cx.view().clone();
 245
 246        cx.new_view(|cx| Vim {
 247            mode: Mode::Normal,
 248            last_mode: Mode::Normal,
 249            temp_mode: false,
 250            exit_temporary_mode: false,
 251            operator_stack: Vec::new(),
 252            replacements: Vec::new(),
 253
 254            marks: HashMap::default(),
 255            stored_visual_mode: None,
 256            change_list: Vec::new(),
 257            change_list_position: None,
 258            current_tx: None,
 259            current_anchor: None,
 260            undo_modes: HashMap::default(),
 261
 262            selected_register: None,
 263            search: SearchState::default(),
 264
 265            editor: editor.downgrade(),
 266            _subscriptions: vec![
 267                cx.observe_keystrokes(Self::observe_keystrokes),
 268                cx.subscribe(&editor, |this, _, event, cx| {
 269                    this.handle_editor_event(event, cx)
 270                }),
 271            ],
 272        })
 273    }
 274
 275    fn register(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
 276        if !editor.use_modal_editing() {
 277            return;
 278        }
 279
 280        let mut was_enabled = Vim::enabled(cx);
 281        let mut was_toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;
 282        cx.observe_global::<SettingsStore>(move |editor, cx| {
 283            let enabled = Vim::enabled(cx);
 284            let toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;
 285            if enabled && was_enabled && (toggle != was_toggle) {
 286                if toggle {
 287                    let is_relative = editor
 288                        .addon::<VimAddon>()
 289                        .map(|vim| vim.view.read(cx).mode != Mode::Insert);
 290                    editor.set_relative_line_number(is_relative, cx)
 291                } else {
 292                    editor.set_relative_line_number(None, cx)
 293                }
 294            }
 295            was_toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;
 296            if was_enabled == enabled {
 297                return;
 298            }
 299            was_enabled = enabled;
 300            if enabled {
 301                Self::activate(editor, cx)
 302            } else {
 303                Self::deactivate(editor, cx)
 304            }
 305        })
 306        .detach();
 307        if was_enabled {
 308            Self::activate(editor, cx)
 309        }
 310    }
 311
 312    fn activate(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
 313        let vim = Vim::new(cx);
 314
 315        editor.register_addon(VimAddon { view: vim.clone() });
 316
 317        vim.update(cx, |_, cx| {
 318            Vim::action(editor, cx, |vim, action: &SwitchMode, cx| {
 319                vim.switch_mode(action.0, false, cx)
 320            });
 321
 322            Vim::action(editor, cx, |vim, action: &PushOperator, cx| {
 323                vim.push_operator(action.0.clone(), cx)
 324            });
 325
 326            Vim::action(editor, cx, |vim, _: &ClearOperators, cx| {
 327                vim.clear_operator(cx)
 328            });
 329            Vim::action(editor, cx, |vim, n: &Number, cx| {
 330                vim.push_count_digit(n.0, cx);
 331            });
 332            Vim::action(editor, cx, |vim, _: &Tab, cx| {
 333                vim.input_ignored(" ".into(), cx)
 334            });
 335            Vim::action(editor, cx, |vim, _: &Enter, cx| {
 336                vim.input_ignored("\n".into(), cx)
 337            });
 338
 339            normal::register(editor, cx);
 340            insert::register(editor, cx);
 341            helix::register(editor, cx);
 342            motion::register(editor, cx);
 343            command::register(editor, cx);
 344            replace::register(editor, cx);
 345            indent::register(editor, cx);
 346            rewrap::register(editor, cx);
 347            object::register(editor, cx);
 348            visual::register(editor, cx);
 349            change_list::register(editor, cx);
 350            digraph::register(editor, cx);
 351
 352            cx.defer(|vim, cx| {
 353                vim.focused(false, cx);
 354            })
 355        })
 356    }
 357
 358    fn deactivate(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
 359        editor.set_cursor_shape(CursorShape::Bar, cx);
 360        editor.set_clip_at_line_ends(false, cx);
 361        editor.set_collapse_matches(false);
 362        editor.set_input_enabled(true);
 363        editor.set_autoindent(true);
 364        editor.selections.line_mode = false;
 365        editor.unregister_addon::<VimAddon>();
 366        editor.set_relative_line_number(None, cx);
 367        if let Some(vim) = Vim::globals(cx).focused_vim() {
 368            if vim.entity_id() == cx.view().entity_id() {
 369                Vim::globals(cx).focused_vim = None;
 370            }
 371        }
 372    }
 373
 374    /// Register an action on the editor.
 375    pub fn action<A: Action>(
 376        editor: &mut Editor,
 377        cx: &mut ViewContext<Vim>,
 378        f: impl Fn(&mut Vim, &A, &mut ViewContext<Vim>) + 'static,
 379    ) {
 380        let subscription = editor.register_action(cx.listener(f));
 381        cx.on_release(|_, _, _| drop(subscription)).detach();
 382    }
 383
 384    pub fn editor(&self) -> Option<View<Editor>> {
 385        self.editor.upgrade()
 386    }
 387
 388    pub fn workspace(&self, cx: &mut ViewContext<Self>) -> Option<View<Workspace>> {
 389        cx.window_handle()
 390            .downcast::<Workspace>()
 391            .and_then(|handle| handle.root(cx).ok())
 392    }
 393
 394    pub fn pane(&self, cx: &mut ViewContext<Self>) -> Option<View<Pane>> {
 395        self.workspace(cx)
 396            .map(|workspace| workspace.read(cx).focused_pane(cx))
 397    }
 398
 399    pub fn enabled(cx: &mut AppContext) -> bool {
 400        VimModeSetting::get_global(cx).0
 401    }
 402
 403    /// Called whenever an keystroke is typed so vim can observe all actions
 404    /// and keystrokes accordingly.
 405    fn observe_keystrokes(&mut self, keystroke_event: &KeystrokeEvent, cx: &mut ViewContext<Self>) {
 406        if self.exit_temporary_mode {
 407            self.exit_temporary_mode = false;
 408            // Don't switch to insert mode if the action is temporary_normal.
 409            if let Some(action) = keystroke_event.action.as_ref() {
 410                if action.as_any().downcast_ref::<TemporaryNormal>().is_some() {
 411                    return;
 412                }
 413            }
 414            self.switch_mode(Mode::Insert, false, cx)
 415        }
 416        if let Some(action) = keystroke_event.action.as_ref() {
 417            // Keystroke is handled by the vim system, so continue forward
 418            if action.name().starts_with("vim::") {
 419                return;
 420            }
 421        } else if cx.has_pending_keystrokes() || keystroke_event.keystroke.is_ime_in_progress() {
 422            return;
 423        }
 424
 425        if let Some(operator) = self.active_operator() {
 426            match operator {
 427                Operator::Literal { prefix } => {
 428                    self.handle_literal_keystroke(keystroke_event, prefix.unwrap_or_default(), cx);
 429                }
 430                _ if !operator.is_waiting(self.mode) => {
 431                    self.clear_operator(cx);
 432                    self.stop_recording_immediately(Box::new(ClearOperators), cx)
 433                }
 434                _ => {}
 435            }
 436        }
 437    }
 438
 439    fn handle_editor_event(&mut self, event: &EditorEvent, cx: &mut ViewContext<Self>) {
 440        match event {
 441            EditorEvent::Focused => self.focused(true, cx),
 442            EditorEvent::Blurred => self.blurred(cx),
 443            EditorEvent::SelectionsChanged { local: true } => {
 444                self.local_selections_changed(cx);
 445            }
 446            EditorEvent::InputIgnored { text } => {
 447                self.input_ignored(text.clone(), cx);
 448                Vim::globals(cx).observe_insertion(text, None)
 449            }
 450            EditorEvent::InputHandled {
 451                text,
 452                utf16_range_to_replace: range_to_replace,
 453            } => Vim::globals(cx).observe_insertion(text, range_to_replace.clone()),
 454            EditorEvent::TransactionBegun { transaction_id } => {
 455                self.transaction_begun(*transaction_id, cx)
 456            }
 457            EditorEvent::TransactionUndone { transaction_id } => {
 458                self.transaction_undone(transaction_id, cx)
 459            }
 460            EditorEvent::Edited { .. } => self.push_to_change_list(cx),
 461            EditorEvent::FocusedIn => self.sync_vim_settings(cx),
 462            EditorEvent::CursorShapeChanged => self.cursor_shape_changed(cx),
 463            _ => {}
 464        }
 465    }
 466
 467    fn push_operator(&mut self, operator: Operator, cx: &mut ViewContext<Self>) {
 468        if matches!(
 469            operator,
 470            Operator::Change
 471                | Operator::Delete
 472                | Operator::Replace
 473                | Operator::Indent
 474                | Operator::Outdent
 475                | Operator::AutoIndent
 476                | Operator::Lowercase
 477                | Operator::Uppercase
 478                | Operator::OppositeCase
 479                | Operator::ToggleComments
 480        ) {
 481            self.start_recording(cx)
 482        };
 483        // Since these operations can only be entered with pre-operators,
 484        // we need to clear the previous operators when pushing,
 485        // so that the current stack is the most correct
 486        if matches!(
 487            operator,
 488            Operator::AddSurrounds { .. }
 489                | Operator::ChangeSurrounds { .. }
 490                | Operator::DeleteSurrounds
 491        ) {
 492            self.operator_stack.clear();
 493            if let Operator::AddSurrounds { target: None } = operator {
 494                self.start_recording(cx);
 495            }
 496        };
 497        self.operator_stack.push(operator);
 498        self.sync_vim_settings(cx);
 499    }
 500
 501    pub fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut ViewContext<Self>) {
 502        if self.temp_mode && mode == Mode::Normal {
 503            self.temp_mode = false;
 504            self.switch_mode(Mode::Normal, leave_selections, cx);
 505            self.switch_mode(Mode::Insert, false, cx);
 506            return;
 507        } else if self.temp_mode
 508            && !matches!(mode, Mode::Visual | Mode::VisualLine | Mode::VisualBlock)
 509        {
 510            self.temp_mode = false;
 511        }
 512
 513        let last_mode = self.mode;
 514        let prior_mode = self.last_mode;
 515        let prior_tx = self.current_tx;
 516        self.last_mode = last_mode;
 517        self.mode = mode;
 518        self.operator_stack.clear();
 519        self.selected_register.take();
 520        if mode == Mode::Normal || mode != last_mode {
 521            self.current_tx.take();
 522            self.current_anchor.take();
 523        }
 524        if mode != Mode::Insert && mode != Mode::Replace {
 525            Vim::take_count(cx);
 526        }
 527
 528        // Sync editor settings like clip mode
 529        self.sync_vim_settings(cx);
 530
 531        if VimSettings::get_global(cx).toggle_relative_line_numbers
 532            && self.mode != self.last_mode
 533            && (self.mode == Mode::Insert || self.last_mode == Mode::Insert)
 534        {
 535            self.update_editor(cx, |vim, editor, cx| {
 536                let is_relative = vim.mode != Mode::Insert;
 537                editor.set_relative_line_number(Some(is_relative), cx)
 538            });
 539        }
 540
 541        if leave_selections {
 542            return;
 543        }
 544
 545        if !mode.is_visual() && last_mode.is_visual() {
 546            self.create_visual_marks(last_mode, cx);
 547        }
 548
 549        // Adjust selections
 550        self.update_editor(cx, |vim, editor, cx| {
 551            if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
 552            {
 553                vim.visual_block_motion(true, editor, cx, |_, point, goal| Some((point, goal)))
 554            }
 555            if last_mode == Mode::Insert || last_mode == Mode::Replace {
 556                if let Some(prior_tx) = prior_tx {
 557                    editor.group_until_transaction(prior_tx, cx)
 558                }
 559            }
 560
 561            editor.change_selections(None, cx, |s| {
 562                // we cheat with visual block mode and use multiple cursors.
 563                // the cost of this cheat is we need to convert back to a single
 564                // cursor whenever vim would.
 565                if last_mode == Mode::VisualBlock
 566                    && (mode != Mode::VisualBlock && mode != Mode::Insert)
 567                {
 568                    let tail = s.oldest_anchor().tail();
 569                    let head = s.newest_anchor().head();
 570                    s.select_anchor_ranges(vec![tail..head]);
 571                } else if last_mode == Mode::Insert
 572                    && prior_mode == Mode::VisualBlock
 573                    && mode != Mode::VisualBlock
 574                {
 575                    let pos = s.first_anchor().head();
 576                    s.select_anchor_ranges(vec![pos..pos])
 577                }
 578
 579                let snapshot = s.display_map();
 580                if let Some(pending) = s.pending.as_mut() {
 581                    if pending.selection.reversed && mode.is_visual() && !last_mode.is_visual() {
 582                        let mut end = pending.selection.end.to_point(&snapshot.buffer_snapshot);
 583                        end = snapshot
 584                            .buffer_snapshot
 585                            .clip_point(end + Point::new(0, 1), Bias::Right);
 586                        pending.selection.end = snapshot.buffer_snapshot.anchor_before(end);
 587                    }
 588                }
 589
 590                s.move_with(|map, selection| {
 591                    if last_mode.is_visual() && !mode.is_visual() {
 592                        let mut point = selection.head();
 593                        if !selection.reversed && !selection.is_empty() {
 594                            point = movement::left(map, selection.head());
 595                        }
 596                        selection.collapse_to(point, selection.goal)
 597                    } else if !last_mode.is_visual() && mode.is_visual() && selection.is_empty() {
 598                        selection.end = movement::right(map, selection.start);
 599                    }
 600                });
 601            })
 602        });
 603    }
 604
 605    pub fn take_count(cx: &mut AppContext) -> Option<usize> {
 606        let global_state = cx.global_mut::<VimGlobals>();
 607        if global_state.dot_replaying {
 608            return global_state.recorded_count;
 609        }
 610
 611        let count = if global_state.post_count.is_none() && global_state.pre_count.is_none() {
 612            return None;
 613        } else {
 614            Some(
 615                global_state.post_count.take().unwrap_or(1)
 616                    * global_state.pre_count.take().unwrap_or(1),
 617            )
 618        };
 619
 620        if global_state.dot_recording {
 621            global_state.recorded_count = count;
 622        }
 623        count
 624    }
 625
 626    pub fn cursor_shape(&self) -> CursorShape {
 627        match self.mode {
 628            Mode::Normal => {
 629                if self.operator_stack.is_empty() {
 630                    CursorShape::Block
 631                } else {
 632                    CursorShape::Underline
 633                }
 634            }
 635            Mode::Replace => CursorShape::Underline,
 636            Mode::HelixNormal | Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
 637                CursorShape::Block
 638            }
 639            Mode::Insert => CursorShape::Bar,
 640        }
 641    }
 642
 643    pub fn editor_input_enabled(&self) -> bool {
 644        match self.mode {
 645            Mode::Insert => {
 646                if let Some(operator) = self.operator_stack.last() {
 647                    !operator.is_waiting(self.mode)
 648                } else {
 649                    true
 650                }
 651            }
 652            Mode::Normal
 653            | Mode::HelixNormal
 654            | Mode::Replace
 655            | Mode::Visual
 656            | Mode::VisualLine
 657            | Mode::VisualBlock => false,
 658        }
 659    }
 660
 661    pub fn should_autoindent(&self) -> bool {
 662        !(self.mode == Mode::Insert && self.last_mode == Mode::VisualBlock)
 663    }
 664
 665    pub fn clip_at_line_ends(&self) -> bool {
 666        match self.mode {
 667            Mode::Insert
 668            | Mode::Visual
 669            | Mode::VisualLine
 670            | Mode::VisualBlock
 671            | Mode::Replace
 672            | Mode::HelixNormal => false,
 673            Mode::Normal => true,
 674        }
 675    }
 676
 677    pub fn extend_key_context(&self, context: &mut KeyContext, cx: &AppContext) {
 678        let mut mode = match self.mode {
 679            Mode::Normal => "normal",
 680            Mode::Visual | Mode::VisualLine | Mode::VisualBlock => "visual",
 681            Mode::Insert => "insert",
 682            Mode::Replace => "replace",
 683            Mode::HelixNormal => "helix_normal",
 684        }
 685        .to_string();
 686
 687        let mut operator_id = "none";
 688
 689        let active_operator = self.active_operator();
 690        if active_operator.is_none() && cx.global::<VimGlobals>().pre_count.is_some()
 691            || active_operator.is_some() && cx.global::<VimGlobals>().post_count.is_some()
 692        {
 693            context.add("VimCount");
 694        }
 695
 696        if let Some(active_operator) = active_operator {
 697            if active_operator.is_waiting(self.mode) {
 698                if matches!(active_operator, Operator::Literal { .. }) {
 699                    mode = "literal".to_string();
 700                } else {
 701                    mode = "waiting".to_string();
 702                }
 703            } else {
 704                operator_id = active_operator.id();
 705                mode = "operator".to_string();
 706            }
 707        }
 708
 709        if mode == "normal" || mode == "visual" || mode == "operator" {
 710            context.add("VimControl");
 711        }
 712        context.set("vim_mode", mode);
 713        context.set("vim_operator", operator_id);
 714    }
 715
 716    fn focused(&mut self, preserve_selection: bool, cx: &mut ViewContext<Self>) {
 717        let Some(editor) = self.editor() else {
 718            return;
 719        };
 720        let newest_selection_empty = editor.update(cx, |editor, cx| {
 721            editor.selections.newest::<usize>(cx).is_empty()
 722        });
 723        let editor = editor.read(cx);
 724        let editor_mode = editor.mode();
 725
 726        if editor_mode == EditorMode::Full
 727                && !newest_selection_empty
 728                && self.mode == Mode::Normal
 729                // When following someone, don't switch vim mode.
 730                && editor.leader_peer_id().is_none()
 731        {
 732            if preserve_selection {
 733                self.switch_mode(Mode::Visual, true, cx);
 734            } else {
 735                self.update_editor(cx, |_, editor, cx| {
 736                    editor.set_clip_at_line_ends(false, cx);
 737                    editor.change_selections(None, cx, |s| {
 738                        s.move_with(|_, selection| {
 739                            selection.collapse_to(selection.start, selection.goal)
 740                        })
 741                    });
 742                });
 743            }
 744        }
 745
 746        cx.emit(VimEvent::Focused);
 747        self.sync_vim_settings(cx);
 748
 749        if VimSettings::get_global(cx).toggle_relative_line_numbers {
 750            if let Some(old_vim) = Vim::globals(cx).focused_vim() {
 751                if old_vim.entity_id() != cx.view().entity_id() {
 752                    old_vim.update(cx, |vim, cx| {
 753                        vim.update_editor(cx, |_, editor, cx| {
 754                            editor.set_relative_line_number(None, cx)
 755                        });
 756                    });
 757
 758                    self.update_editor(cx, |vim, editor, cx| {
 759                        let is_relative = vim.mode != Mode::Insert;
 760                        editor.set_relative_line_number(Some(is_relative), cx)
 761                    });
 762                }
 763            } else {
 764                self.update_editor(cx, |vim, editor, cx| {
 765                    let is_relative = vim.mode != Mode::Insert;
 766                    editor.set_relative_line_number(Some(is_relative), cx)
 767                });
 768            }
 769        }
 770        Vim::globals(cx).focused_vim = Some(cx.view().downgrade());
 771    }
 772
 773    fn blurred(&mut self, cx: &mut ViewContext<Self>) {
 774        self.stop_recording_immediately(NormalBefore.boxed_clone(), cx);
 775        self.store_visual_marks(cx);
 776        self.clear_operator(cx);
 777        self.update_editor(cx, |_, editor, cx| {
 778            editor.set_cursor_shape(language::CursorShape::Hollow, cx);
 779        });
 780    }
 781
 782    fn cursor_shape_changed(&mut self, cx: &mut ViewContext<Self>) {
 783        self.update_editor(cx, |vim, editor, cx| {
 784            editor.set_cursor_shape(vim.cursor_shape(), cx);
 785        });
 786    }
 787
 788    fn update_editor<S>(
 789        &mut self,
 790        cx: &mut ViewContext<Self>,
 791        update: impl FnOnce(&mut Self, &mut Editor, &mut ViewContext<Editor>) -> S,
 792    ) -> Option<S> {
 793        let editor = self.editor.upgrade()?;
 794        Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
 795    }
 796
 797    fn editor_selections(&mut self, cx: &mut ViewContext<Self>) -> Vec<Range<Anchor>> {
 798        self.update_editor(cx, |_, editor, _| {
 799            editor
 800                .selections
 801                .disjoint_anchors()
 802                .iter()
 803                .map(|selection| selection.tail()..selection.head())
 804                .collect()
 805        })
 806        .unwrap_or_default()
 807    }
 808
 809    /// When doing an action that modifies the buffer, we start recording so that `.`
 810    /// will replay the action.
 811    pub fn start_recording(&mut self, cx: &mut ViewContext<Self>) {
 812        Vim::update_globals(cx, |globals, cx| {
 813            if !globals.dot_replaying {
 814                globals.dot_recording = true;
 815                globals.recording_actions = Default::default();
 816                globals.recorded_count = None;
 817
 818                let selections = self.editor().map(|editor| {
 819                    editor.update(cx, |editor, cx| {
 820                        (
 821                            editor.selections.oldest::<Point>(cx),
 822                            editor.selections.newest::<Point>(cx),
 823                        )
 824                    })
 825                });
 826
 827                if let Some((oldest, newest)) = selections {
 828                    globals.recorded_selection = match self.mode {
 829                        Mode::Visual if newest.end.row == newest.start.row => {
 830                            RecordedSelection::SingleLine {
 831                                cols: newest.end.column - newest.start.column,
 832                            }
 833                        }
 834                        Mode::Visual => RecordedSelection::Visual {
 835                            rows: newest.end.row - newest.start.row,
 836                            cols: newest.end.column,
 837                        },
 838                        Mode::VisualLine => RecordedSelection::VisualLine {
 839                            rows: newest.end.row - newest.start.row,
 840                        },
 841                        Mode::VisualBlock => RecordedSelection::VisualBlock {
 842                            rows: newest.end.row.abs_diff(oldest.start.row),
 843                            cols: newest.end.column.abs_diff(oldest.start.column),
 844                        },
 845                        _ => RecordedSelection::None,
 846                    }
 847                } else {
 848                    globals.recorded_selection = RecordedSelection::None;
 849                }
 850            }
 851        })
 852    }
 853
 854    pub fn stop_replaying(&mut self, cx: &mut ViewContext<Self>) {
 855        let globals = Vim::globals(cx);
 856        globals.dot_replaying = false;
 857        if let Some(replayer) = globals.replayer.take() {
 858            replayer.stop();
 859        }
 860    }
 861
 862    /// When finishing an action that modifies the buffer, stop recording.
 863    /// as you usually call this within a keystroke handler we also ensure that
 864    /// the current action is recorded.
 865    pub fn stop_recording(&mut self, cx: &mut ViewContext<Self>) {
 866        let globals = Vim::globals(cx);
 867        if globals.dot_recording {
 868            globals.stop_recording_after_next_action = true;
 869        }
 870        self.exit_temporary_mode = self.temp_mode;
 871    }
 872
 873    /// Stops recording actions immediately rather than waiting until after the
 874    /// next action to stop recording.
 875    ///
 876    /// This doesn't include the current action.
 877    pub fn stop_recording_immediately(
 878        &mut self,
 879        action: Box<dyn Action>,
 880        cx: &mut ViewContext<Self>,
 881    ) {
 882        let globals = Vim::globals(cx);
 883        if globals.dot_recording {
 884            globals
 885                .recording_actions
 886                .push(ReplayableAction::Action(action.boxed_clone()));
 887            globals.recorded_actions = mem::take(&mut globals.recording_actions);
 888            globals.dot_recording = false;
 889            globals.stop_recording_after_next_action = false;
 890        }
 891        self.exit_temporary_mode = self.temp_mode;
 892    }
 893
 894    /// Explicitly record one action (equivalents to start_recording and stop_recording)
 895    pub fn record_current_action(&mut self, cx: &mut ViewContext<Self>) {
 896        self.start_recording(cx);
 897        self.stop_recording(cx);
 898    }
 899
 900    fn push_count_digit(&mut self, number: usize, cx: &mut ViewContext<Self>) {
 901        if self.active_operator().is_some() {
 902            let post_count = Vim::globals(cx).post_count.unwrap_or(0);
 903
 904            Vim::globals(cx).post_count = Some(
 905                post_count
 906                    .checked_mul(10)
 907                    .and_then(|post_count| post_count.checked_add(number))
 908                    .unwrap_or(post_count),
 909            )
 910        } else {
 911            let pre_count = Vim::globals(cx).pre_count.unwrap_or(0);
 912
 913            Vim::globals(cx).pre_count = Some(
 914                pre_count
 915                    .checked_mul(10)
 916                    .and_then(|pre_count| pre_count.checked_add(number))
 917                    .unwrap_or(pre_count),
 918            )
 919        }
 920        // update the keymap so that 0 works
 921        self.sync_vim_settings(cx)
 922    }
 923
 924    fn select_register(&mut self, register: Arc<str>, cx: &mut ViewContext<Self>) {
 925        if register.chars().count() == 1 {
 926            self.selected_register
 927                .replace(register.chars().next().unwrap());
 928        }
 929        self.operator_stack.clear();
 930        self.sync_vim_settings(cx);
 931    }
 932
 933    fn maybe_pop_operator(&mut self) -> Option<Operator> {
 934        self.operator_stack.pop()
 935    }
 936
 937    fn pop_operator(&mut self, cx: &mut ViewContext<Self>) -> Operator {
 938        let popped_operator = self.operator_stack.pop()
 939            .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
 940        self.sync_vim_settings(cx);
 941        popped_operator
 942    }
 943
 944    fn clear_operator(&mut self, cx: &mut ViewContext<Self>) {
 945        Vim::take_count(cx);
 946        self.selected_register.take();
 947        self.operator_stack.clear();
 948        self.sync_vim_settings(cx);
 949    }
 950
 951    fn active_operator(&self) -> Option<Operator> {
 952        self.operator_stack.last().cloned()
 953    }
 954
 955    fn transaction_begun(&mut self, transaction_id: TransactionId, _: &mut ViewContext<Self>) {
 956        let mode = if (self.mode == Mode::Insert
 957            || self.mode == Mode::Replace
 958            || self.mode == Mode::Normal)
 959            && self.current_tx.is_none()
 960        {
 961            self.current_tx = Some(transaction_id);
 962            self.last_mode
 963        } else {
 964            self.mode
 965        };
 966        if mode == Mode::VisualLine || mode == Mode::VisualBlock {
 967            self.undo_modes.insert(transaction_id, mode);
 968        }
 969    }
 970
 971    fn transaction_undone(&mut self, transaction_id: &TransactionId, cx: &mut ViewContext<Self>) {
 972        match self.mode {
 973            Mode::VisualLine | Mode::VisualBlock | Mode::Visual => {
 974                self.update_editor(cx, |vim, editor, cx| {
 975                    let original_mode = vim.undo_modes.get(transaction_id);
 976                    editor.change_selections(None, cx, |s| match original_mode {
 977                        Some(Mode::VisualLine) => {
 978                            s.move_with(|map, selection| {
 979                                selection.collapse_to(
 980                                    map.prev_line_boundary(selection.start.to_point(map)).1,
 981                                    SelectionGoal::None,
 982                                )
 983                            });
 984                        }
 985                        Some(Mode::VisualBlock) => {
 986                            let mut first = s.first_anchor();
 987                            first.collapse_to(first.start, first.goal);
 988                            s.select_anchors(vec![first]);
 989                        }
 990                        _ => {
 991                            s.move_with(|map, selection| {
 992                                selection.collapse_to(
 993                                    map.clip_at_line_end(selection.start),
 994                                    selection.goal,
 995                                );
 996                            });
 997                        }
 998                    });
 999                });
1000                self.switch_mode(Mode::Normal, true, cx)
1001            }
1002            Mode::Normal => {
1003                self.update_editor(cx, |_, editor, cx| {
1004                    editor.change_selections(None, cx, |s| {
1005                        s.move_with(|map, selection| {
1006                            selection
1007                                .collapse_to(map.clip_at_line_end(selection.end), selection.goal)
1008                        })
1009                    })
1010                });
1011            }
1012            Mode::Insert | Mode::Replace | Mode::HelixNormal => {}
1013        }
1014    }
1015
1016    fn local_selections_changed(&mut self, cx: &mut ViewContext<Self>) {
1017        let Some(editor) = self.editor() else { return };
1018
1019        if editor.read(cx).leader_peer_id().is_some() {
1020            return;
1021        }
1022
1023        let newest = editor.read(cx).selections.newest_anchor().clone();
1024        let is_multicursor = editor.read(cx).selections.count() > 1;
1025        if self.mode == Mode::Insert && self.current_tx.is_some() {
1026            if self.current_anchor.is_none() {
1027                self.current_anchor = Some(newest);
1028            } else if self.current_anchor.as_ref().unwrap() != &newest {
1029                if let Some(tx_id) = self.current_tx.take() {
1030                    self.update_editor(cx, |_, editor, cx| {
1031                        editor.group_until_transaction(tx_id, cx)
1032                    });
1033                }
1034            }
1035        } else if self.mode == Mode::Normal && newest.start != newest.end {
1036            if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
1037                self.switch_mode(Mode::VisualBlock, false, cx);
1038            } else {
1039                self.switch_mode(Mode::Visual, false, cx)
1040            }
1041        } else if newest.start == newest.end
1042            && !is_multicursor
1043            && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&self.mode)
1044        {
1045            self.switch_mode(Mode::Normal, true, cx);
1046        }
1047    }
1048
1049    fn input_ignored(&mut self, text: Arc<str>, cx: &mut ViewContext<Self>) {
1050        if text.is_empty() {
1051            return;
1052        }
1053
1054        match self.active_operator() {
1055            Some(Operator::FindForward { before }) => {
1056                let find = Motion::FindForward {
1057                    before,
1058                    char: text.chars().next().unwrap(),
1059                    mode: if VimSettings::get_global(cx).use_multiline_find {
1060                        FindRange::MultiLine
1061                    } else {
1062                        FindRange::SingleLine
1063                    },
1064                    smartcase: VimSettings::get_global(cx).use_smartcase_find,
1065                };
1066                Vim::globals(cx).last_find = Some(find.clone());
1067                self.motion(find, cx)
1068            }
1069            Some(Operator::FindBackward { after }) => {
1070                let find = Motion::FindBackward {
1071                    after,
1072                    char: text.chars().next().unwrap(),
1073                    mode: if VimSettings::get_global(cx).use_multiline_find {
1074                        FindRange::MultiLine
1075                    } else {
1076                        FindRange::SingleLine
1077                    },
1078                    smartcase: VimSettings::get_global(cx).use_smartcase_find,
1079                };
1080                Vim::globals(cx).last_find = Some(find.clone());
1081                self.motion(find, cx)
1082            }
1083            Some(Operator::Replace) => match self.mode {
1084                Mode::Normal => self.normal_replace(text, cx),
1085                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1086                    self.visual_replace(text, cx)
1087                }
1088                _ => self.clear_operator(cx),
1089            },
1090            Some(Operator::Digraph { first_char }) => {
1091                if let Some(first_char) = first_char {
1092                    if let Some(second_char) = text.chars().next() {
1093                        self.insert_digraph(first_char, second_char, cx);
1094                    }
1095                } else {
1096                    let first_char = text.chars().next();
1097                    self.pop_operator(cx);
1098                    self.push_operator(Operator::Digraph { first_char }, cx);
1099                }
1100            }
1101            Some(Operator::Literal { prefix }) => {
1102                self.handle_literal_input(prefix.unwrap_or_default(), &text, cx)
1103            }
1104            Some(Operator::AddSurrounds { target }) => match self.mode {
1105                Mode::Normal => {
1106                    if let Some(target) = target {
1107                        self.add_surrounds(text, target, cx);
1108                        self.clear_operator(cx);
1109                    }
1110                }
1111                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1112                    self.add_surrounds(text, SurroundsType::Selection, cx);
1113                    self.clear_operator(cx);
1114                }
1115                _ => self.clear_operator(cx),
1116            },
1117            Some(Operator::ChangeSurrounds { target }) => match self.mode {
1118                Mode::Normal => {
1119                    if let Some(target) = target {
1120                        self.change_surrounds(text, target, cx);
1121                        self.clear_operator(cx);
1122                    }
1123                }
1124                _ => self.clear_operator(cx),
1125            },
1126            Some(Operator::DeleteSurrounds) => match self.mode {
1127                Mode::Normal => {
1128                    self.delete_surrounds(text, cx);
1129                    self.clear_operator(cx);
1130                }
1131                _ => self.clear_operator(cx),
1132            },
1133            Some(Operator::Mark) => self.create_mark(text, false, cx),
1134            Some(Operator::RecordRegister) => {
1135                self.record_register(text.chars().next().unwrap(), cx)
1136            }
1137            Some(Operator::ReplayRegister) => {
1138                self.replay_register(text.chars().next().unwrap(), cx)
1139            }
1140            Some(Operator::Register) => match self.mode {
1141                Mode::Insert => {
1142                    self.update_editor(cx, |_, editor, cx| {
1143                        if let Some(register) = Vim::update_globals(cx, |globals, cx| {
1144                            globals.read_register(text.chars().next(), Some(editor), cx)
1145                        }) {
1146                            editor.do_paste(
1147                                &register.text.to_string(),
1148                                register.clipboard_selections.clone(),
1149                                false,
1150                                cx,
1151                            )
1152                        }
1153                    });
1154                    self.clear_operator(cx);
1155                }
1156                _ => {
1157                    self.select_register(text, cx);
1158                }
1159            },
1160            Some(Operator::Jump { line }) => self.jump(text, line, cx),
1161            _ => {
1162                if self.mode == Mode::Replace {
1163                    self.multi_replace(text, cx)
1164                }
1165            }
1166        }
1167    }
1168
1169    fn sync_vim_settings(&mut self, cx: &mut ViewContext<Self>) {
1170        self.update_editor(cx, |vim, editor, cx| {
1171            editor.set_cursor_shape(vim.cursor_shape(), cx);
1172            editor.set_clip_at_line_ends(vim.clip_at_line_ends(), cx);
1173            editor.set_collapse_matches(true);
1174            editor.set_input_enabled(vim.editor_input_enabled());
1175            editor.set_autoindent(vim.should_autoindent());
1176            editor.selections.line_mode = matches!(vim.mode, Mode::VisualLine);
1177            editor.set_inline_completions_enabled(matches!(vim.mode, Mode::Insert | Mode::Replace));
1178        });
1179        cx.notify()
1180    }
1181}
1182
1183/// Controls when to use system clipboard.
1184#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
1185#[serde(rename_all = "snake_case")]
1186pub enum UseSystemClipboard {
1187    /// Don't use system clipboard.
1188    Never,
1189    /// Use system clipboard.
1190    Always,
1191    /// Use system clipboard for yank operations.
1192    OnYank,
1193}
1194
1195#[derive(Deserialize)]
1196struct VimSettings {
1197    pub toggle_relative_line_numbers: bool,
1198    pub use_system_clipboard: UseSystemClipboard,
1199    pub use_multiline_find: bool,
1200    pub use_smartcase_find: bool,
1201    pub custom_digraphs: HashMap<String, Arc<str>>,
1202}
1203
1204#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
1205struct VimSettingsContent {
1206    pub toggle_relative_line_numbers: Option<bool>,
1207    pub use_system_clipboard: Option<UseSystemClipboard>,
1208    pub use_multiline_find: Option<bool>,
1209    pub use_smartcase_find: Option<bool>,
1210    pub custom_digraphs: Option<HashMap<String, Arc<str>>>,
1211}
1212
1213impl Settings for VimSettings {
1214    const KEY: Option<&'static str> = Some("vim");
1215
1216    type FileContent = VimSettingsContent;
1217
1218    fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1219        sources.json_merge()
1220    }
1221}