Conrad Irwinvim: Fix >... (#15404)6db33b82 years agoHistory
1085 lines · 40.6 KB · Rust
RawDownload
//! Vim support for Zed. #[cfg(test)]mod test; mod change_list;mod command;mod digraph;mod editor_events;mod insert;mod mode_indicator;mod motion;mod normal;mod object;mod replace;mod state;mod surrounds;mod visual; use anyhow::Result;use change_list::push_to_change_list;use collections::HashMap;use command_palette_hooks::{CommandPaletteFilter, CommandPaletteInterceptor};use editor::{    movement::{self, FindRange},    Anchor, Bias, Editor, EditorEvent, EditorMode, ToPoint,};use gpui::{    actions, impl_actions, Action, AppContext, EntityId, FocusableView, Global, KeystrokeEvent,    Subscription, UpdateGlobal, View, ViewContext, WeakView, WindowContext,};use language::{CursorShape, Point, SelectionGoal, TransactionId};pub use mode_indicator::ModeIndicator;use motion::Motion;use normal::{    mark::create_visual_marks,    normal_replace,    repeat::{observe_action, observe_insertion, record_register, replay_register},};use replace::multi_replace;use schemars::JsonSchema;use serde::Deserialize;use serde_derive::Serialize;use settings::{update_settings_file, Settings, SettingsSources, SettingsStore};use state::{EditorState, Mode, Operator, RecordedSelection, Register, WorkspaceState};use std::{ops::Range, sync::Arc};use surrounds::{add_surrounds, change_surrounds, delete_surrounds, SurroundsType};use ui::BorrowAppContext;use visual::{visual_block_motion, visual_replace};use workspace::{self, Workspace}; use crate::state::ReplayableAction; /// Whether or not to enable Vim mode (work in progress).////// 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) {    cx.set_global(Vim::default());    VimModeSetting::register(cx);    VimSettings::register(cx);     cx.observe_keystrokes(observe_keystrokes).detach();    editor_events::init(cx);     cx.observe_new_views(|workspace: &mut Workspace, cx| register(workspace, cx))        .detach();     // Any time settings change, update vim mode to match. The Vim struct    // will be initialized as disabled by default, so we filter its commands    // out when starting up.    CommandPaletteFilter::update_global(cx, |filter, _| {        filter.hide_namespace(Vim::NAMESPACE);    });    Vim::update_global(cx, |vim, cx| {        vim.set_enabled(VimModeSetting::get_global(cx).0, cx)    });    cx.observe_global::<SettingsStore>(|cx| {        Vim::update_global(cx, |vim, cx| {            vim.set_enabled(VimModeSetting::get_global(cx).0, cx)        });    })    .detach();} fn register(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {    workspace.register_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {        Vim::update(cx, |vim, cx| vim.switch_mode(mode, false, cx))    });    workspace.register_action(        |_: &mut Workspace, PushOperator(operator): &PushOperator, cx| {            Vim::update(cx, |vim, cx| vim.push_operator(operator.clone(), cx))        },    );    workspace.register_action(|_: &mut Workspace, _: &ClearOperators, cx| {        Vim::update(cx, |vim, cx| vim.clear_operator(cx))    });    workspace.register_action(|_: &mut Workspace, n: &Number, cx: _| {        Vim::update(cx, |vim, cx| vim.push_count_digit(n.0, cx));    });    workspace.register_action(|_: &mut Workspace, _: &Tab, cx| {        Vim::active_editor_input_ignored(" ".into(), cx)    });     workspace.register_action(|_: &mut Workspace, _: &Enter, cx| {        Vim::active_editor_input_ignored("\n".into(), cx)    });     workspace.register_action(|workspace: &mut Workspace, _: &ToggleVimMode, cx| {        let fs = workspace.app_state().fs.clone();        let currently_enabled = VimModeSetting::get_global(cx).0;        update_settings_file::<VimModeSetting>(fs, cx, move |setting, _| {            *setting = Some(!currently_enabled)        })    });     workspace.register_action(|_: &mut Workspace, _: &OpenDefaultKeymap, cx| {        cx.emit(workspace::Event::OpenBundledFile {            text: settings::vim_keymap(),            title: "Default Vim Bindings",            language: "JSON",        });    });     normal::register(workspace, cx);    insert::register(workspace, cx);    motion::register(workspace, cx);    command::register(workspace, cx);    replace::register(workspace, cx);    object::register(workspace, cx);    visual::register(workspace, cx);    change_list::register(workspace, cx);} /// Called whenever an keystroke is typed so vim can observe all actions/// and keystrokes accordingly.fn observe_keystrokes(keystroke_event: &KeystrokeEvent, cx: &mut WindowContext) {    if let Some(action) = keystroke_event        .action        .as_ref()        .map(|action| action.boxed_clone())    {        observe_action(action.boxed_clone(), cx);         // 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;    }     Vim::update(cx, |vim, cx| {        if let Some(operator) = vim.active_operator() {            if !operator.is_waiting(vim.state().mode) {                vim.clear_operator(cx);                vim.stop_recording_immediately(Box::new(ClearOperators))            }        }    });} /// The state pertaining to Vim mode.#[derive(Default)]struct Vim {    active_editor: Option<WeakView<Editor>>,    editor_subscription: Option<Subscription>,    enabled: bool,    editor_states: HashMap<EntityId, EditorState>,    workspace_state: WorkspaceState,    default_state: EditorState,} impl Global for Vim {} impl Vim {    /// The namespace for Vim actions.    const NAMESPACE: &'static str = "vim";     fn read(cx: &mut AppContext) -> &Self {        cx.global::<Self>()    }     fn update<F, S>(cx: &mut WindowContext, update: F) -> S    where        F: FnOnce(&mut Self, &mut WindowContext) -> S,    {        cx.update_global(update)    }     fn activate_editor(&mut self, editor: View<Editor>, cx: &mut WindowContext) {        if !editor.read(cx).use_modal_editing() {            return;        }         self.active_editor = Some(editor.clone().downgrade());        self.editor_subscription = Some(cx.subscribe(&editor, |editor, event, cx| match event {            EditorEvent::SelectionsChanged { local: true } => {                if editor.read(cx).leader_peer_id().is_none() {                    Vim::update(cx, |vim, cx| {                        vim.local_selections_changed(editor, cx);                    })                }            }            EditorEvent::InputIgnored { text } => {                Vim::active_editor_input_ignored(text.clone(), cx);                observe_insertion(text, None, cx)            }            EditorEvent::InputHandled {                text,                utf16_range_to_replace: range_to_replace,            } => observe_insertion(text, range_to_replace.clone(), cx),            EditorEvent::TransactionBegun { transaction_id } => Vim::update(cx, |vim, cx| {                vim.transaction_begun(*transaction_id, cx);            }),            EditorEvent::TransactionUndone { transaction_id } => Vim::update(cx, |vim, cx| {                vim.transaction_undone(transaction_id, cx);            }),            EditorEvent::Edited { .. } => {                Vim::update(cx, |vim, cx| vim.transaction_ended(editor, cx))            }            EditorEvent::FocusedIn => Vim::update(cx, |vim, cx| vim.sync_vim_settings(cx)),            _ => {}        }));         let editor = editor.read(cx);        let editor_mode = editor.mode();        let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();         if editor_mode == EditorMode::Full                && !newest_selection_empty                && self.state().mode == Mode::Normal                // When following someone, don't switch vim mode.                && editor.leader_peer_id().is_none()        {            self.switch_mode(Mode::Visual, true, cx);        }         self.sync_vim_settings(cx);    }     fn update_active_editor<S>(        &mut self,        cx: &mut WindowContext,        update: impl FnOnce(&mut Vim, &mut Editor, &mut ViewContext<Editor>) -> S,    ) -> Option<S> {        let editor = self.active_editor.clone()?.upgrade()?;        Some(editor.update(cx, |editor, cx| update(self, editor, cx)))    }     fn editor_selections(&mut self, cx: &mut WindowContext) -> Vec<Range<Anchor>> {        self.update_active_editor(cx, |_, editor, _| {            editor                .selections                .disjoint_anchors()                .iter()                .map(|selection| selection.tail()..selection.head())                .collect()        })        .unwrap_or_default()    }     /// When doing an action that modifies the buffer, we start recording so that `.`    /// will replay the action.    pub fn start_recording(&mut self, cx: &mut WindowContext) {        if !self.workspace_state.dot_replaying {            self.workspace_state.dot_recording = true;            self.workspace_state.recorded_actions = Default::default();            self.workspace_state.recorded_count = None;             let selections = self                .active_editor                .as_ref()                .and_then(|editor| editor.upgrade())                .map(|editor| {                    let editor = editor.read(cx);                    (                        editor.selections.oldest::<Point>(cx),                        editor.selections.newest::<Point>(cx),                    )                });             if let Some((oldest, newest)) = selections {                self.workspace_state.recorded_selection = match self.state().mode {                    Mode::Visual if newest.end.row == newest.start.row => {                        RecordedSelection::SingleLine {                            cols: newest.end.column - newest.start.column,                        }                    }                    Mode::Visual => RecordedSelection::Visual {                        rows: newest.end.row - newest.start.row,                        cols: newest.end.column,                    },                    Mode::VisualLine => RecordedSelection::VisualLine {                        rows: newest.end.row - newest.start.row,                    },                    Mode::VisualBlock => RecordedSelection::VisualBlock {                        rows: newest.end.row.abs_diff(oldest.start.row),                        cols: newest.end.column.abs_diff(oldest.start.column),                    },                    _ => RecordedSelection::None,                }            } else {                self.workspace_state.recorded_selection = RecordedSelection::None;            }        }    }     pub fn stop_replaying(&mut self, _: &mut WindowContext) {        self.workspace_state.dot_replaying = false;        if let Some(replayer) = self.workspace_state.replayer.take() {            replayer.stop();        }    }     /// When finishing an action that modifies the buffer, stop recording.    /// as you usually call this within a keystroke handler we also ensure that    /// the current action is recorded.    pub fn stop_recording(&mut self) {        if self.workspace_state.dot_recording {            self.workspace_state.stop_recording_after_next_action = true;        }    }     /// Stops recording actions immediately rather than waiting until after the    /// next action to stop recording.    ///    /// This doesn't include the current action.    pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>) {        if self.workspace_state.dot_recording {            self.workspace_state                .recorded_actions                .push(ReplayableAction::Action(action.boxed_clone()));            self.workspace_state.dot_recording = false;            self.workspace_state.stop_recording_after_next_action = false;        }    }     /// Explicitly record one action (equivalents to start_recording and stop_recording)    pub fn record_current_action(&mut self, cx: &mut WindowContext) {        self.start_recording(cx);        self.stop_recording();    }     // When handling an action, you must create visual marks if you will switch to normal    // mode without the default selection behavior.    fn store_visual_marks(&mut self, cx: &mut WindowContext) {        let mode = self.state().mode;        if mode.is_visual() {            create_visual_marks(self, mode, cx);        }    }     fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut WindowContext) {        let state = self.state();        let last_mode = state.mode;        let prior_mode = state.last_mode;        let prior_tx = state.current_tx;        self.update_state(|state| {            state.last_mode = last_mode;            state.mode = mode;            state.operator_stack.clear();            state.selected_register.take();            if mode == Mode::Normal || mode != last_mode {                state.current_tx.take();                state.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 leave_selections {            return;        }         if !mode.is_visual() && last_mode.is_visual() {            create_visual_marks(self, last_mode, cx);        }         // Adjust selections        self.update_active_editor(cx, |_, editor, cx| {            if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock            {                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);                        pending.selection.end = snapshot.buffer_snapshot.anchor_before(end);                    }                }                 s.move_with(|map, selection| {                    if last_mode.is_visual() && !mode.is_visual() {                        let mut point = selection.head();                        if !selection.reversed && !selection.is_empty() {                            point = movement::left(map, selection.head());                        }                        selection.collapse_to(point, selection.goal)                    } else if !last_mode.is_visual() && mode.is_visual() {                        if selection.is_empty() {                            selection.end = movement::right(map, selection.start);                        }                    }                });            })        });    }     fn push_count_digit(&mut self, number: usize, cx: &mut WindowContext) {        if self.active_operator().is_some() {            self.update_state(|state| {                let post_count = state.post_count.unwrap_or(0);                 state.post_count = Some(                    post_count                        .checked_mul(10)                        .and_then(|post_count| post_count.checked_add(number))                        .unwrap_or(post_count),                )            })        } else {            self.update_state(|state| {                let pre_count = state.pre_count.unwrap_or(0);                 state.pre_count = Some(                    pre_count                        .checked_mul(10)                        .and_then(|pre_count| pre_count.checked_add(number))

Lines 1–500 of 1085.