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, Subscription, View, ViewContext,
24 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 activate_editor(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
201 if editor.read(cx).mode() != EditorMode::Full {
202 return;
203 }
204
205 self.active_editor = Some(editor.clone().downgrade());
206 self.editor_subscription = Some(cx.subscribe(&editor, |editor, event, cx| match event {
207 EditorEvent::SelectionsChanged { local: true } => {
208 let editor = editor.read(cx);
209 if editor.leader_peer_id().is_none() {
210 let newest = editor.selections.newest::<usize>(cx);
211 let is_multicursor = editor.selections.count() > 1;
212 local_selections_changed(newest, is_multicursor, cx);
213 }
214 }
215 EditorEvent::InputIgnored { text } => {
216 Vim::active_editor_input_ignored(text.clone(), cx);
217 Vim::record_insertion(text, None, cx)
218 }
219 EditorEvent::InputHandled {
220 text,
221 utf16_range_to_replace: range_to_replace,
222 } => Vim::record_insertion(text, range_to_replace.clone(), cx),
223 _ => {}
224 }));
225
226 let editor = editor.read(cx);
227 let editor_mode = editor.mode();
228 let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
229
230 if editor_mode == EditorMode::Full
231 && !newest_selection_empty
232 && self.state().mode == Mode::Normal
233 // When following someone, don't switch vim mode.
234 && editor.leader_peer_id().is_none()
235 {
236 self.switch_mode(Mode::Visual, true, cx);
237 }
238
239 self.sync_vim_settings(cx);
240 }
241
242 fn record_insertion(
243 text: &Arc<str>,
244 range_to_replace: Option<Range<isize>>,
245 cx: &mut WindowContext,
246 ) {
247 Vim::update(cx, |vim, _| {
248 if vim.workspace_state.recording {
249 vim.workspace_state
250 .recorded_actions
251 .push(ReplayableAction::Insertion {
252 text: text.clone(),
253 utf16_range_to_replace: range_to_replace,
254 });
255 if vim.workspace_state.stop_recording_after_next_action {
256 vim.workspace_state.recording = false;
257 vim.workspace_state.stop_recording_after_next_action = false;
258 }
259 }
260 });
261 }
262
263 fn update_active_editor<S>(
264 &self,
265 cx: &mut WindowContext,
266 update: impl FnOnce(&mut Editor, &mut ViewContext<Editor>) -> S,
267 ) -> Option<S> {
268 let editor = self.active_editor.clone()?.upgrade()?;
269 Some(editor.update(cx, update))
270 }
271
272 /// When doing an action that modifies the buffer, we start recording so that `.`
273 /// will replay the action.
274 pub fn start_recording(&mut self, cx: &mut WindowContext) {
275 if !self.workspace_state.replaying {
276 self.workspace_state.recording = true;
277 self.workspace_state.recorded_actions = Default::default();
278 self.workspace_state.recorded_count = None;
279
280 let selections = self
281 .active_editor
282 .as_ref()
283 .and_then(|editor| editor.upgrade())
284 .map(|editor| {
285 let editor = editor.read(cx);
286 (
287 editor.selections.oldest::<Point>(cx),
288 editor.selections.newest::<Point>(cx),
289 )
290 });
291
292 if let Some((oldest, newest)) = selections {
293 self.workspace_state.recorded_selection = match self.state().mode {
294 Mode::Visual if newest.end.row == newest.start.row => {
295 RecordedSelection::SingleLine {
296 cols: newest.end.column - newest.start.column,
297 }
298 }
299 Mode::Visual => RecordedSelection::Visual {
300 rows: newest.end.row - newest.start.row,
301 cols: newest.end.column,
302 },
303 Mode::VisualLine => RecordedSelection::VisualLine {
304 rows: newest.end.row - newest.start.row,
305 },
306 Mode::VisualBlock => RecordedSelection::VisualBlock {
307 rows: newest.end.row.abs_diff(oldest.start.row),
308 cols: newest.end.column.abs_diff(oldest.start.column),
309 },
310 _ => RecordedSelection::None,
311 }
312 } else {
313 self.workspace_state.recorded_selection = RecordedSelection::None;
314 }
315 }
316 }
317
318 /// When finishing an action that modifies the buffer, stop recording.
319 /// as you usually call this within a keystroke handler we also ensure that
320 /// the current action is recorded.
321 pub fn stop_recording(&mut self) {
322 if self.workspace_state.recording {
323 self.workspace_state.stop_recording_after_next_action = true;
324 }
325 }
326
327 /// Stops recording actions immediately rather than waiting until after the
328 /// next action to stop recording.
329 ///
330 /// This doesn't include the current action.
331 pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>) {
332 if self.workspace_state.recording {
333 self.workspace_state
334 .recorded_actions
335 .push(ReplayableAction::Action(action.boxed_clone()));
336 self.workspace_state.recording = false;
337 self.workspace_state.stop_recording_after_next_action = false;
338 }
339 }
340
341 /// Explicitly record one action (equivalents to start_recording and stop_recording)
342 pub fn record_current_action(&mut self, cx: &mut WindowContext) {
343 self.start_recording(cx);
344 self.stop_recording();
345 }
346
347 fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut WindowContext) {
348 let state = self.state();
349 let last_mode = state.mode;
350 let prior_mode = state.last_mode;
351 self.update_state(|state| {
352 state.last_mode = last_mode;
353 state.mode = mode;
354 state.operator_stack.clear();
355 });
356 if mode != Mode::Insert {
357 self.take_count(cx);
358 }
359
360 // Sync editor settings like clip mode
361 self.sync_vim_settings(cx);
362
363 if leave_selections {
364 return;
365 }
366
367 // Adjust selections
368 self.update_active_editor(cx, |editor, cx| {
369 if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
370 {
371 visual_block_motion(true, editor, cx, |_, point, goal| Some((point, goal)))
372 }
373
374 editor.change_selections(None, cx, |s| {
375 // we cheat with visual block mode and use multiple cursors.
376 // the cost of this cheat is we need to convert back to a single
377 // cursor whenever vim would.
378 if last_mode == Mode::VisualBlock
379 && (mode != Mode::VisualBlock && mode != Mode::Insert)
380 {
381 let tail = s.oldest_anchor().tail();
382 let head = s.newest_anchor().head();
383 s.select_anchor_ranges(vec![tail..head]);
384 } else if last_mode == Mode::Insert
385 && prior_mode == Mode::VisualBlock
386 && mode != Mode::VisualBlock
387 {
388 let pos = s.first_anchor().head();
389 s.select_anchor_ranges(vec![pos..pos])
390 }
391
392 s.move_with(|map, selection| {
393 if last_mode.is_visual() && !mode.is_visual() {
394 let mut point = selection.head();
395 if !selection.reversed && !selection.is_empty() {
396 point = movement::left(map, selection.head());
397 }
398 selection.collapse_to(point, selection.goal)
399 } else if !last_mode.is_visual() && mode.is_visual() {
400 if selection.is_empty() {
401 selection.end = movement::right(map, selection.start);
402 }
403 }
404 });
405 })
406 });
407 }
408
409 fn push_count_digit(&mut self, number: usize, cx: &mut WindowContext) {
410 if self.active_operator().is_some() {
411 self.update_state(|state| {
412 state.post_count = Some(state.post_count.unwrap_or(0) * 10 + number)
413 })
414 } else {
415 self.update_state(|state| {
416 state.pre_count = Some(state.pre_count.unwrap_or(0) * 10 + number)
417 })
418 }
419 // update the keymap so that 0 works
420 self.sync_vim_settings(cx)
421 }
422
423 fn take_count(&mut self, cx: &mut WindowContext) -> Option<usize> {
424 if self.workspace_state.replaying {
425 return self.workspace_state.recorded_count;
426 }
427
428 let count = if self.state().post_count == None && self.state().pre_count == None {
429 return None;
430 } else {
431 Some(self.update_state(|state| {
432 state.post_count.take().unwrap_or(1) * state.pre_count.take().unwrap_or(1)
433 }))
434 };
435 if self.workspace_state.recording {
436 self.workspace_state.recorded_count = count;
437 }
438 self.sync_vim_settings(cx);
439 count
440 }
441
442 fn push_operator(&mut self, operator: Operator, cx: &mut WindowContext) {
443 if matches!(
444 operator,
445 Operator::Change | Operator::Delete | Operator::Replace
446 ) {
447 self.start_recording(cx)
448 };
449 self.update_state(|state| state.operator_stack.push(operator));
450 self.sync_vim_settings(cx);
451 }
452
453 fn maybe_pop_operator(&mut self) -> Option<Operator> {
454 self.update_state(|state| state.operator_stack.pop())
455 }
456
457 fn pop_operator(&mut self, cx: &mut WindowContext) -> Operator {
458 let popped_operator = self.update_state( |state| state.operator_stack.pop()
459 ) .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
460 self.sync_vim_settings(cx);
461 popped_operator
462 }
463 fn clear_operator(&mut self, cx: &mut WindowContext) {
464 self.take_count(cx);
465 self.update_state(|state| state.operator_stack.clear());
466 self.sync_vim_settings(cx);
467 }
468
469 fn active_operator(&self) -> Option<Operator> {
470 self.state().operator_stack.last().copied()
471 }
472
473 fn active_editor_input_ignored(text: Arc<str>, cx: &mut WindowContext) {
474 if text.is_empty() {
475 return;
476 }
477
478 match Vim::read(cx).active_operator() {
479 Some(Operator::FindForward { before }) => {
480 let find = Motion::FindForward {
481 before,
482 char: text.chars().next().unwrap(),
483 };
484 Vim::update(cx, |vim, _| {
485 vim.workspace_state.last_find = Some(find.clone())
486 });
487 motion::motion(find, cx)
488 }
489 Some(Operator::FindBackward { after }) => {
490 let find = Motion::FindBackward {
491 after,
492 char: text.chars().next().unwrap(),
493 };
494 Vim::update(cx, |vim, _| {
495 vim.workspace_state.last_find = Some(find.clone())
496 });
497 motion::motion(find, cx)
498 }
499 Some(Operator::Replace) => match Vim::read(cx).state().mode {
500 Mode::Normal => normal_replace(text, cx),
501 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => visual_replace(text, cx),
502 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
503 },
504 _ => {}
505 }
506 }
507
508 fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
509 if self.enabled == enabled {
510 return;
511 }
512 if !enabled {
513 let _ = cx.remove_global::<CommandPaletteInterceptor>();
514 cx.update_global::<CommandPaletteFilter, _>(|filter, _| {
515 filter.hidden_namespaces.insert("vim");
516 });
517 *self = Default::default();
518 return;
519 }
520
521 self.enabled = true;
522 cx.update_global::<CommandPaletteFilter, _>(|filter, _| {
523 filter.hidden_namespaces.remove("vim");
524 });
525 cx.set_global::<CommandPaletteInterceptor>(CommandPaletteInterceptor(Box::new(
526 command::command_interceptor,
527 )));
528
529 if let Some(active_window) = cx
530 .active_window()
531 .and_then(|window| window.downcast::<Workspace>())
532 {
533 active_window
534 .update(cx, |workspace, cx| {
535 let active_editor = workspace.active_item_as::<Editor>(cx);
536 if let Some(active_editor) = active_editor {
537 self.activate_editor(active_editor, cx);
538 self.switch_mode(Mode::Normal, false, cx);
539 }
540 })
541 .ok();
542 }
543 }
544
545 /// Returns the state of the active editor.
546 pub fn state(&self) -> &EditorState {
547 if let Some(active_editor) = self.active_editor.as_ref() {
548 if let Some(state) = self.editor_states.get(&active_editor.entity_id()) {
549 return state;
550 }
551 }
552
553 &self.default_state
554 }
555
556 /// Updates the state of the active editor.
557 pub fn update_state<T>(&mut self, func: impl FnOnce(&mut EditorState) -> T) -> T {
558 let mut state = self.state().clone();
559 let ret = func(&mut state);
560
561 if let Some(active_editor) = self.active_editor.as_ref() {
562 self.editor_states.insert(active_editor.entity_id(), state);
563 }
564
565 ret
566 }
567
568 fn sync_vim_settings(&self, cx: &mut WindowContext) {
569 let state = self.state();
570
571 self.update_active_editor(cx, |editor, cx| {
572 editor.set_cursor_shape(state.cursor_shape(), cx);
573 editor.set_clip_at_line_ends(state.clip_at_line_ends(), cx);
574 editor.set_collapse_matches(true);
575 editor.set_input_enabled(!state.vim_controlled());
576 editor.set_autoindent(state.should_autoindent());
577 editor.selections.line_mode = matches!(state.mode, Mode::VisualLine);
578 let context_layer = state.keymap_context_layer();
579 editor.set_keymap_context_layer::<Self>(context_layer, cx);
580 });
581 }
582
583 fn unhook_vim_settings(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
584 if editor.mode() == EditorMode::Full {
585 editor.set_cursor_shape(CursorShape::Bar, cx);
586 editor.set_clip_at_line_ends(false, cx);
587 editor.set_collapse_matches(false);
588 editor.set_input_enabled(true);
589 editor.set_autoindent(true);
590 editor.selections.line_mode = false;
591 }
592 editor.remove_keymap_context_layer::<Self>(cx)
593 }
594}
595
596impl Settings for VimModeSetting {
597 const KEY: Option<&'static str> = Some("vim_mode");
598
599 type FileContent = Option<bool>;
600
601 fn load(
602 default_value: &Self::FileContent,
603 user_values: &[&Self::FileContent],
604 _: &mut AppContext,
605 ) -> Result<Self> {
606 Ok(Self(user_values.iter().rev().find_map(|v| **v).unwrap_or(
607 default_value.ok_or_else(Self::missing_default)?,
608 )))
609 }
610}
611
612fn local_selections_changed(
613 newest: Selection<usize>,
614 is_multicursor: bool,
615 cx: &mut WindowContext,
616) {
617 Vim::update(cx, |vim, cx| {
618 if vim.state().mode == Mode::Normal && !newest.is_empty() {
619 if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
620 vim.switch_mode(Mode::VisualBlock, false, cx);
621 } else {
622 vim.switch_mode(Mode::Visual, false, cx)
623 }
624 } else if newest.is_empty()
625 && !is_multicursor
626 && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&vim.state().mode)
627 {
628 vim.switch_mode(Mode::Normal, true, cx)
629 }
630 })
631}