1//! Vim support for Zed.
2
3#[cfg(test)]
4mod test;
5
6mod change_list;
7mod command;
8mod digraph;
9mod insert;
10mod mode_indicator;
11mod motion;
12mod normal;
13mod object;
14mod replace;
15mod state;
16mod surrounds;
17mod visual;
18
19use anyhow::Result;
20use collections::HashMap;
21use editor::{
22 movement::{self, FindRange},
23 Anchor, Bias, Editor, EditorEvent, EditorMode, ToPoint,
24};
25use gpui::{
26 actions, impl_actions, Action, AppContext, Entity, EventEmitter, KeyContext, KeystrokeEvent,
27 Render, View, ViewContext, WeakView,
28};
29use insert::NormalBefore;
30use language::{CursorShape, Point, Selection, SelectionGoal, TransactionId};
31pub use mode_indicator::ModeIndicator;
32use motion::Motion;
33use normal::search::SearchSubmit;
34use schemars::JsonSchema;
35use serde::Deserialize;
36use serde_derive::Serialize;
37use settings::{update_settings_file, Settings, SettingsSources, SettingsStore};
38use state::{Mode, Operator, RecordedSelection, SearchState, VimGlobals};
39use std::{ops::Range, sync::Arc};
40use surrounds::SurroundsType;
41use ui::{IntoElement, VisualContext};
42use workspace::{self, Pane, Workspace};
43
44use crate::state::ReplayableAction;
45
46/// Whether or not to enable Vim mode.
47///
48/// Default: false
49pub struct VimModeSetting(pub bool);
50
51/// An Action to Switch between modes
52#[derive(Clone, Deserialize, PartialEq)]
53pub struct SwitchMode(pub Mode);
54
55/// PushOperator is used to put vim into a "minor" mode,
56/// where it's waiting for a specific next set of keystrokes.
57/// For example 'd' needs a motion to complete.
58#[derive(Clone, Deserialize, PartialEq)]
59pub struct PushOperator(pub Operator);
60
61/// Number is used to manage vim's count. Pushing a digit
62/// multiplis the current value by 10 and adds the digit.
63#[derive(Clone, Deserialize, PartialEq)]
64struct Number(usize);
65
66#[derive(Clone, Deserialize, PartialEq)]
67struct SelectRegister(String);
68
69actions!(
70 vim,
71 [
72 ClearOperators,
73 Tab,
74 Enter,
75 Object,
76 InnerObject,
77 FindForward,
78 FindBackward,
79 OpenDefaultKeymap
80 ]
81);
82
83// in the workspace namespace so it's not filtered out when vim is disabled.
84actions!(workspace, [ToggleVimMode]);
85
86impl_actions!(vim, [SwitchMode, PushOperator, Number, SelectRegister]);
87
88/// Initializes the `vim` crate.
89pub fn init(cx: &mut AppContext) {
90 VimModeSetting::register(cx);
91 VimSettings::register(cx);
92 VimGlobals::register(cx);
93
94 cx.observe_new_views(|editor: &mut Editor, cx| Vim::register(editor, cx))
95 .detach();
96
97 cx.observe_new_views(|workspace: &mut Workspace, _| {
98 workspace.register_action(|workspace, _: &ToggleVimMode, cx| {
99 let fs = workspace.app_state().fs.clone();
100 let currently_enabled = Vim::enabled(cx);
101 update_settings_file::<VimModeSetting>(fs, cx, move |setting, _| {
102 *setting = Some(!currently_enabled)
103 })
104 });
105
106 workspace.register_action(|_, _: &OpenDefaultKeymap, cx| {
107 cx.emit(workspace::Event::OpenBundledFile {
108 text: settings::vim_keymap(),
109 title: "Default Vim Bindings",
110 language: "JSON",
111 });
112 });
113
114 workspace.register_action(|workspace, _: &SearchSubmit, cx| {
115 let Some(vim) = workspace
116 .active_item_as::<Editor>(cx)
117 .and_then(|editor| editor.read(cx).addon::<VimAddon>().cloned())
118 else {
119 return;
120 };
121 vim.view
122 .update(cx, |_, cx| cx.defer(|vim, cx| vim.search_submit(cx)))
123 });
124 })
125 .detach();
126}
127
128#[derive(Clone)]
129pub(crate) struct VimAddon {
130 pub(crate) view: View<Vim>,
131}
132
133impl editor::Addon for VimAddon {
134 fn extend_key_context(&self, key_context: &mut KeyContext, cx: &AppContext) {
135 self.view.read(cx).extend_key_context(key_context)
136 }
137
138 fn to_any(&self) -> &dyn std::any::Any {
139 self
140 }
141}
142
143/// The state pertaining to Vim mode.
144pub(crate) struct Vim {
145 pub(crate) mode: Mode,
146 pub last_mode: Mode,
147
148 /// pre_count is the number before an operator is specified (3 in 3d2d)
149 pre_count: Option<usize>,
150 /// post_count is the number after an operator is specified (2 in 3d2d)
151 post_count: Option<usize>,
152
153 operator_stack: Vec<Operator>,
154 pub(crate) replacements: Vec<(Range<editor::Anchor>, String)>,
155
156 pub(crate) marks: HashMap<String, Vec<Anchor>>,
157 pub(crate) stored_visual_mode: Option<(Mode, Vec<bool>)>,
158 pub(crate) change_list: Vec<Vec<Anchor>>,
159 pub(crate) change_list_position: Option<usize>,
160
161 pub(crate) current_tx: Option<TransactionId>,
162 pub(crate) current_anchor: Option<Selection<Anchor>>,
163 pub(crate) undo_modes: HashMap<TransactionId, Mode>,
164
165 selected_register: Option<char>,
166 pub search: SearchState,
167
168 editor: WeakView<Editor>,
169}
170
171// Hack: Vim intercepts events dispatched to a window and updates the view in response.
172// This means it needs a VisualContext. The easiest way to satisfy that constraint is
173// to make Vim a "View" that is just never actually rendered.
174impl Render for Vim {
175 fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
176 gpui::Empty
177 }
178}
179
180enum VimEvent {
181 Focused,
182}
183impl EventEmitter<VimEvent> for Vim {}
184
185impl Vim {
186 /// The namespace for Vim actions.
187 const NAMESPACE: &'static str = "vim";
188
189 pub fn new(cx: &mut ViewContext<Editor>) -> View<Self> {
190 let editor = cx.view().clone();
191
192 cx.new_view(|cx: &mut ViewContext<Vim>| {
193 cx.subscribe(&editor, |vim, _, event, cx| {
194 vim.handle_editor_event(event, cx)
195 })
196 .detach();
197
198 let listener = cx.listener(Vim::observe_keystrokes);
199 cx.observe_keystrokes(listener).detach();
200
201 Vim {
202 mode: Mode::Normal,
203 last_mode: Mode::Normal,
204 pre_count: None,
205 post_count: None,
206 operator_stack: Vec::new(),
207 replacements: Vec::new(),
208
209 marks: HashMap::default(),
210 stored_visual_mode: None,
211 change_list: Vec::new(),
212 change_list_position: None,
213 current_tx: None,
214 current_anchor: None,
215 undo_modes: HashMap::default(),
216
217 selected_register: None,
218 search: SearchState::default(),
219
220 editor: editor.downgrade(),
221 }
222 })
223 }
224
225 fn register(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
226 if !editor.use_modal_editing() {
227 return;
228 }
229
230 let mut was_enabled = Vim::enabled(cx);
231 let mut was_toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;
232 cx.observe_global::<SettingsStore>(move |editor, cx| {
233 let enabled = Vim::enabled(cx);
234 let toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;
235 if enabled && was_enabled && (toggle != was_toggle) {
236 if toggle {
237 let is_relative = editor
238 .addon::<VimAddon>()
239 .map(|vim| vim.view.read(cx).mode != Mode::Insert);
240 editor.set_relative_line_number(is_relative, cx)
241 } else {
242 editor.set_relative_line_number(None, cx)
243 }
244 }
245 was_toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;
246 if was_enabled == enabled {
247 return;
248 }
249 was_enabled = enabled;
250 if enabled {
251 Self::activate(editor, cx)
252 } else {
253 Self::deactivate(editor, cx)
254 }
255 })
256 .detach();
257 if was_enabled {
258 Self::activate(editor, cx)
259 }
260 }
261
262 fn activate(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
263 let vim = Vim::new(cx);
264
265 editor.register_addon(VimAddon { view: vim.clone() });
266
267 vim.update(cx, |_, cx| {
268 Vim::action(editor, cx, |vim, action: &SwitchMode, cx| {
269 vim.switch_mode(action.0, false, cx)
270 });
271
272 Vim::action(editor, cx, |vim, action: &PushOperator, cx| {
273 vim.push_operator(action.0.clone(), cx)
274 });
275
276 Vim::action(editor, cx, |vim, _: &ClearOperators, cx| {
277 vim.clear_operator(cx)
278 });
279 Vim::action(editor, cx, |vim, n: &Number, cx| {
280 vim.push_count_digit(n.0, cx);
281 });
282 Vim::action(editor, cx, |vim, _: &Tab, cx| {
283 vim.input_ignored(" ".into(), cx)
284 });
285 Vim::action(editor, cx, |vim, _: &Enter, cx| {
286 vim.input_ignored("\n".into(), cx)
287 });
288
289 normal::register(editor, cx);
290 insert::register(editor, cx);
291 motion::register(editor, cx);
292 command::register(editor, cx);
293 replace::register(editor, cx);
294 object::register(editor, cx);
295 visual::register(editor, cx);
296 change_list::register(editor, cx);
297
298 cx.defer(|vim, cx| {
299 vim.focused(false, cx);
300 })
301 })
302 }
303
304 fn deactivate(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
305 editor.set_cursor_shape(CursorShape::Bar, cx);
306 editor.set_clip_at_line_ends(false, cx);
307 editor.set_collapse_matches(false);
308 editor.set_input_enabled(true);
309 editor.set_autoindent(true);
310 editor.selections.line_mode = false;
311 editor.unregister_addon::<VimAddon>();
312 editor.set_relative_line_number(None, cx)
313 }
314
315 /// Register an action on the editor.
316 pub fn action<A: Action>(
317 editor: &mut Editor,
318 cx: &mut ViewContext<Vim>,
319 f: impl Fn(&mut Vim, &A, &mut ViewContext<Vim>) + 'static,
320 ) {
321 let subscription = editor.register_action(cx.listener(f));
322 cx.on_release(|_, _, _| drop(subscription)).detach();
323 }
324
325 pub fn editor(&self) -> Option<View<Editor>> {
326 self.editor.upgrade()
327 }
328
329 pub fn workspace(&self, cx: &ViewContext<Self>) -> Option<View<Workspace>> {
330 self.editor().and_then(|editor| editor.read(cx).workspace())
331 }
332
333 pub fn pane(&self, cx: &ViewContext<Self>) -> Option<View<Pane>> {
334 self.workspace(cx)
335 .and_then(|workspace| workspace.read(cx).pane_for(&self.editor()?))
336 }
337
338 pub fn enabled(cx: &mut AppContext) -> bool {
339 VimModeSetting::get_global(cx).0
340 }
341
342 /// Called whenever an keystroke is typed so vim can observe all actions
343 /// and keystrokes accordingly.
344 fn observe_keystrokes(&mut self, keystroke_event: &KeystrokeEvent, cx: &mut ViewContext<Self>) {
345 if let Some(action) = keystroke_event.action.as_ref() {
346 // Keystroke is handled by the vim system, so continue forward
347 if action.name().starts_with("vim::") {
348 return;
349 }
350 } else if cx.has_pending_keystrokes() || keystroke_event.keystroke.is_ime_in_progress() {
351 return;
352 }
353
354 if let Some(operator) = self.active_operator() {
355 if !operator.is_waiting(self.mode) {
356 self.clear_operator(cx);
357 self.stop_recording_immediately(Box::new(ClearOperators), cx)
358 }
359 }
360 }
361
362 fn handle_editor_event(&mut self, event: &EditorEvent, cx: &mut ViewContext<Self>) {
363 match event {
364 EditorEvent::Focused => self.focused(true, cx),
365 EditorEvent::Blurred => self.blurred(cx),
366 EditorEvent::SelectionsChanged { local: true } => {
367 self.local_selections_changed(cx);
368 }
369 EditorEvent::InputIgnored { text } => {
370 self.input_ignored(text.clone(), cx);
371 Vim::globals(cx).observe_insertion(text, None)
372 }
373 EditorEvent::InputHandled {
374 text,
375 utf16_range_to_replace: range_to_replace,
376 } => Vim::globals(cx).observe_insertion(text, range_to_replace.clone()),
377 EditorEvent::TransactionBegun { transaction_id } => {
378 self.transaction_begun(*transaction_id, cx)
379 }
380 EditorEvent::TransactionUndone { transaction_id } => {
381 self.transaction_undone(transaction_id, cx)
382 }
383 EditorEvent::Edited { .. } => self.push_to_change_list(cx),
384 EditorEvent::FocusedIn => self.sync_vim_settings(cx),
385 _ => {}
386 }
387 }
388
389 fn push_operator(&mut self, operator: Operator, cx: &mut ViewContext<Self>) {
390 if matches!(
391 operator,
392 Operator::Change
393 | Operator::Delete
394 | Operator::Replace
395 | Operator::Indent
396 | Operator::Outdent
397 | Operator::Lowercase
398 | Operator::Uppercase
399 | Operator::OppositeCase
400 | Operator::ToggleComments
401 ) {
402 self.start_recording(cx)
403 };
404 // Since these operations can only be entered with pre-operators,
405 // we need to clear the previous operators when pushing,
406 // so that the current stack is the most correct
407 if matches!(
408 operator,
409 Operator::AddSurrounds { .. }
410 | Operator::ChangeSurrounds { .. }
411 | Operator::DeleteSurrounds
412 ) {
413 self.operator_stack.clear();
414 if let Operator::AddSurrounds { target: None } = operator {
415 self.start_recording(cx);
416 }
417 };
418 self.operator_stack.push(operator);
419 self.sync_vim_settings(cx);
420 }
421
422 pub fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut ViewContext<Self>) {
423 let last_mode = self.mode;
424 let prior_mode = self.last_mode;
425 let prior_tx = self.current_tx;
426 self.last_mode = last_mode;
427 self.mode = mode;
428 self.operator_stack.clear();
429 self.selected_register.take();
430 if mode == Mode::Normal || mode != last_mode {
431 self.current_tx.take();
432 self.current_anchor.take();
433 }
434 if mode != Mode::Insert && mode != Mode::Replace {
435 self.take_count(cx);
436 }
437
438 // Sync editor settings like clip mode
439 self.sync_vim_settings(cx);
440
441 if VimSettings::get_global(cx).toggle_relative_line_numbers {
442 if self.mode != self.last_mode {
443 if self.mode == Mode::Insert || self.last_mode == Mode::Insert {
444 self.update_editor(cx, |vim, editor, cx| {
445 let is_relative = vim.mode != Mode::Insert;
446 editor.set_relative_line_number(Some(is_relative), cx)
447 });
448 }
449 }
450 }
451
452 if leave_selections {
453 return;
454 }
455
456 if !mode.is_visual() && last_mode.is_visual() {
457 self.create_visual_marks(last_mode, cx);
458 }
459
460 // Adjust selections
461 self.update_editor(cx, |vim, editor, cx| {
462 if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
463 {
464 vim.visual_block_motion(true, editor, cx, |_, point, goal| Some((point, goal)))
465 }
466 if last_mode == Mode::Insert || last_mode == Mode::Replace {
467 if let Some(prior_tx) = prior_tx {
468 editor.group_until_transaction(prior_tx, cx)
469 }
470 }
471
472 editor.change_selections(None, cx, |s| {
473 // we cheat with visual block mode and use multiple cursors.
474 // the cost of this cheat is we need to convert back to a single
475 // cursor whenever vim would.
476 if last_mode == Mode::VisualBlock
477 && (mode != Mode::VisualBlock && mode != Mode::Insert)
478 {
479 let tail = s.oldest_anchor().tail();
480 let head = s.newest_anchor().head();
481 s.select_anchor_ranges(vec![tail..head]);
482 } else if last_mode == Mode::Insert
483 && prior_mode == Mode::VisualBlock
484 && mode != Mode::VisualBlock
485 {
486 let pos = s.first_anchor().head();
487 s.select_anchor_ranges(vec![pos..pos])
488 }
489
490 let snapshot = s.display_map();
491 if let Some(pending) = s.pending.as_mut() {
492 if pending.selection.reversed && mode.is_visual() && !last_mode.is_visual() {
493 let mut end = pending.selection.end.to_point(&snapshot.buffer_snapshot);
494 end = snapshot
495 .buffer_snapshot
496 .clip_point(end + Point::new(0, 1), Bias::Right);
497 pending.selection.end = snapshot.buffer_snapshot.anchor_before(end);
498 }
499 }
500
501 s.move_with(|map, selection| {
502 if last_mode.is_visual() && !mode.is_visual() {
503 let mut point = selection.head();
504 if !selection.reversed && !selection.is_empty() {
505 point = movement::left(map, selection.head());
506 }
507 selection.collapse_to(point, selection.goal)
508 } else if !last_mode.is_visual() && mode.is_visual() {
509 if selection.is_empty() {
510 selection.end = movement::right(map, selection.start);
511 }
512 }
513 });
514 })
515 });
516 }
517
518 fn take_count(&mut self, cx: &mut ViewContext<Self>) -> Option<usize> {
519 let global_state = cx.global_mut::<VimGlobals>();
520 if global_state.dot_replaying {
521 return global_state.recorded_count;
522 }
523
524 let count = if self.post_count == None && self.pre_count == None {
525 return None;
526 } else {
527 Some(self.post_count.take().unwrap_or(1) * self.pre_count.take().unwrap_or(1))
528 };
529
530 if global_state.dot_recording {
531 global_state.recorded_count = count;
532 }
533 self.sync_vim_settings(cx);
534 count
535 }
536
537 pub fn cursor_shape(&self) -> CursorShape {
538 match self.mode {
539 Mode::Normal => {
540 if self.operator_stack.is_empty() {
541 CursorShape::Block
542 } else {
543 CursorShape::Underscore
544 }
545 }
546 Mode::Replace => CursorShape::Underscore,
547 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => CursorShape::Block,
548 Mode::Insert => CursorShape::Bar,
549 }
550 }
551
552 pub fn editor_input_enabled(&self) -> bool {
553 match self.mode {
554 Mode::Insert => {
555 if let Some(operator) = self.operator_stack.last() {
556 !operator.is_waiting(self.mode)
557 } else {
558 true
559 }
560 }
561 Mode::Normal | Mode::Replace | Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
562 false
563 }
564 }
565 }
566
567 pub fn should_autoindent(&self) -> bool {
568 !(self.mode == Mode::Insert && self.last_mode == Mode::VisualBlock)
569 }
570
571 pub fn clip_at_line_ends(&self) -> bool {
572 match self.mode {
573 Mode::Insert | Mode::Visual | Mode::VisualLine | Mode::VisualBlock | Mode::Replace => {
574 false
575 }
576 Mode::Normal => true,
577 }
578 }
579
580 pub fn extend_key_context(&self, context: &mut KeyContext) {
581 let mut mode = match self.mode {
582 Mode::Normal => "normal",
583 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => "visual",
584 Mode::Insert => "insert",
585 Mode::Replace => "replace",
586 }
587 .to_string();
588
589 let mut operator_id = "none";
590
591 let active_operator = self.active_operator();
592 if active_operator.is_none() && self.pre_count.is_some()
593 || active_operator.is_some() && self.post_count.is_some()
594 {
595 context.add("VimCount");
596 }
597
598 if let Some(active_operator) = active_operator {
599 if active_operator.is_waiting(self.mode) {
600 mode = "waiting".to_string();
601 } else {
602 mode = "operator".to_string();
603 operator_id = active_operator.id();
604 }
605 }
606
607 if mode != "waiting" && mode != "insert" && mode != "replace" {
608 context.add("VimControl");
609 }
610 context.set("vim_mode", mode);
611 context.set("vim_operator", operator_id);
612 }
613
614 fn focused(&mut self, preserve_selection: bool, cx: &mut ViewContext<Self>) {
615 let Some(editor) = self.editor() else {
616 return;
617 };
618 let editor = editor.read(cx);
619 let editor_mode = editor.mode();
620 let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
621
622 if editor_mode == EditorMode::Full
623 && !newest_selection_empty
624 && self.mode == Mode::Normal
625 // When following someone, don't switch vim mode.
626 && editor.leader_peer_id().is_none()
627 {
628 if preserve_selection {
629 self.switch_mode(Mode::Visual, true, cx);
630 } else {
631 self.update_editor(cx, |_, editor, cx| {
632 editor.set_clip_at_line_ends(false, cx);
633 editor.change_selections(None, cx, |s| {
634 s.move_with(|_, selection| {
635 selection.collapse_to(selection.start, selection.goal)
636 })
637 });
638 });
639 }
640 }
641
642 cx.emit(VimEvent::Focused);
643 self.sync_vim_settings(cx);
644
645 if VimSettings::get_global(cx).toggle_relative_line_numbers {
646 if let Some(old_vim) = Vim::globals(cx).focused_vim() {
647 if old_vim.entity_id() != cx.view().entity_id() {
648 old_vim.update(cx, |vim, cx| {
649 vim.update_editor(cx, |_, editor, cx| {
650 editor.set_relative_line_number(None, cx)
651 });
652 });
653
654 self.update_editor(cx, |vim, editor, cx| {
655 let is_relative = vim.mode != Mode::Insert;
656 editor.set_relative_line_number(Some(is_relative), cx)
657 });
658 }
659 }
660 }
661 Vim::globals(cx).focused_vim = Some(cx.view().downgrade());
662 }
663
664 fn blurred(&mut self, cx: &mut ViewContext<Self>) {
665 self.stop_recording_immediately(NormalBefore.boxed_clone(), cx);
666 self.store_visual_marks(cx);
667 self.clear_operator(cx);
668 self.update_editor(cx, |_, editor, cx| {
669 editor.set_cursor_shape(language::CursorShape::Hollow, cx);
670 });
671 }
672
673 fn update_editor<S>(
674 &mut self,
675 cx: &mut ViewContext<Self>,
676 update: impl FnOnce(&mut Self, &mut Editor, &mut ViewContext<Editor>) -> S,
677 ) -> Option<S> {
678 let editor = self.editor.upgrade()?;
679 Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
680 }
681
682 fn editor_selections(&mut self, cx: &mut ViewContext<Self>) -> Vec<Range<Anchor>> {
683 self.update_editor(cx, |_, editor, _| {
684 editor
685 .selections
686 .disjoint_anchors()
687 .iter()
688 .map(|selection| selection.tail()..selection.head())
689 .collect()
690 })
691 .unwrap_or_default()
692 }
693
694 /// When doing an action that modifies the buffer, we start recording so that `.`
695 /// will replay the action.
696 pub fn start_recording(&mut self, cx: &mut ViewContext<Self>) {
697 Vim::update_globals(cx, |globals, cx| {
698 if !globals.dot_replaying {
699 globals.dot_recording = true;
700 globals.recorded_actions = Default::default();
701 globals.recorded_count = None;
702
703 let selections = self.editor().map(|editor| {
704 let editor = editor.read(cx);
705 (
706 editor.selections.oldest::<Point>(cx),
707 editor.selections.newest::<Point>(cx),
708 )
709 });
710
711 if let Some((oldest, newest)) = selections {
712 globals.recorded_selection = match self.mode {
713 Mode::Visual if newest.end.row == newest.start.row => {
714 RecordedSelection::SingleLine {
715 cols: newest.end.column - newest.start.column,
716 }
717 }
718 Mode::Visual => RecordedSelection::Visual {
719 rows: newest.end.row - newest.start.row,
720 cols: newest.end.column,
721 },
722 Mode::VisualLine => RecordedSelection::VisualLine {
723 rows: newest.end.row - newest.start.row,
724 },
725 Mode::VisualBlock => RecordedSelection::VisualBlock {
726 rows: newest.end.row.abs_diff(oldest.start.row),
727 cols: newest.end.column.abs_diff(oldest.start.column),
728 },
729 _ => RecordedSelection::None,
730 }
731 } else {
732 globals.recorded_selection = RecordedSelection::None;
733 }
734 }
735 })
736 }
737
738 pub fn stop_replaying(&mut self, cx: &mut ViewContext<Self>) {
739 let globals = Vim::globals(cx);
740 globals.dot_replaying = false;
741 if let Some(replayer) = globals.replayer.take() {
742 replayer.stop();
743 }
744 }
745
746 /// When finishing an action that modifies the buffer, stop recording.
747 /// as you usually call this within a keystroke handler we also ensure that
748 /// the current action is recorded.
749 pub fn stop_recording(&mut self, cx: &mut ViewContext<Self>) {
750 let globals = Vim::globals(cx);
751 if globals.dot_recording {
752 globals.stop_recording_after_next_action = true;
753 }
754 }
755
756 /// Stops recording actions immediately rather than waiting until after the
757 /// next action to stop recording.
758 ///
759 /// This doesn't include the current action.
760 pub fn stop_recording_immediately(
761 &mut self,
762 action: Box<dyn Action>,
763 cx: &mut ViewContext<Self>,
764 ) {
765 let globals = Vim::globals(cx);
766 if globals.dot_recording {
767 globals
768 .recorded_actions
769 .push(ReplayableAction::Action(action.boxed_clone()));
770 globals.dot_recording = false;
771 globals.stop_recording_after_next_action = false;
772 }
773 }
774
775 /// Explicitly record one action (equivalents to start_recording and stop_recording)
776 pub fn record_current_action(&mut self, cx: &mut ViewContext<Self>) {
777 self.start_recording(cx);
778 self.stop_recording(cx);
779 }
780
781 fn push_count_digit(&mut self, number: usize, cx: &mut ViewContext<Self>) {
782 if self.active_operator().is_some() {
783 let post_count = self.post_count.unwrap_or(0);
784
785 self.post_count = Some(
786 post_count
787 .checked_mul(10)
788 .and_then(|post_count| post_count.checked_add(number))
789 .unwrap_or(post_count),
790 )
791 } else {
792 let pre_count = self.pre_count.unwrap_or(0);
793
794 self.pre_count = Some(
795 pre_count
796 .checked_mul(10)
797 .and_then(|pre_count| pre_count.checked_add(number))
798 .unwrap_or(pre_count),
799 )
800 }
801 // update the keymap so that 0 works
802 self.sync_vim_settings(cx)
803 }
804
805 fn select_register(&mut self, register: Arc<str>, cx: &mut ViewContext<Self>) {
806 if register.chars().count() == 1 {
807 self.selected_register
808 .replace(register.chars().next().unwrap());
809 }
810 self.operator_stack.clear();
811 self.sync_vim_settings(cx);
812 }
813
814 fn maybe_pop_operator(&mut self) -> Option<Operator> {
815 self.operator_stack.pop()
816 }
817
818 fn pop_operator(&mut self, cx: &mut ViewContext<Self>) -> Operator {
819 let popped_operator = self.operator_stack.pop()
820 .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
821 self.sync_vim_settings(cx);
822 popped_operator
823 }
824
825 fn clear_operator(&mut self, cx: &mut ViewContext<Self>) {
826 self.take_count(cx);
827 self.selected_register.take();
828 self.operator_stack.clear();
829 self.sync_vim_settings(cx);
830 }
831
832 fn active_operator(&self) -> Option<Operator> {
833 self.operator_stack.last().cloned()
834 }
835
836 fn transaction_begun(&mut self, transaction_id: TransactionId, _: &mut ViewContext<Self>) {
837 let mode = if (self.mode == Mode::Insert
838 || self.mode == Mode::Replace
839 || self.mode == Mode::Normal)
840 && self.current_tx.is_none()
841 {
842 self.current_tx = Some(transaction_id);
843 self.last_mode
844 } else {
845 self.mode
846 };
847 if mode == Mode::VisualLine || mode == Mode::VisualBlock {
848 self.undo_modes.insert(transaction_id, mode);
849 }
850 }
851
852 fn transaction_undone(&mut self, transaction_id: &TransactionId, cx: &mut ViewContext<Self>) {
853 match self.mode {
854 Mode::VisualLine | Mode::VisualBlock | Mode::Visual => {
855 self.update_editor(cx, |vim, editor, cx| {
856 let original_mode = vim.undo_modes.get(transaction_id);
857 editor.change_selections(None, cx, |s| match original_mode {
858 Some(Mode::VisualLine) => {
859 s.move_with(|map, selection| {
860 selection.collapse_to(
861 map.prev_line_boundary(selection.start.to_point(map)).1,
862 SelectionGoal::None,
863 )
864 });
865 }
866 Some(Mode::VisualBlock) => {
867 let mut first = s.first_anchor();
868 first.collapse_to(first.start, first.goal);
869 s.select_anchors(vec![first]);
870 }
871 _ => {
872 s.move_with(|map, selection| {
873 selection.collapse_to(
874 map.clip_at_line_end(selection.start),
875 selection.goal,
876 );
877 });
878 }
879 });
880 });
881 self.switch_mode(Mode::Normal, true, cx)
882 }
883 Mode::Normal => {
884 self.update_editor(cx, |_, editor, cx| {
885 editor.change_selections(None, cx, |s| {
886 s.move_with(|map, selection| {
887 selection
888 .collapse_to(map.clip_at_line_end(selection.end), selection.goal)
889 })
890 })
891 });
892 }
893 Mode::Insert | Mode::Replace => {}
894 }
895 }
896
897 fn local_selections_changed(&mut self, cx: &mut ViewContext<Self>) {
898 let Some(editor) = self.editor() else { return };
899
900 if editor.read(cx).leader_peer_id().is_some() {
901 return;
902 }
903
904 let newest = editor.read(cx).selections.newest_anchor().clone();
905 let is_multicursor = editor.read(cx).selections.count() > 1;
906 if self.mode == Mode::Insert && self.current_tx.is_some() {
907 if self.current_anchor.is_none() {
908 self.current_anchor = Some(newest);
909 } else if self.current_anchor.as_ref().unwrap() != &newest {
910 if let Some(tx_id) = self.current_tx.take() {
911 self.update_editor(cx, |_, editor, cx| {
912 editor.group_until_transaction(tx_id, cx)
913 });
914 }
915 }
916 } else if self.mode == Mode::Normal && newest.start != newest.end {
917 if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
918 self.switch_mode(Mode::VisualBlock, false, cx);
919 } else {
920 self.switch_mode(Mode::Visual, false, cx)
921 }
922 } else if newest.start == newest.end
923 && !is_multicursor
924 && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&self.mode)
925 {
926 self.switch_mode(Mode::Normal, true, cx);
927 }
928 }
929
930 fn input_ignored(&mut self, text: Arc<str>, cx: &mut ViewContext<Self>) {
931 if text.is_empty() {
932 return;
933 }
934
935 match self.active_operator() {
936 Some(Operator::FindForward { before }) => {
937 let find = Motion::FindForward {
938 before,
939 char: text.chars().next().unwrap(),
940 mode: if VimSettings::get_global(cx).use_multiline_find {
941 FindRange::MultiLine
942 } else {
943 FindRange::SingleLine
944 },
945 smartcase: VimSettings::get_global(cx).use_smartcase_find,
946 };
947 Vim::globals(cx).last_find = Some(find.clone());
948 self.motion(find, cx)
949 }
950 Some(Operator::FindBackward { after }) => {
951 let find = Motion::FindBackward {
952 after,
953 char: text.chars().next().unwrap(),
954 mode: if VimSettings::get_global(cx).use_multiline_find {
955 FindRange::MultiLine
956 } else {
957 FindRange::SingleLine
958 },
959 smartcase: VimSettings::get_global(cx).use_smartcase_find,
960 };
961 Vim::globals(cx).last_find = Some(find.clone());
962 self.motion(find, cx)
963 }
964 Some(Operator::Replace) => match self.mode {
965 Mode::Normal => self.normal_replace(text, cx),
966 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
967 self.visual_replace(text, cx)
968 }
969 _ => self.clear_operator(cx),
970 },
971 Some(Operator::Digraph { first_char }) => {
972 if let Some(first_char) = first_char {
973 if let Some(second_char) = text.chars().next() {
974 self.insert_digraph(first_char, second_char, cx);
975 }
976 } else {
977 let first_char = text.chars().next();
978 self.pop_operator(cx);
979 self.push_operator(Operator::Digraph { first_char }, cx);
980 }
981 }
982 Some(Operator::AddSurrounds { target }) => match self.mode {
983 Mode::Normal => {
984 if let Some(target) = target {
985 self.add_surrounds(text, target, cx);
986 self.clear_operator(cx);
987 }
988 }
989 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
990 self.add_surrounds(text, SurroundsType::Selection, cx);
991 self.clear_operator(cx);
992 }
993 _ => self.clear_operator(cx),
994 },
995 Some(Operator::ChangeSurrounds { target }) => match self.mode {
996 Mode::Normal => {
997 if let Some(target) = target {
998 self.change_surrounds(text, target, cx);
999 self.clear_operator(cx);
1000 }
1001 }
1002 _ => self.clear_operator(cx),
1003 },
1004 Some(Operator::DeleteSurrounds) => match self.mode {
1005 Mode::Normal => {
1006 self.delete_surrounds(text, cx);
1007 self.clear_operator(cx);
1008 }
1009 _ => self.clear_operator(cx),
1010 },
1011 Some(Operator::Mark) => self.create_mark(text, false, cx),
1012 Some(Operator::RecordRegister) => {
1013 self.record_register(text.chars().next().unwrap(), cx)
1014 }
1015 Some(Operator::ReplayRegister) => {
1016 self.replay_register(text.chars().next().unwrap(), cx)
1017 }
1018 Some(Operator::Register) => match self.mode {
1019 Mode::Insert => {
1020 self.update_editor(cx, |_, editor, cx| {
1021 if let Some(register) = Vim::update_globals(cx, |globals, cx| {
1022 globals.read_register(text.chars().next(), Some(editor), cx)
1023 }) {
1024 editor.do_paste(
1025 ®ister.text.to_string(),
1026 register.clipboard_selections.clone(),
1027 false,
1028 cx,
1029 )
1030 }
1031 });
1032 self.clear_operator(cx);
1033 }
1034 _ => {
1035 self.select_register(text, cx);
1036 }
1037 },
1038 Some(Operator::Jump { line }) => self.jump(text, line, cx),
1039 _ => match self.mode {
1040 Mode::Replace => self.multi_replace(text, cx),
1041 _ => {}
1042 },
1043 }
1044 }
1045
1046 fn sync_vim_settings(&mut self, cx: &mut ViewContext<Self>) {
1047 self.update_editor(cx, |vim, editor, cx| {
1048 editor.set_cursor_shape(vim.cursor_shape(), cx);
1049 editor.set_clip_at_line_ends(vim.clip_at_line_ends(), cx);
1050 editor.set_collapse_matches(true);
1051 editor.set_input_enabled(vim.editor_input_enabled());
1052 editor.set_autoindent(vim.should_autoindent());
1053 editor.selections.line_mode = matches!(vim.mode, Mode::VisualLine);
1054 });
1055 cx.notify()
1056 }
1057}
1058
1059impl Settings for VimModeSetting {
1060 const KEY: Option<&'static str> = Some("vim_mode");
1061
1062 type FileContent = Option<bool>;
1063
1064 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1065 Ok(Self(sources.user.copied().flatten().unwrap_or(
1066 sources.default.ok_or_else(Self::missing_default)?,
1067 )))
1068 }
1069}
1070
1071/// Controls when to use system clipboard.
1072#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
1073#[serde(rename_all = "snake_case")]
1074pub enum UseSystemClipboard {
1075 /// Don't use system clipboard.
1076 Never,
1077 /// Use system clipboard.
1078 Always,
1079 /// Use system clipboard for yank operations.
1080 OnYank,
1081}
1082
1083#[derive(Deserialize)]
1084struct VimSettings {
1085 pub toggle_relative_line_numbers: bool,
1086 pub use_system_clipboard: UseSystemClipboard,
1087 pub use_multiline_find: bool,
1088 pub use_smartcase_find: bool,
1089 pub custom_digraphs: HashMap<String, Arc<str>>,
1090}
1091
1092#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
1093struct VimSettingsContent {
1094 pub toggle_relative_line_numbers: Option<bool>,
1095 pub use_system_clipboard: Option<UseSystemClipboard>,
1096 pub use_multiline_find: Option<bool>,
1097 pub use_smartcase_find: Option<bool>,
1098 pub custom_digraphs: Option<HashMap<String, Arc<str>>>,
1099}
1100
1101impl Settings for VimSettings {
1102 const KEY: Option<&'static str> = Some("vim");
1103
1104 type FileContent = VimSettingsContent;
1105
1106 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1107 sources.json_merge()
1108 }
1109}