vim.rs

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