vim.rs

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