1118 lines · 39.9 KB · Rust
RawDownload
//! Vim support for Zed. #[cfg(test)]mod test; mod change_list;mod command;mod digraph;mod insert;mod mode_indicator;mod motion;mod normal;mod object;mod replace;mod state;mod surrounds;mod visual; use anyhow::Result;use collections::HashMap;use editor::{    movement::{self, FindRange},    Anchor, Bias, Editor, EditorEvent, EditorMode, ToPoint,};use gpui::{    actions, impl_actions, Action, AppContext, Entity, EventEmitter, KeyContext, KeystrokeEvent,    Render, View, ViewContext, WeakView,};use insert::NormalBefore;use language::{CursorShape, Point, Selection, SelectionGoal, TransactionId};pub use mode_indicator::ModeIndicator;use motion::Motion;use normal::search::SearchSubmit;use schemars::JsonSchema;use serde::Deserialize;use serde_derive::Serialize;use settings::{update_settings_file, Settings, SettingsSources, SettingsStore};use state::{Mode, Operator, RecordedSelection, SearchState, VimGlobals};use std::{ops::Range, sync::Arc};use surrounds::SurroundsType;use ui::{IntoElement, VisualContext};use workspace::{self, Pane, Workspace}; use crate::state::ReplayableAction; /// Whether or not to enable Vim mode.////// Default: falsepub struct VimModeSetting(pub bool); /// An Action to Switch between modes#[derive(Clone, Deserialize, PartialEq)]pub struct SwitchMode(pub Mode); /// PushOperator is used to put vim into a "minor" mode,/// where it's waiting for a specific next set of keystrokes./// For example 'd' needs a motion to complete.#[derive(Clone, Deserialize, PartialEq)]pub struct PushOperator(pub Operator); /// Number is used to manage vim's count. Pushing a digit/// multiplis the current value by 10 and adds the digit.#[derive(Clone, Deserialize, PartialEq)]struct Number(usize); #[derive(Clone, Deserialize, PartialEq)]struct SelectRegister(String); actions!(    vim,    [        ClearOperators,        Tab,        Enter,        Object,        InnerObject,        FindForward,        FindBackward,        OpenDefaultKeymap    ]); // in the workspace namespace so it's not filtered out when vim is disabled.actions!(workspace, [ToggleVimMode]); impl_actions!(vim, [SwitchMode, PushOperator, Number, SelectRegister]); /// Initializes the `vim` crate.pub fn init(cx: &mut AppContext) {    VimModeSetting::register(cx);    VimSettings::register(cx);    VimGlobals::register(cx);     cx.observe_new_views(|editor: &mut Editor, cx| Vim::register(editor, cx))        .detach();     cx.observe_new_views(|workspace: &mut Workspace, _| {        workspace.register_action(|workspace, _: &ToggleVimMode, cx| {            let fs = workspace.app_state().fs.clone();            let currently_enabled = Vim::enabled(cx);            update_settings_file::<VimModeSetting>(fs, cx, move |setting, _| {                *setting = Some(!currently_enabled)            })        });         workspace.register_action(|_, _: &OpenDefaultKeymap, cx| {            cx.emit(workspace::Event::OpenBundledFile {                text: settings::vim_keymap(),                title: "Default Vim Bindings",                language: "JSON",            });        });         workspace.register_action(|workspace, _: &SearchSubmit, cx| {            let Some(vim) = workspace                .active_item_as::<Editor>(cx)                .and_then(|editor| editor.read(cx).addon::<VimAddon>().cloned())            else {                return;            };            vim.view                .update(cx, |_, cx| cx.defer(|vim, cx| vim.search_submit(cx)))        });    })    .detach();} #[derive(Clone)]pub(crate) struct VimAddon {    pub(crate) view: View<Vim>,} impl editor::Addon for VimAddon {    fn extend_key_context(&self, key_context: &mut KeyContext, cx: &AppContext) {        self.view.read(cx).extend_key_context(key_context)    }     fn to_any(&self) -> &dyn std::any::Any {        self    }} /// The state pertaining to Vim mode.pub(crate) struct Vim {    pub(crate) mode: Mode,    pub last_mode: Mode,     /// pre_count is the number before an operator is specified (3 in 3d2d)    pre_count: Option<usize>,    /// post_count is the number after an operator is specified (2 in 3d2d)    post_count: Option<usize>,     operator_stack: Vec<Operator>,    pub(crate) replacements: Vec<(Range<editor::Anchor>, String)>,     pub(crate) marks: HashMap<String, Vec<Anchor>>,    pub(crate) stored_visual_mode: Option<(Mode, Vec<bool>)>,    pub(crate) change_list: Vec<Vec<Anchor>>,    pub(crate) change_list_position: Option<usize>,     pub(crate) current_tx: Option<TransactionId>,    pub(crate) current_anchor: Option<Selection<Anchor>>,    pub(crate) undo_modes: HashMap<TransactionId, Mode>,     selected_register: Option<char>,    pub search: SearchState,     editor: WeakView<Editor>,} // Hack: Vim intercepts events dispatched to a window and updates the view in response.// This means it needs a VisualContext. The easiest way to satisfy that constraint is// to make Vim a "View" that is just never actually rendered.impl Render for Vim {    fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {        gpui::Empty    }} enum VimEvent {    Focused,}impl EventEmitter<VimEvent> for Vim {} impl Vim {    /// The namespace for Vim actions.    const NAMESPACE: &'static str = "vim";     pub fn new(cx: &mut ViewContext<Editor>) -> View<Self> {        let editor = cx.view().clone();         cx.new_view(|cx: &mut ViewContext<Vim>| {            cx.subscribe(&editor, |vim, _, event, cx| {                vim.handle_editor_event(event, cx)            })            .detach();             let listener = cx.listener(Vim::observe_keystrokes);            cx.observe_keystrokes(listener).detach();             Vim {                mode: Mode::Normal,                last_mode: Mode::Normal,                pre_count: None,                post_count: None,                operator_stack: Vec::new(),                replacements: Vec::new(),                 marks: HashMap::default(),                stored_visual_mode: None,                change_list: Vec::new(),                change_list_position: None,                current_tx: None,                current_anchor: None,                undo_modes: HashMap::default(),                 selected_register: None,                search: SearchState::default(),                 editor: editor.downgrade(),            }        })    }     fn register(editor: &mut Editor, cx: &mut ViewContext<Editor>) {        if !editor.use_modal_editing() {            return;        }         let mut was_enabled = Vim::enabled(cx);        let mut was_toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;        cx.observe_global::<SettingsStore>(move |editor, cx| {            let enabled = Vim::enabled(cx);            let toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;            if enabled && was_enabled && (toggle != was_toggle) {                if toggle {                    let is_relative = editor                        .addon::<VimAddon>()                        .map(|vim| vim.view.read(cx).mode != Mode::Insert);                    editor.set_relative_line_number(is_relative, cx)                } else {                    editor.set_relative_line_number(None, cx)                }            }            was_toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;            if was_enabled == enabled {                return;            }            was_enabled = enabled;            if enabled {                Self::activate(editor, cx)            } else {                Self::deactivate(editor, cx)            }        })        .detach();        if was_enabled {            Self::activate(editor, cx)        }    }     fn activate(editor: &mut Editor, cx: &mut ViewContext<Editor>) {        let vim = Vim::new(cx);         editor.register_addon(VimAddon { view: vim.clone() });         vim.update(cx, |_, cx| {            Vim::action(editor, cx, |vim, action: &SwitchMode, cx| {                vim.switch_mode(action.0, false, cx)            });             Vim::action(editor, cx, |vim, action: &PushOperator, cx| {                vim.push_operator(action.0.clone(), cx)            });             Vim::action(editor, cx, |vim, _: &ClearOperators, cx| {                vim.clear_operator(cx)            });            Vim::action(editor, cx, |vim, n: &Number, cx| {                vim.push_count_digit(n.0, cx);            });            Vim::action(editor, cx, |vim, _: &Tab, cx| {                vim.input_ignored(" ".into(), cx)            });            Vim::action(editor, cx, |vim, _: &Enter, cx| {                vim.input_ignored("\n".into(), cx)            });             normal::register(editor, cx);            insert::register(editor, cx);            motion::register(editor, cx);            command::register(editor, cx);            replace::register(editor, cx);            object::register(editor, cx);            visual::register(editor, cx);            change_list::register(editor, cx);             cx.defer(|vim, cx| {                vim.focused(false, cx);            })        })    }     fn deactivate(editor: &mut Editor, cx: &mut ViewContext<Editor>) {        editor.set_cursor_shape(CursorShape::Bar, cx);        editor.set_clip_at_line_ends(false, cx);        editor.set_collapse_matches(false);        editor.set_input_enabled(true);        editor.set_autoindent(true);        editor.selections.line_mode = false;        editor.unregister_addon::<VimAddon>();        editor.set_relative_line_number(None, cx);        if let Some(vim) = Vim::globals(cx).focused_vim() {            if vim.entity_id() == cx.view().entity_id() {                Vim::globals(cx).focused_vim = None;            }        }    }     /// Register an action on the editor.    pub fn action<A: Action>(        editor: &mut Editor,        cx: &mut ViewContext<Vim>,        f: impl Fn(&mut Vim, &A, &mut ViewContext<Vim>) + 'static,    ) {        let subscription = editor.register_action(cx.listener(f));        cx.on_release(|_, _, _| drop(subscription)).detach();    }     pub fn editor(&self) -> Option<View<Editor>> {        self.editor.upgrade()    }     pub fn workspace(&self, cx: &ViewContext<Self>) -> Option<View<Workspace>> {        self.editor().and_then(|editor| editor.read(cx).workspace())    }     pub fn pane(&self, cx: &ViewContext<Self>) -> Option<View<Pane>> {        self.workspace(cx)            .and_then(|workspace| workspace.read(cx).pane_for(&self.editor()?))    }     pub fn enabled(cx: &mut AppContext) -> bool {        VimModeSetting::get_global(cx).0    }     /// Called whenever an keystroke is typed so vim can observe all actions    /// and keystrokes accordingly.    fn observe_keystrokes(&mut self, keystroke_event: &KeystrokeEvent, cx: &mut ViewContext<Self>) {        if let Some(action) = keystroke_event.action.as_ref() {            // Keystroke is handled by the vim system, so continue forward            if action.name().starts_with("vim::") {                return;            }        } else if cx.has_pending_keystrokes() || keystroke_event.keystroke.is_ime_in_progress() {            return;        }         if let Some(operator) = self.active_operator() {            if !operator.is_waiting(self.mode) {                self.clear_operator(cx);                self.stop_recording_immediately(Box::new(ClearOperators), cx)            }        }    }     fn handle_editor_event(&mut self, event: &EditorEvent, cx: &mut ViewContext<Self>) {        match event {            EditorEvent::Focused => self.focused(true, cx),            EditorEvent::Blurred => self.blurred(cx),            EditorEvent::SelectionsChanged { local: true } => {                self.local_selections_changed(cx);            }            EditorEvent::InputIgnored { text } => {                self.input_ignored(text.clone(), cx);                Vim::globals(cx).observe_insertion(text, None)            }            EditorEvent::InputHandled {                text,                utf16_range_to_replace: range_to_replace,            } => Vim::globals(cx).observe_insertion(text, range_to_replace.clone()),            EditorEvent::TransactionBegun { transaction_id } => {                self.transaction_begun(*transaction_id, cx)            }            EditorEvent::TransactionUndone { transaction_id } => {                self.transaction_undone(transaction_id, cx)            }            EditorEvent::Edited { .. } => self.push_to_change_list(cx),            EditorEvent::FocusedIn => self.sync_vim_settings(cx),            _ => {}        }    }     fn push_operator(&mut self, operator: Operator, cx: &mut ViewContext<Self>) {        if matches!(            operator,            Operator::Change                | Operator::Delete                | Operator::Replace                | Operator::Indent                | Operator::Outdent                | Operator::Lowercase                | Operator::Uppercase                | Operator::OppositeCase                | Operator::ToggleComments        ) {            self.start_recording(cx)        };        // Since these operations can only be entered with pre-operators,        // we need to clear the previous operators when pushing,        // so that the current stack is the most correct        if matches!(            operator,            Operator::AddSurrounds { .. }                | Operator::ChangeSurrounds { .. }                | Operator::DeleteSurrounds        ) {            self.operator_stack.clear();            if let Operator::AddSurrounds { target: None } = operator {                self.start_recording(cx);            }        };        self.operator_stack.push(operator);        self.sync_vim_settings(cx);    }     pub fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut ViewContext<Self>) {        let last_mode = self.mode;        let prior_mode = self.last_mode;        let prior_tx = self.current_tx;        self.last_mode = last_mode;        self.mode = mode;        self.operator_stack.clear();        self.selected_register.take();        if mode == Mode::Normal || mode != last_mode {            self.current_tx.take();            self.current_anchor.take();        }        if mode != Mode::Insert && mode != Mode::Replace {            self.take_count(cx);        }         // Sync editor settings like clip mode        self.sync_vim_settings(cx);         if VimSettings::get_global(cx).toggle_relative_line_numbers            && self.mode != self.last_mode            && (self.mode == Mode::Insert || self.last_mode == Mode::Insert)        {            self.update_editor(cx, |vim, editor, cx| {                let is_relative = vim.mode != Mode::Insert;                editor.set_relative_line_number(Some(is_relative), cx)            });        }         if leave_selections {            return;        }         if !mode.is_visual() && last_mode.is_visual() {            self.create_visual_marks(last_mode, cx);        }         // Adjust selections        self.update_editor(cx, |vim, editor, cx| {            if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock            {                vim.visual_block_motion(true, editor, cx, |_, point, goal| Some((point, goal)))            }            if last_mode == Mode::Insert || last_mode == Mode::Replace {                if let Some(prior_tx) = prior_tx {                    editor.group_until_transaction(prior_tx, cx)                }            }             editor.change_selections(None, cx, |s| {                // we cheat with visual block mode and use multiple cursors.                // the cost of this cheat is we need to convert back to a single                // cursor whenever vim would.                if last_mode == Mode::VisualBlock                    && (mode != Mode::VisualBlock && mode != Mode::Insert)                {                    let tail = s.oldest_anchor().tail();                    let head = s.newest_anchor().head();                    s.select_anchor_ranges(vec![tail..head]);                } else if last_mode == Mode::Insert                    && prior_mode == Mode::VisualBlock                    && mode != Mode::VisualBlock                {                    let pos = s.first_anchor().head();                    s.select_anchor_ranges(vec![pos..pos])                }                 let snapshot = s.display_map();                if let Some(pending) = s.pending.as_mut() {                    if pending.selection.reversed && mode.is_visual() && !last_mode.is_visual() {                        let mut end = pending.selection.end.to_point(&snapshot.buffer_snapshot);                        end = snapshot                            .buffer_snapshot                            .clip_point(end + Point::new(0, 1), Bias::Right);

Lines 1–500 of 1118.