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