//! Vim support for Zed. #[cfg(test)]mod test; mod change_list;mod command;mod digraph;mod helix;mod indent;mod insert;mod mode_indicator;mod motion;mod normal;mod object;mod replace;mod rewrap;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, App, AppContext as _, Axis, Context, Entity, EventEmitter, KeyContext, KeystrokeEvent, Render, Subscription, Task, WeakEntity, Window,};use insert::{NormalBefore, TemporaryNormal};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::{mem, ops::Range, sync::Arc};use surrounds::SurroundsType;use theme::ThemeSettings;use ui::{px, IntoElement, SharedString};use vim_mode_setting::VimModeSetting;use workspace::{self, Pane, ResizeIntent, Workspace}; use crate::state::ReplayableAction; /// Used to resize the current pane#[derive(Clone, Deserialize, JsonSchema, PartialEq)]pub struct ResizePane(pub ResizeIntent); /// An Action to Switch between modes#[derive(Clone, Deserialize, JsonSchema, 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, JsonSchema, PartialEq)]pub struct PushOperator(pub Operator); /// Number is used to manage vim's count. Pushing a digit/// multiplies the current value by 10 and adds the digit.#[derive(Clone, Deserialize, JsonSchema, PartialEq)]struct Number(usize); #[derive(Clone, Deserialize, JsonSchema, PartialEq)]struct SelectRegister(String); actions!( vim, [ ClearOperators, Tab, Enter, InnerObject, FindForward, FindBackward, MaximizePane, OpenDefaultKeymap, ResetPaneSizes, Sneak, SneakBackward, ]); // in the workspace namespace so it's not filtered out when vim is disabled.actions!(workspace, [ToggleVimMode]); impl_actions!( vim, [ResizePane, SwitchMode, PushOperator, Number, SelectRegister]); /// Initializes the `vim` crate.pub fn init(cx: &mut App) { vim_mode_setting::init(cx); VimSettings::register(cx); VimGlobals::register(cx); cx.observe_new(Vim::register).detach(); cx.observe_new(|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, _: &ResetPaneSizes, _, cx| { workspace.reset_pane_sizes(cx); }); workspace.register_action(|workspace, _: &MaximizePane, _, cx| { let pane = workspace.active_pane(); let Some(size) = workspace.bounding_box_for_pane(&pane) else { return; }; let theme = ThemeSettings::get_global(cx); let height = theme.buffer_font_size() * theme.buffer_line_height.value(); let desired_size = if let Some(count) = Vim::take_count(cx) { height * count } else { px(10000.) }; workspace.resize_pane(Axis::Vertical, desired_size - size.size.height, cx) }); workspace.register_action(|workspace, action: &ResizePane, window, cx| { let count = Vim::take_count(cx).unwrap_or(1) as f32; let theme = ThemeSettings::get_global(cx); let Ok(font_id) = window.text_system().font_id(&theme.buffer_font) else { return; }; let Ok(width) = window .text_system() .advance(font_id, theme.buffer_font_size(), 'm') else { return; }; let height = theme.buffer_font_size() * theme.buffer_line_height.value(); let (axis, amount) = match action.0 { ResizeIntent::Lengthen => (Axis::Vertical, height), ResizeIntent::Shorten => (Axis::Vertical, height * -1.), ResizeIntent::Widen => (Axis::Horizontal, width.width), ResizeIntent::Narrow => (Axis::Horizontal, width.width * -1.), }; workspace.resize_pane(axis, amount * count, cx); }); workspace.register_action(|workspace, _: &SearchSubmit, window, cx| { let vim = workspace .focused_pane(window, cx) .read(cx) .active_item() .and_then(|item| item.act_as::<Editor>(cx)) .and_then(|editor| editor.read(cx).addon::<VimAddon>().cloned()); let Some(vim) = vim else { return }; vim.model.update(cx, |_, cx| { cx.defer_in(window, |vim, window, cx| vim.search_submit(window, cx)) }) }); }) .detach();} #[derive(Clone)]pub(crate) struct VimAddon { pub(crate) model: Entity<Vim>,} impl editor::Addon for VimAddon { fn extend_key_context(&self, key_context: &mut KeyContext, cx: &App) { self.model.read(cx).extend_key_context(key_context, cx) } 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, pub temp_mode: bool, pub status_label: Option<SharedString>, pub exit_temporary_mode: bool, 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: WeakEntity<Editor>, last_command: Option<String>, running_command: Option<Task<()>>, _subscriptions: Vec<Subscription>,} // 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, _window: &mut Window, _cx: &mut Context<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(window: &mut Window, cx: &mut Context<Editor>) -> Entity<Self> { let editor = cx.entity().clone(); cx.new(|cx| Vim { mode: Mode::Normal, last_mode: Mode::Normal, temp_mode: false, exit_temporary_mode: false, 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(), status_label: None, selected_register: None, search: SearchState::default(), last_command: None, running_command: None, editor: editor.downgrade(), _subscriptions: vec![ cx.observe_keystrokes(Self::observe_keystrokes), cx.subscribe_in(&editor, window, |this, _, event, window, cx| { this.handle_editor_event(event, window, cx) }), ], }) } fn register(editor: &mut Editor, window: Option<&mut Window>, cx: &mut Context<Editor>) { let Some(window) = window else { return; }; 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_in::<SettingsStore>(window, move |editor, window, 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.model.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, window, cx) } else { Self::deactivate(editor, cx) } }) .detach(); if was_enabled { Self::activate(editor, window, cx) } } fn activate(editor: &mut Editor, window: &mut Window, cx: &mut Context<Editor>) { let vim = Vim::new(window, cx); editor.register_addon(VimAddon { model: vim.clone() }); vim.update(cx, |_, cx| { Vim::action(editor, cx, |vim, action: &SwitchMode, window, cx| { vim.switch_mode(action.0, false, window, cx) }); Vim::action(editor, cx, |vim, action: &PushOperator, window, cx| { vim.push_operator(action.0.clone(), window, cx) }); Vim::action(editor, cx, |vim, _: &ClearOperators, window, cx| { vim.clear_operator(window, cx) }); Vim::action(editor, cx, |vim, n: &Number, window, cx| { vim.push_count_digit(n.0, window, cx); }); Vim::action(editor, cx, |vim, _: &Tab, window, cx| { vim.input_ignored(" ".into(), window, cx) }); Vim::action(editor, cx, |vim, _: &Enter, window, cx| { vim.input_ignored("\n".into(), window, cx) }); normal::register(editor, cx); insert::register(editor, cx); helix::register(editor, cx); motion::register(editor, cx); command::register(editor, cx); replace::register(editor, cx); indent::register(editor, cx); rewrap::register(editor, cx); object::register(editor, cx); visual::register(editor, cx); change_list::register(editor, cx); digraph::register(editor, cx); cx.defer_in(window, |vim, window, cx| { vim.focused(false, window, cx); }) }) } fn deactivate(editor: &mut Editor, cx: &mut Context<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.entity().entity_id() { Vim::globals(cx).focused_vim = None; } } } /// Register an action on the editor. pub fn action<A: Action>( editor: &mut Editor, cx: &mut Context<Vim>, f: impl Fn(&mut Vim, &A, &mut Window, &mut Context<Vim>) + 'static, ) { let subscription = editor.register_action(cx.listener(f)); cx.on_release(|_, _| drop(subscription)).detach(); } pub fn editor(&self) -> Option<Entity<Editor>> { self.editor.upgrade() } pub fn workspace(&self, window: &mut Window) -> Option<Entity<Workspace>> { window.root::<Workspace>().flatten() } pub fn pane(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Entity<Pane>> { self.workspace(window) .map(|workspace| workspace.read(cx).focused_pane(window, cx)) } pub fn enabled(cx: &mut App) -> 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, window: &mut Window, cx: &mut Context<Self>, ) { if self.exit_temporary_mode { self.exit_temporary_mode = false; // Don't switch to insert mode if the action is temporary_normal. if let Some(action) = keystroke_event.action.as_ref() { if action.as_any().downcast_ref::<TemporaryNormal>().is_some() { return; } } self.switch_mode(Mode::Insert, false, window, cx) } 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 window.has_pending_keystrokes() || keystroke_event.keystroke.is_ime_in_progress() { return; } if let Some(operator) = self.active_operator() { match operator { Operator::Literal { prefix } => { self.handle_literal_keystroke( keystroke_event, prefix.unwrap_or_default(), window, cx, ); } _ if !operator.is_waiting(self.mode) => { self.clear_operator(window, cx); self.stop_recording_immediately(Box::new(ClearOperators), cx) } _ => {} } } } fn handle_editor_event( &mut self, event: &EditorEvent, window: &mut Window, cx: &mut Context<Self>, ) { match event { EditorEvent::Focused => self.focused(true, window, cx), EditorEvent::Blurred => self.blurred(window, cx), EditorEvent::SelectionsChanged { local: true } => { self.local_selections_changed(window, cx); } EditorEvent::InputIgnored { text } => { self.input_ignored(text.clone(), window, 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, window, cx) } EditorEvent::TransactionUndone { transaction_id } => { self.transaction_undone(transaction_id, window, cx) } EditorEvent::Edited { .. } => self.push_to_change_list(window, cx), EditorEvent::FocusedIn => self.sync_vim_settings(window, cx), EditorEvent::CursorShapeChanged => self.cursor_shape_changed(window, cx), _ => {} } } fn push_operator(&mut self, operator: Operator, window: &mut Window, cx: &mut Context<Self>) { if matches!( operator, Operator::Change | Operator::Delete | Operator::Replace | Operator::Indent | Operator::OutdentLines 1–500 of 1336. Load more
//! Vim support for Zed. #[cfg(test)] mod test; mod change_list; mod command; mod digraph; mod helix; mod indent; mod insert; mod mode_indicator; mod motion; mod normal; mod object; mod replace; mod rewrap; 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, App, AppContext as _, Axis, Context, Entity, EventEmitter, KeyContext, KeystrokeEvent, Render, Subscription, Task, WeakEntity, Window, }; use insert::{NormalBefore, TemporaryNormal}; 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::{mem, ops::Range, sync::Arc}; use surrounds::SurroundsType; use theme::ThemeSettings; use ui::{px, IntoElement, SharedString}; use vim_mode_setting::VimModeSetting; use workspace::{self, Pane, ResizeIntent, Workspace}; use crate::state::ReplayableAction; /// Used to resize the current pane #[derive(Clone, Deserialize, JsonSchema, PartialEq)] pub struct ResizePane(pub ResizeIntent); /// An Action to Switch between modes #[derive(Clone, Deserialize, JsonSchema, 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, JsonSchema, PartialEq)] pub struct PushOperator(pub Operator); /// Number is used to manage vim's count. Pushing a digit /// multiplies the current value by 10 and adds the digit. #[derive(Clone, Deserialize, JsonSchema, PartialEq)] struct Number(usize); #[derive(Clone, Deserialize, JsonSchema, PartialEq)] struct SelectRegister(String); actions!( vim, [ ClearOperators, Tab, Enter, InnerObject, FindForward, FindBackward, MaximizePane, OpenDefaultKeymap, ResetPaneSizes, Sneak, SneakBackward, ] ); // in the workspace namespace so it's not filtered out when vim is disabled. actions!(workspace, [ToggleVimMode]); impl_actions!( vim, [ResizePane, SwitchMode, PushOperator, Number, SelectRegister] ); /// Initializes the `vim` crate. pub fn init(cx: &mut App) { vim_mode_setting::init(cx); VimSettings::register(cx); VimGlobals::register(cx); cx.observe_new(Vim::register).detach(); cx.observe_new(|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, _: &ResetPaneSizes, _, cx| { workspace.reset_pane_sizes(cx); }); workspace.register_action(|workspace, _: &MaximizePane, _, cx| { let pane = workspace.active_pane(); let Some(size) = workspace.bounding_box_for_pane(&pane) else { return; }; let theme = ThemeSettings::get_global(cx); let height = theme.buffer_font_size() * theme.buffer_line_height.value(); let desired_size = if let Some(count) = Vim::take_count(cx) { height * count } else { px(10000.) }; workspace.resize_pane(Axis::Vertical, desired_size - size.size.height, cx) }); workspace.register_action(|workspace, action: &ResizePane, window, cx| { let count = Vim::take_count(cx).unwrap_or(1) as f32; let theme = ThemeSettings::get_global(cx); let Ok(font_id) = window.text_system().font_id(&theme.buffer_font) else { return; }; let Ok(width) = window .text_system() .advance(font_id, theme.buffer_font_size(), 'm') else { return; }; let height = theme.buffer_font_size() * theme.buffer_line_height.value(); let (axis, amount) = match action.0 { ResizeIntent::Lengthen => (Axis::Vertical, height), ResizeIntent::Shorten => (Axis::Vertical, height * -1.), ResizeIntent::Widen => (Axis::Horizontal, width.width), ResizeIntent::Narrow => (Axis::Horizontal, width.width * -1.), }; workspace.resize_pane(axis, amount * count, cx); }); workspace.register_action(|workspace, _: &SearchSubmit, window, cx| { let vim = workspace .focused_pane(window, cx) .read(cx) .active_item() .and_then(|item| item.act_as::<Editor>(cx)) .and_then(|editor| editor.read(cx).addon::<VimAddon>().cloned()); let Some(vim) = vim else { return }; vim.model.update(cx, |_, cx| { cx.defer_in(window, |vim, window, cx| vim.search_submit(window, cx)) }) }); }) .detach(); } #[derive(Clone)] pub(crate) struct VimAddon { pub(crate) model: Entity<Vim>, } impl editor::Addon for VimAddon { fn extend_key_context(&self, key_context: &mut KeyContext, cx: &App) { self.model.read(cx).extend_key_context(key_context, cx) } 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, pub temp_mode: bool, pub status_label: Option<SharedString>, pub exit_temporary_mode: bool, 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: WeakEntity<Editor>, last_command: Option<String>, running_command: Option<Task<()>>, _subscriptions: Vec<Subscription>, } // 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, _window: &mut Window, _cx: &mut Context<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(window: &mut Window, cx: &mut Context<Editor>) -> Entity<Self> { let editor = cx.entity().clone(); cx.new(|cx| Vim { mode: Mode::Normal, last_mode: Mode::Normal, temp_mode: false, exit_temporary_mode: false, 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(), status_label: None, selected_register: None, search: SearchState::default(), last_command: None, running_command: None, editor: editor.downgrade(), _subscriptions: vec![ cx.observe_keystrokes(Self::observe_keystrokes), cx.subscribe_in(&editor, window, |this, _, event, window, cx| { this.handle_editor_event(event, window, cx) }), ], }) } fn register(editor: &mut Editor, window: Option<&mut Window>, cx: &mut Context<Editor>) { let Some(window) = window else { return; }; 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_in::<SettingsStore>(window, move |editor, window, 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.model.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, window, cx) } else { Self::deactivate(editor, cx) } }) .detach(); if was_enabled { Self::activate(editor, window, cx) } } fn activate(editor: &mut Editor, window: &mut Window, cx: &mut Context<Editor>) { let vim = Vim::new(window, cx); editor.register_addon(VimAddon { model: vim.clone() }); vim.update(cx, |_, cx| { Vim::action(editor, cx, |vim, action: &SwitchMode, window, cx| { vim.switch_mode(action.0, false, window, cx) }); Vim::action(editor, cx, |vim, action: &PushOperator, window, cx| { vim.push_operator(action.0.clone(), window, cx) }); Vim::action(editor, cx, |vim, _: &ClearOperators, window, cx| { vim.clear_operator(window, cx) }); Vim::action(editor, cx, |vim, n: &Number, window, cx| { vim.push_count_digit(n.0, window, cx); }); Vim::action(editor, cx, |vim, _: &Tab, window, cx| { vim.input_ignored(" ".into(), window, cx) }); Vim::action(editor, cx, |vim, _: &Enter, window, cx| { vim.input_ignored("\n".into(), window, cx) }); normal::register(editor, cx); insert::register(editor, cx); helix::register(editor, cx); motion::register(editor, cx); command::register(editor, cx); replace::register(editor, cx); indent::register(editor, cx); rewrap::register(editor, cx); object::register(editor, cx); visual::register(editor, cx); change_list::register(editor, cx); digraph::register(editor, cx); cx.defer_in(window, |vim, window, cx| { vim.focused(false, window, cx); }) }) } fn deactivate(editor: &mut Editor, cx: &mut Context<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.entity().entity_id() { Vim::globals(cx).focused_vim = None; } } } /// Register an action on the editor. pub fn action<A: Action>( editor: &mut Editor, cx: &mut Context<Vim>, f: impl Fn(&mut Vim, &A, &mut Window, &mut Context<Vim>) + 'static, ) { let subscription = editor.register_action(cx.listener(f)); cx.on_release(|_, _| drop(subscription)).detach(); } pub fn editor(&self) -> Option<Entity<Editor>> { self.editor.upgrade() } pub fn workspace(&self, window: &mut Window) -> Option<Entity<Workspace>> { window.root::<Workspace>().flatten() } pub fn pane(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Entity<Pane>> { self.workspace(window) .map(|workspace| workspace.read(cx).focused_pane(window, cx)) } pub fn enabled(cx: &mut App) -> 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, window: &mut Window, cx: &mut Context<Self>, ) { if self.exit_temporary_mode { self.exit_temporary_mode = false; // Don't switch to insert mode if the action is temporary_normal. if let Some(action) = keystroke_event.action.as_ref() { if action.as_any().downcast_ref::<TemporaryNormal>().is_some() { return; } } self.switch_mode(Mode::Insert, false, window, cx) } 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 window.has_pending_keystrokes() || keystroke_event.keystroke.is_ime_in_progress() { return; } if let Some(operator) = self.active_operator() { match operator { Operator::Literal { prefix } => { self.handle_literal_keystroke( keystroke_event, prefix.unwrap_or_default(), window, cx, ); } _ if !operator.is_waiting(self.mode) => { self.clear_operator(window, cx); self.stop_recording_immediately(Box::new(ClearOperators), cx) } _ => {} } } } fn handle_editor_event( &mut self, event: &EditorEvent, window: &mut Window, cx: &mut Context<Self>, ) { match event { EditorEvent::Focused => self.focused(true, window, cx), EditorEvent::Blurred => self.blurred(window, cx), EditorEvent::SelectionsChanged { local: true } => { self.local_selections_changed(window, cx); } EditorEvent::InputIgnored { text } => { self.input_ignored(text.clone(), window, 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, window, cx) } EditorEvent::TransactionUndone { transaction_id } => { self.transaction_undone(transaction_id, window, cx) } EditorEvent::Edited { .. } => self.push_to_change_list(window, cx), EditorEvent::FocusedIn => self.sync_vim_settings(window, cx), EditorEvent::CursorShapeChanged => self.cursor_shape_changed(window, cx), _ => {} } } fn push_operator(&mut self, operator: Operator, window: &mut Window, cx: &mut Context<Self>) { if matches!( operator, Operator::Change | Operator::Delete | Operator::Replace | Operator::Indent | Operator::Outdent