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