1//! Vim support for Zed.
2
3#[cfg(test)]
4mod test;
5
6mod command;
7mod editor_events;
8mod insert;
9mod mode_indicator;
10mod motion;
11mod normal;
12mod object;
13mod state;
14mod utils;
15mod visual;
16
17use anyhow::Result;
18use collections::HashMap;
19use command_palette_hooks::{CommandPaletteFilter, CommandPaletteInterceptor};
20use editor::{
21 movement::{self, FindRange},
22 Editor, EditorEvent, EditorMode,
23};
24use gpui::{
25 actions, impl_actions, Action, AppContext, EntityId, Global, KeystrokeEvent, Subscription,
26 View, ViewContext, WeakView, WindowContext,
27};
28use language::{CursorShape, Point, Selection, SelectionGoal};
29pub use mode_indicator::ModeIndicator;
30use motion::Motion;
31use normal::normal_replace;
32use schemars::JsonSchema;
33use serde::Deserialize;
34use serde_derive::Serialize;
35use settings::{update_settings_file, Settings, SettingsStore};
36use state::{EditorState, Mode, Operator, RecordedSelection, WorkspaceState};
37use std::{ops::Range, sync::Arc};
38use visual::{visual_block_motion, visual_replace};
39use workspace::{self, Workspace};
40
41use crate::state::ReplayableAction;
42
43/// Whether or not to enable Vim mode (work in progress).
44///
45/// Default: false
46pub struct VimModeSetting(pub bool);
47
48/// An Action to Switch between modes
49#[derive(Clone, Deserialize, PartialEq)]
50pub struct SwitchMode(pub Mode);
51
52/// PushOperator is used to put vim into a "minor" mode,
53/// where it's waiting for a specific next set of keystrokes.
54/// For example 'd' needs a motion to complete.
55#[derive(Clone, Deserialize, PartialEq)]
56pub struct PushOperator(pub Operator);
57
58/// Number is used to manage vim's count. Pushing a digit
59/// multiplis the current value by 10 and adds the digit.
60#[derive(Clone, Deserialize, PartialEq)]
61struct Number(usize);
62
63actions!(
64 vim,
65 [Tab, Enter, Object, InnerObject, FindForward, FindBackward]
66);
67
68// in the workspace namespace so it's not filtered out when vim is disabled.
69actions!(workspace, [ToggleVimMode]);
70
71impl_actions!(vim, [SwitchMode, PushOperator, Number]);
72
73/// Initializes the `vim` crate.
74pub fn init(cx: &mut AppContext) {
75 cx.set_global(Vim::default());
76 VimModeSetting::register(cx);
77 VimSettings::register(cx);
78
79 cx.observe_keystrokes(observe_keystrokes).detach();
80 editor_events::init(cx);
81
82 cx.observe_new_views(|workspace: &mut Workspace, cx| register(workspace, cx))
83 .detach();
84
85 // Any time settings change, update vim mode to match. The Vim struct
86 // will be initialized as disabled by default, so we filter its commands
87 // out when starting up.
88 cx.update_global::<CommandPaletteFilter, _>(|filter, _| {
89 filter.hidden_namespaces.insert("vim");
90 });
91 cx.update_global(|vim: &mut Vim, cx: &mut AppContext| {
92 vim.set_enabled(VimModeSetting::get_global(cx).0, cx)
93 });
94 cx.observe_global::<SettingsStore>(|cx| {
95 cx.update_global(|vim: &mut Vim, cx: &mut AppContext| {
96 vim.set_enabled(VimModeSetting::get_global(cx).0, cx)
97 });
98 })
99 .detach();
100}
101
102fn register(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
103 workspace.register_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {
104 Vim::update(cx, |vim, cx| vim.switch_mode(mode, false, cx))
105 });
106 workspace.register_action(
107 |_: &mut Workspace, &PushOperator(operator): &PushOperator, cx| {
108 Vim::update(cx, |vim, cx| vim.push_operator(operator, cx))
109 },
110 );
111 workspace.register_action(|_: &mut Workspace, n: &Number, cx: _| {
112 Vim::update(cx, |vim, cx| vim.push_count_digit(n.0, cx));
113 });
114
115 workspace.register_action(|_: &mut Workspace, _: &Tab, cx| {
116 Vim::active_editor_input_ignored(" ".into(), cx)
117 });
118
119 workspace.register_action(|_: &mut Workspace, _: &Enter, cx| {
120 Vim::active_editor_input_ignored("\n".into(), cx)
121 });
122
123 workspace.register_action(|workspace: &mut Workspace, _: &ToggleVimMode, cx| {
124 let fs = workspace.app_state().fs.clone();
125 let currently_enabled = VimModeSetting::get_global(cx).0;
126 update_settings_file::<VimModeSetting>(fs, cx, move |setting| {
127 *setting = Some(!currently_enabled)
128 })
129 });
130
131 normal::register(workspace, cx);
132 insert::register(workspace, cx);
133 motion::register(workspace, cx);
134 command::register(workspace, cx);
135 object::register(workspace, cx);
136 visual::register(workspace, cx);
137}
138
139/// Called whenever an keystroke is typed so vim can observe all actions
140/// and keystrokes accordingly.
141fn observe_keystrokes(keystroke_event: &KeystrokeEvent, cx: &mut WindowContext) {
142 if let Some(action) = keystroke_event
143 .action
144 .as_ref()
145 .map(|action| action.boxed_clone())
146 {
147 Vim::update(cx, |vim, _| {
148 if vim.workspace_state.recording {
149 vim.workspace_state
150 .recorded_actions
151 .push(ReplayableAction::Action(action.boxed_clone()));
152
153 if vim.workspace_state.stop_recording_after_next_action {
154 vim.workspace_state.recording = false;
155 vim.workspace_state.stop_recording_after_next_action = false;
156 }
157 }
158 });
159
160 // Keystroke is handled by the vim system, so continue forward
161 if action.name().starts_with("vim::") {
162 return;
163 }
164 } else if cx.has_pending_keystrokes() {
165 return;
166 }
167
168 Vim::update(cx, |vim, cx| match vim.active_operator() {
169 Some(Operator::FindForward { .. } | Operator::FindBackward { .. } | Operator::Replace) => {}
170 Some(_) => {
171 vim.clear_operator(cx);
172 }
173 _ => {}
174 });
175}
176
177/// The state pertaining to Vim mode.
178#[derive(Default)]
179struct Vim {
180 active_editor: Option<WeakView<Editor>>,
181 editor_subscription: Option<Subscription>,
182 enabled: bool,
183 editor_states: HashMap<EntityId, EditorState>,
184 workspace_state: WorkspaceState,
185 default_state: EditorState,
186}
187
188impl Global for Vim {}
189
190impl Vim {
191 fn read(cx: &mut AppContext) -> &Self {
192 cx.global::<Self>()
193 }
194
195 fn update<F, S>(cx: &mut WindowContext, update: F) -> S
196 where
197 F: FnOnce(&mut Self, &mut WindowContext) -> S,
198 {
199 cx.update_global(update)
200 }
201
202 fn activate_editor(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
203 if !editor.read(cx).use_modal_editing() {
204 return;
205 }
206
207 self.active_editor = Some(editor.clone().downgrade());
208 self.editor_subscription = Some(cx.subscribe(&editor, |editor, event, cx| match event {
209 EditorEvent::SelectionsChanged { local: true } => {
210 let editor = editor.read(cx);
211 if editor.leader_peer_id().is_none() {
212 let newest = editor.selections.newest::<usize>(cx);
213 let is_multicursor = editor.selections.count() > 1;
214 local_selections_changed(newest, is_multicursor, cx);
215 }
216 }
217 EditorEvent::InputIgnored { text } => {
218 Vim::active_editor_input_ignored(text.clone(), cx);
219 Vim::record_insertion(text, None, cx)
220 }
221 EditorEvent::InputHandled {
222 text,
223 utf16_range_to_replace: range_to_replace,
224 } => Vim::record_insertion(text, range_to_replace.clone(), cx),
225 _ => {}
226 }));
227
228 let editor = editor.read(cx);
229 let editor_mode = editor.mode();
230 let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
231
232 if editor_mode == EditorMode::Full
233 && !newest_selection_empty
234 && self.state().mode == Mode::Normal
235 // When following someone, don't switch vim mode.
236 && editor.leader_peer_id().is_none()
237 {
238 self.switch_mode(Mode::Visual, true, cx);
239 }
240
241 self.sync_vim_settings(cx);
242 }
243
244 fn record_insertion(
245 text: &Arc<str>,
246 range_to_replace: Option<Range<isize>>,
247 cx: &mut WindowContext,
248 ) {
249 Vim::update(cx, |vim, _| {
250 if vim.workspace_state.recording {
251 vim.workspace_state
252 .recorded_actions
253 .push(ReplayableAction::Insertion {
254 text: text.clone(),
255 utf16_range_to_replace: range_to_replace,
256 });
257 if vim.workspace_state.stop_recording_after_next_action {
258 vim.workspace_state.recording = false;
259 vim.workspace_state.stop_recording_after_next_action = false;
260 }
261 }
262 });
263 }
264
265 fn update_active_editor<S>(
266 &mut self,
267 cx: &mut WindowContext,
268 update: impl FnOnce(&mut Vim, &mut Editor, &mut ViewContext<Editor>) -> S,
269 ) -> Option<S> {
270 let editor = self.active_editor.clone()?.upgrade()?;
271 Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
272 }
273
274 /// When doing an action that modifies the buffer, we start recording so that `.`
275 /// will replay the action.
276 pub fn start_recording(&mut self, cx: &mut WindowContext) {
277 if !self.workspace_state.replaying {
278 self.workspace_state.recording = true;
279 self.workspace_state.recorded_actions = Default::default();
280 self.workspace_state.recorded_count = None;
281
282 let selections = self
283 .active_editor
284 .as_ref()
285 .and_then(|editor| editor.upgrade())
286 .map(|editor| {
287 let editor = editor.read(cx);
288 (
289 editor.selections.oldest::<Point>(cx),
290 editor.selections.newest::<Point>(cx),
291 )
292 });
293
294 if let Some((oldest, newest)) = selections {
295 self.workspace_state.recorded_selection = match self.state().mode {
296 Mode::Visual if newest.end.row == newest.start.row => {
297 RecordedSelection::SingleLine {
298 cols: newest.end.column - newest.start.column,
299 }
300 }
301 Mode::Visual => RecordedSelection::Visual {
302 rows: newest.end.row - newest.start.row,
303 cols: newest.end.column,
304 },
305 Mode::VisualLine => RecordedSelection::VisualLine {
306 rows: newest.end.row - newest.start.row,
307 },
308 Mode::VisualBlock => RecordedSelection::VisualBlock {
309 rows: newest.end.row.abs_diff(oldest.start.row),
310 cols: newest.end.column.abs_diff(oldest.start.column),
311 },
312 _ => RecordedSelection::None,
313 }
314 } else {
315 self.workspace_state.recorded_selection = RecordedSelection::None;
316 }
317 }
318 }
319
320 /// When finishing an action that modifies the buffer, stop recording.
321 /// as you usually call this within a keystroke handler we also ensure that
322 /// the current action is recorded.
323 pub fn stop_recording(&mut self) {
324 if self.workspace_state.recording {
325 self.workspace_state.stop_recording_after_next_action = true;
326 }
327 }
328
329 /// Stops recording actions immediately rather than waiting until after the
330 /// next action to stop recording.
331 ///
332 /// This doesn't include the current action.
333 pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>) {
334 if self.workspace_state.recording {
335 self.workspace_state
336 .recorded_actions
337 .push(ReplayableAction::Action(action.boxed_clone()));
338 self.workspace_state.recording = false;
339 self.workspace_state.stop_recording_after_next_action = false;
340 }
341 }
342
343 /// Explicitly record one action (equivalents to start_recording and stop_recording)
344 pub fn record_current_action(&mut self, cx: &mut WindowContext) {
345 self.start_recording(cx);
346 self.stop_recording();
347 }
348
349 fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut WindowContext) {
350 let state = self.state();
351 let last_mode = state.mode;
352 let prior_mode = state.last_mode;
353 self.update_state(|state| {
354 state.last_mode = last_mode;
355 state.mode = mode;
356 state.operator_stack.clear();
357 });
358 if mode != Mode::Insert {
359 self.take_count(cx);
360 }
361
362 // Sync editor settings like clip mode
363 self.sync_vim_settings(cx);
364
365 if leave_selections {
366 return;
367 }
368
369 // Adjust selections
370 self.update_active_editor(cx, |_, editor, cx| {
371 if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
372 {
373 visual_block_motion(true, editor, cx, |_, point, goal| Some((point, goal)))
374 }
375
376 editor.change_selections(None, cx, |s| {
377 // we cheat with visual block mode and use multiple cursors.
378 // the cost of this cheat is we need to convert back to a single
379 // cursor whenever vim would.
380 if last_mode == Mode::VisualBlock
381 && (mode != Mode::VisualBlock && mode != Mode::Insert)
382 {
383 let tail = s.oldest_anchor().tail();
384 let head = s.newest_anchor().head();
385 s.select_anchor_ranges(vec![tail..head]);
386 } else if last_mode == Mode::Insert
387 && prior_mode == Mode::VisualBlock
388 && mode != Mode::VisualBlock
389 {
390 let pos = s.first_anchor().head();
391 s.select_anchor_ranges(vec![pos..pos])
392 }
393
394 s.move_with(|map, selection| {
395 if last_mode.is_visual() && !mode.is_visual() {
396 let mut point = selection.head();
397 if !selection.reversed && !selection.is_empty() {
398 point = movement::left(map, selection.head());
399 }
400 selection.collapse_to(point, selection.goal)
401 } else if !last_mode.is_visual() && mode.is_visual() {
402 if selection.is_empty() {
403 selection.end = movement::right(map, selection.start);
404 }
405 }
406 });
407 })
408 });
409 }
410
411 fn push_count_digit(&mut self, number: usize, cx: &mut WindowContext) {
412 if self.active_operator().is_some() {
413 self.update_state(|state| {
414 state.post_count = Some(state.post_count.unwrap_or(0) * 10 + number)
415 })
416 } else {
417 self.update_state(|state| {
418 state.pre_count = Some(state.pre_count.unwrap_or(0) * 10 + number)
419 })
420 }
421 // update the keymap so that 0 works
422 self.sync_vim_settings(cx)
423 }
424
425 fn take_count(&mut self, cx: &mut WindowContext) -> Option<usize> {
426 if self.workspace_state.replaying {
427 return self.workspace_state.recorded_count;
428 }
429
430 let count = if self.state().post_count == None && self.state().pre_count == None {
431 return None;
432 } else {
433 Some(self.update_state(|state| {
434 state.post_count.take().unwrap_or(1) * state.pre_count.take().unwrap_or(1)
435 }))
436 };
437 if self.workspace_state.recording {
438 self.workspace_state.recorded_count = count;
439 }
440 self.sync_vim_settings(cx);
441 count
442 }
443
444 fn push_operator(&mut self, operator: Operator, cx: &mut WindowContext) {
445 if matches!(
446 operator,
447 Operator::Change | Operator::Delete | Operator::Replace
448 ) {
449 self.start_recording(cx)
450 };
451 self.update_state(|state| state.operator_stack.push(operator));
452 self.sync_vim_settings(cx);
453 }
454
455 fn maybe_pop_operator(&mut self) -> Option<Operator> {
456 self.update_state(|state| state.operator_stack.pop())
457 }
458
459 fn pop_operator(&mut self, cx: &mut WindowContext) -> Operator {
460 let popped_operator = self.update_state( |state| state.operator_stack.pop()
461 ) .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
462 self.sync_vim_settings(cx);
463 popped_operator
464 }
465 fn clear_operator(&mut self, cx: &mut WindowContext) {
466 self.take_count(cx);
467 self.update_state(|state| state.operator_stack.clear());
468 self.sync_vim_settings(cx);
469 }
470
471 fn active_operator(&self) -> Option<Operator> {
472 self.state().operator_stack.last().copied()
473 }
474
475 fn active_editor_input_ignored(text: Arc<str>, cx: &mut WindowContext) {
476 if text.is_empty() {
477 return;
478 }
479
480 match Vim::read(cx).active_operator() {
481 Some(Operator::FindForward { before }) => {
482 let find = Motion::FindForward {
483 before,
484 char: text.chars().next().unwrap(),
485 mode: if VimSettings::get_global(cx).use_multiline_find {
486 FindRange::MultiLine
487 } else {
488 FindRange::SingleLine
489 },
490 smartcase: VimSettings::get_global(cx).use_smartcase_find,
491 };
492 Vim::update(cx, |vim, _| {
493 vim.workspace_state.last_find = Some(find.clone())
494 });
495 motion::motion(find, cx)
496 }
497 Some(Operator::FindBackward { after }) => {
498 let find = Motion::FindBackward {
499 after,
500 char: text.chars().next().unwrap(),
501 mode: if VimSettings::get_global(cx).use_multiline_find {
502 FindRange::MultiLine
503 } else {
504 FindRange::SingleLine
505 },
506 smartcase: VimSettings::get_global(cx).use_smartcase_find,
507 };
508 Vim::update(cx, |vim, _| {
509 vim.workspace_state.last_find = Some(find.clone())
510 });
511 motion::motion(find, cx)
512 }
513 Some(Operator::Replace) => match Vim::read(cx).state().mode {
514 Mode::Normal => normal_replace(text, cx),
515 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => visual_replace(text, cx),
516 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
517 },
518 _ => {}
519 }
520 }
521
522 fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
523 if self.enabled == enabled {
524 return;
525 }
526 if !enabled {
527 let _ = cx.remove_global::<CommandPaletteInterceptor>();
528 cx.update_global::<CommandPaletteFilter, _>(|filter, _| {
529 filter.hidden_namespaces.insert("vim");
530 });
531 *self = Default::default();
532 return;
533 }
534
535 self.enabled = true;
536 cx.update_global::<CommandPaletteFilter, _>(|filter, _| {
537 filter.hidden_namespaces.remove("vim");
538 });
539 cx.set_global::<CommandPaletteInterceptor>(CommandPaletteInterceptor(Box::new(
540 command::command_interceptor,
541 )));
542
543 if let Some(active_window) = cx
544 .active_window()
545 .and_then(|window| window.downcast::<Workspace>())
546 {
547 active_window
548 .update(cx, |workspace, cx| {
549 let active_editor = workspace.active_item_as::<Editor>(cx);
550 if let Some(active_editor) = active_editor {
551 self.activate_editor(active_editor, cx);
552 self.switch_mode(Mode::Normal, false, cx);
553 }
554 })
555 .ok();
556 }
557 }
558
559 /// Returns the state of the active editor.
560 pub fn state(&self) -> &EditorState {
561 if let Some(active_editor) = self.active_editor.as_ref() {
562 if let Some(state) = self.editor_states.get(&active_editor.entity_id()) {
563 return state;
564 }
565 }
566
567 &self.default_state
568 }
569
570 /// Updates the state of the active editor.
571 pub fn update_state<T>(&mut self, func: impl FnOnce(&mut EditorState) -> T) -> T {
572 let mut state = self.state().clone();
573 let ret = func(&mut state);
574
575 if let Some(active_editor) = self.active_editor.as_ref() {
576 self.editor_states.insert(active_editor.entity_id(), state);
577 }
578
579 ret
580 }
581
582 fn sync_vim_settings(&mut self, cx: &mut WindowContext) {
583 self.update_active_editor(cx, |vim, editor, cx| {
584 let state = vim.state();
585 editor.set_cursor_shape(state.cursor_shape(), cx);
586 editor.set_clip_at_line_ends(state.clip_at_line_ends(), cx);
587 editor.set_collapse_matches(true);
588 editor.set_input_enabled(!state.vim_controlled());
589 editor.set_autoindent(state.should_autoindent());
590 editor.selections.line_mode = matches!(state.mode, Mode::VisualLine);
591 if editor.is_focused(cx) {
592 editor.set_keymap_context_layer::<Self>(state.keymap_context_layer(), cx);
593 } else {
594 editor.remove_keymap_context_layer::<Self>(cx);
595 }
596 });
597 }
598
599 fn unhook_vim_settings(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
600 if editor.mode() == EditorMode::Full {
601 editor.set_cursor_shape(CursorShape::Bar, cx);
602 editor.set_clip_at_line_ends(false, cx);
603 editor.set_collapse_matches(false);
604 editor.set_input_enabled(true);
605 editor.set_autoindent(true);
606 editor.selections.line_mode = false;
607 }
608 editor.remove_keymap_context_layer::<Self>(cx)
609 }
610}
611
612impl Settings for VimModeSetting {
613 const KEY: Option<&'static str> = Some("vim_mode");
614
615 type FileContent = Option<bool>;
616
617 fn load(
618 default_value: &Self::FileContent,
619 user_values: &[&Self::FileContent],
620 _: &mut AppContext,
621 ) -> Result<Self> {
622 Ok(Self(user_values.iter().rev().find_map(|v| **v).unwrap_or(
623 default_value.ok_or_else(Self::missing_default)?,
624 )))
625 }
626}
627
628/// Controls when to use system clipboard.
629#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
630#[serde(rename_all = "snake_case")]
631pub enum UseSystemClipboard {
632 /// Don't use system clipboard.
633 Never,
634 /// Use system clipboard.
635 Always,
636 /// Use system clipboard for yank operations.
637 OnYank,
638}
639
640#[derive(Deserialize)]
641struct VimSettings {
642 // all vim uses vim clipboard
643 // vim always uses system cliupbaord
644 // some magic where yy is system and dd is not.
645 pub use_system_clipboard: UseSystemClipboard,
646 pub use_multiline_find: bool,
647 pub use_smartcase_find: bool,
648}
649
650#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
651struct VimSettingsContent {
652 pub use_system_clipboard: Option<UseSystemClipboard>,
653 pub use_multiline_find: Option<bool>,
654 pub use_smartcase_find: Option<bool>,
655}
656
657impl Settings for VimSettings {
658 const KEY: Option<&'static str> = Some("vim");
659
660 type FileContent = VimSettingsContent;
661
662 fn load(
663 default_value: &Self::FileContent,
664 user_values: &[&Self::FileContent],
665 _: &mut AppContext,
666 ) -> Result<Self> {
667 Self::load_via_json_merge(default_value, user_values)
668 }
669}
670
671fn local_selections_changed(
672 newest: Selection<usize>,
673 is_multicursor: bool,
674 cx: &mut WindowContext,
675) {
676 Vim::update(cx, |vim, cx| {
677 if vim.state().mode == Mode::Normal && !newest.is_empty() {
678 if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
679 vim.switch_mode(Mode::VisualBlock, false, cx);
680 } else {
681 vim.switch_mode(Mode::Visual, false, cx)
682 }
683 } else if newest.is_empty()
684 && !is_multicursor
685 && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&vim.state().mode)
686 {
687 vim.switch_mode(Mode::Normal, true, cx)
688 }
689 })
690}