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