vim.rs

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