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
300 cx.defer(|vim, cx| {
301 vim.focused(false, cx);
302 })
303 })
304 }
305
306 fn deactivate(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
307 editor.set_cursor_shape(CursorShape::Bar, cx);
308 editor.set_clip_at_line_ends(false, cx);
309 editor.set_collapse_matches(false);
310 editor.set_input_enabled(true);
311 editor.set_autoindent(true);
312 editor.selections.line_mode = false;
313 editor.unregister_addon::<VimAddon>();
314 editor.set_relative_line_number(None, cx);
315 if let Some(vim) = Vim::globals(cx).focused_vim() {
316 if vim.entity_id() == cx.view().entity_id() {
317 Vim::globals(cx).focused_vim = None;
318 }
319 }
320 }
321
322 /// Register an action on the editor.
323 pub fn action<A: Action>(
324 editor: &mut Editor,
325 cx: &mut ViewContext<Vim>,
326 f: impl Fn(&mut Vim, &A, &mut ViewContext<Vim>) + 'static,
327 ) {
328 let subscription = editor.register_action(cx.listener(f));
329 cx.on_release(|_, _, _| drop(subscription)).detach();
330 }
331
332 pub fn editor(&self) -> Option<View<Editor>> {
333 self.editor.upgrade()
334 }
335
336 pub fn workspace(&self, cx: &ViewContext<Self>) -> Option<View<Workspace>> {
337 self.editor().and_then(|editor| editor.read(cx).workspace())
338 }
339
340 pub fn pane(&self, cx: &ViewContext<Self>) -> Option<View<Pane>> {
341 self.workspace(cx)
342 .and_then(|workspace| workspace.read(cx).pane_for(&self.editor()?))
343 }
344
345 pub fn enabled(cx: &mut AppContext) -> bool {
346 VimModeSetting::get_global(cx).0
347 }
348
349 /// Called whenever an keystroke is typed so vim can observe all actions
350 /// and keystrokes accordingly.
351 fn observe_keystrokes(&mut self, keystroke_event: &KeystrokeEvent, cx: &mut ViewContext<Self>) {
352 if let Some(action) = keystroke_event.action.as_ref() {
353 // Keystroke is handled by the vim system, so continue forward
354 if action.name().starts_with("vim::") {
355 return;
356 }
357 } else if cx.has_pending_keystrokes() || keystroke_event.keystroke.is_ime_in_progress() {
358 return;
359 }
360
361 if let Some(operator) = self.active_operator() {
362 if !operator.is_waiting(self.mode) {
363 self.clear_operator(cx);
364 self.stop_recording_immediately(Box::new(ClearOperators), cx)
365 }
366 }
367 }
368
369 fn handle_editor_event(&mut self, event: &EditorEvent, cx: &mut ViewContext<Self>) {
370 match event {
371 EditorEvent::Focused => self.focused(true, cx),
372 EditorEvent::Blurred => self.blurred(cx),
373 EditorEvent::SelectionsChanged { local: true } => {
374 self.local_selections_changed(cx);
375 }
376 EditorEvent::InputIgnored { text } => {
377 self.input_ignored(text.clone(), cx);
378 Vim::globals(cx).observe_insertion(text, None)
379 }
380 EditorEvent::InputHandled {
381 text,
382 utf16_range_to_replace: range_to_replace,
383 } => Vim::globals(cx).observe_insertion(text, range_to_replace.clone()),
384 EditorEvent::TransactionBegun { transaction_id } => {
385 self.transaction_begun(*transaction_id, cx)
386 }
387 EditorEvent::TransactionUndone { transaction_id } => {
388 self.transaction_undone(transaction_id, cx)
389 }
390 EditorEvent::Edited { .. } => self.push_to_change_list(cx),
391 EditorEvent::FocusedIn => self.sync_vim_settings(cx),
392 _ => {}
393 }
394 }
395
396 fn push_operator(&mut self, operator: Operator, cx: &mut ViewContext<Self>) {
397 if matches!(
398 operator,
399 Operator::Change
400 | Operator::Delete
401 | Operator::Replace
402 | Operator::Indent
403 | Operator::Outdent
404 | Operator::Lowercase
405 | Operator::Uppercase
406 | Operator::OppositeCase
407 | Operator::ToggleComments
408 ) {
409 self.start_recording(cx)
410 };
411 // Since these operations can only be entered with pre-operators,
412 // we need to clear the previous operators when pushing,
413 // so that the current stack is the most correct
414 if matches!(
415 operator,
416 Operator::AddSurrounds { .. }
417 | Operator::ChangeSurrounds { .. }
418 | Operator::DeleteSurrounds
419 ) {
420 self.operator_stack.clear();
421 if let Operator::AddSurrounds { target: None } = operator {
422 self.start_recording(cx);
423 }
424 };
425 self.operator_stack.push(operator);
426 self.sync_vim_settings(cx);
427 }
428
429 pub fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut ViewContext<Self>) {
430 let last_mode = self.mode;
431 let prior_mode = self.last_mode;
432 let prior_tx = self.current_tx;
433 self.last_mode = last_mode;
434 self.mode = mode;
435 self.operator_stack.clear();
436 self.selected_register.take();
437 if mode == Mode::Normal || mode != last_mode {
438 self.current_tx.take();
439 self.current_anchor.take();
440 }
441 if mode != Mode::Insert && mode != Mode::Replace {
442 self.take_count(cx);
443 }
444
445 // Sync editor settings like clip mode
446 self.sync_vim_settings(cx);
447
448 if VimSettings::get_global(cx).toggle_relative_line_numbers
449 && self.mode != self.last_mode
450 && (self.mode == Mode::Insert || self.last_mode == Mode::Insert)
451 {
452 self.update_editor(cx, |vim, editor, cx| {
453 let is_relative = vim.mode != Mode::Insert;
454 editor.set_relative_line_number(Some(is_relative), cx)
455 });
456 }
457
458 if leave_selections {
459 return;
460 }
461
462 if !mode.is_visual() && last_mode.is_visual() {
463 self.create_visual_marks(last_mode, cx);
464 }
465
466 // Adjust selections
467 self.update_editor(cx, |vim, editor, cx| {
468 if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
469 {
470 vim.visual_block_motion(true, editor, cx, |_, point, goal| Some((point, goal)))
471 }
472 if last_mode == Mode::Insert || last_mode == Mode::Replace {
473 if let Some(prior_tx) = prior_tx {
474 editor.group_until_transaction(prior_tx, cx)
475 }
476 }
477
478 editor.change_selections(None, cx, |s| {
479 // we cheat with visual block mode and use multiple cursors.
480 // the cost of this cheat is we need to convert back to a single
481 // cursor whenever vim would.
482 if last_mode == Mode::VisualBlock
483 && (mode != Mode::VisualBlock && mode != Mode::Insert)
484 {
485 let tail = s.oldest_anchor().tail();
486 let head = s.newest_anchor().head();
487 s.select_anchor_ranges(vec![tail..head]);
488 } else if last_mode == Mode::Insert
489 && prior_mode == Mode::VisualBlock
490 && mode != Mode::VisualBlock
491 {
492 let pos = s.first_anchor().head();
493 s.select_anchor_ranges(vec![pos..pos])
494 }
495
496 let snapshot = s.display_map();
497 if let Some(pending) = s.pending.as_mut() {
498 if pending.selection.reversed && mode.is_visual() && !last_mode.is_visual() {
499 let mut end = pending.selection.end.to_point(&snapshot.buffer_snapshot);
500 end = snapshot
501 .buffer_snapshot
502 .clip_point(end + Point::new(0, 1), Bias::Right);
503 pending.selection.end = snapshot.buffer_snapshot.anchor_before(end);
504 }
505 }
506
507 s.move_with(|map, selection| {
508 if last_mode.is_visual() && !mode.is_visual() {
509 let mut point = selection.head();
510 if !selection.reversed && !selection.is_empty() {
511 point = movement::left(map, selection.head());
512 }
513 selection.collapse_to(point, selection.goal)
514 } else if !last_mode.is_visual() && mode.is_visual() && selection.is_empty() {
515 selection.end = movement::right(map, selection.start);
516 }
517 });
518 })
519 });
520 }
521
522 fn take_count(&mut self, cx: &mut ViewContext<Self>) -> Option<usize> {
523 let global_state = cx.global_mut::<VimGlobals>();
524 if global_state.dot_replaying {
525 return global_state.recorded_count;
526 }
527
528 let count = if self.post_count.is_none() && self.pre_count.is_none() {
529 return None;
530 } else {
531 Some(self.post_count.take().unwrap_or(1) * self.pre_count.take().unwrap_or(1))
532 };
533
534 if global_state.dot_recording {
535 global_state.recorded_count = count;
536 }
537 self.sync_vim_settings(cx);
538 count
539 }
540
541 pub fn cursor_shape(&self) -> CursorShape {
542 match self.mode {
543 Mode::Normal => {
544 if self.operator_stack.is_empty() {
545 CursorShape::Block
546 } else {
547 CursorShape::Underscore
548 }
549 }
550 Mode::Replace => CursorShape::Underscore,
551 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => CursorShape::Block,
552 Mode::Insert => CursorShape::Bar,
553 }
554 }
555
556 pub fn editor_input_enabled(&self) -> bool {
557 match self.mode {
558 Mode::Insert => {
559 if let Some(operator) = self.operator_stack.last() {
560 !operator.is_waiting(self.mode)
561 } else {
562 true
563 }
564 }
565 Mode::Normal | Mode::Replace | Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
566 false
567 }
568 }
569 }
570
571 pub fn should_autoindent(&self) -> bool {
572 !(self.mode == Mode::Insert && self.last_mode == Mode::VisualBlock)
573 }
574
575 pub fn clip_at_line_ends(&self) -> bool {
576 match self.mode {
577 Mode::Insert | Mode::Visual | Mode::VisualLine | Mode::VisualBlock | Mode::Replace => {
578 false
579 }
580 Mode::Normal => true,
581 }
582 }
583
584 pub fn extend_key_context(&self, context: &mut KeyContext) {
585 let mut mode = match self.mode {
586 Mode::Normal => "normal",
587 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => "visual",
588 Mode::Insert => "insert",
589 Mode::Replace => "replace",
590 }
591 .to_string();
592
593 let mut operator_id = "none";
594
595 let active_operator = self.active_operator();
596 if active_operator.is_none() && self.pre_count.is_some()
597 || active_operator.is_some() && self.post_count.is_some()
598 {
599 context.add("VimCount");
600 }
601
602 if let Some(active_operator) = active_operator {
603 if active_operator.is_waiting(self.mode) {
604 mode = "waiting".to_string();
605 } else {
606 mode = "operator".to_string();
607 operator_id = active_operator.id();
608 }
609 }
610
611 if mode != "waiting" && mode != "insert" && mode != "replace" {
612 context.add("VimControl");
613 }
614 context.set("vim_mode", mode);
615 context.set("vim_operator", operator_id);
616 }
617
618 fn focused(&mut self, preserve_selection: bool, cx: &mut ViewContext<Self>) {
619 let Some(editor) = self.editor() else {
620 return;
621 };
622 let editor = editor.read(cx);
623 let editor_mode = editor.mode();
624 let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
625
626 if editor_mode == EditorMode::Full
627 && !newest_selection_empty
628 && self.mode == Mode::Normal
629 // When following someone, don't switch vim mode.
630 && editor.leader_peer_id().is_none()
631 {
632 if preserve_selection {
633 self.switch_mode(Mode::Visual, true, cx);
634 } else {
635 self.update_editor(cx, |_, editor, cx| {
636 editor.set_clip_at_line_ends(false, cx);
637 editor.change_selections(None, cx, |s| {
638 s.move_with(|_, selection| {
639 selection.collapse_to(selection.start, selection.goal)
640 })
641 });
642 });
643 }
644 }
645
646 cx.emit(VimEvent::Focused);
647 self.sync_vim_settings(cx);
648
649 if VimSettings::get_global(cx).toggle_relative_line_numbers {
650 if let Some(old_vim) = Vim::globals(cx).focused_vim() {
651 if old_vim.entity_id() != cx.view().entity_id() {
652 old_vim.update(cx, |vim, cx| {
653 vim.update_editor(cx, |_, editor, cx| {
654 editor.set_relative_line_number(None, cx)
655 });
656 });
657
658 self.update_editor(cx, |vim, editor, cx| {
659 let is_relative = vim.mode != Mode::Insert;
660 editor.set_relative_line_number(Some(is_relative), cx)
661 });
662 }
663 } else {
664 self.update_editor(cx, |vim, editor, cx| {
665 let is_relative = vim.mode != Mode::Insert;
666 editor.set_relative_line_number(Some(is_relative), cx)
667 });
668 }
669 }
670 Vim::globals(cx).focused_vim = Some(cx.view().downgrade());
671 }
672
673 fn blurred(&mut self, cx: &mut ViewContext<Self>) {
674 self.stop_recording_immediately(NormalBefore.boxed_clone(), cx);
675 self.store_visual_marks(cx);
676 self.clear_operator(cx);
677 self.update_editor(cx, |_, editor, cx| {
678 editor.set_cursor_shape(language::CursorShape::Hollow, cx);
679 });
680 }
681
682 fn update_editor<S>(
683 &mut self,
684 cx: &mut ViewContext<Self>,
685 update: impl FnOnce(&mut Self, &mut Editor, &mut ViewContext<Editor>) -> S,
686 ) -> Option<S> {
687 let editor = self.editor.upgrade()?;
688 Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
689 }
690
691 fn editor_selections(&mut self, cx: &mut ViewContext<Self>) -> Vec<Range<Anchor>> {
692 self.update_editor(cx, |_, editor, _| {
693 editor
694 .selections
695 .disjoint_anchors()
696 .iter()
697 .map(|selection| selection.tail()..selection.head())
698 .collect()
699 })
700 .unwrap_or_default()
701 }
702
703 /// When doing an action that modifies the buffer, we start recording so that `.`
704 /// will replay the action.
705 pub fn start_recording(&mut self, cx: &mut ViewContext<Self>) {
706 Vim::update_globals(cx, |globals, cx| {
707 if !globals.dot_replaying {
708 globals.dot_recording = true;
709 globals.recorded_actions = Default::default();
710 globals.recorded_count = None;
711
712 let selections = self.editor().map(|editor| {
713 let editor = editor.read(cx);
714 (
715 editor.selections.oldest::<Point>(cx),
716 editor.selections.newest::<Point>(cx),
717 )
718 });
719
720 if let Some((oldest, newest)) = selections {
721 globals.recorded_selection = match self.mode {
722 Mode::Visual if newest.end.row == newest.start.row => {
723 RecordedSelection::SingleLine {
724 cols: newest.end.column - newest.start.column,
725 }
726 }
727 Mode::Visual => RecordedSelection::Visual {
728 rows: newest.end.row - newest.start.row,
729 cols: newest.end.column,
730 },
731 Mode::VisualLine => RecordedSelection::VisualLine {
732 rows: newest.end.row - newest.start.row,
733 },
734 Mode::VisualBlock => RecordedSelection::VisualBlock {
735 rows: newest.end.row.abs_diff(oldest.start.row),
736 cols: newest.end.column.abs_diff(oldest.start.column),
737 },
738 _ => RecordedSelection::None,
739 }
740 } else {
741 globals.recorded_selection = RecordedSelection::None;
742 }
743 }
744 })
745 }
746
747 pub fn stop_replaying(&mut self, cx: &mut ViewContext<Self>) {
748 let globals = Vim::globals(cx);
749 globals.dot_replaying = false;
750 if let Some(replayer) = globals.replayer.take() {
751 replayer.stop();
752 }
753 }
754
755 /// When finishing an action that modifies the buffer, stop recording.
756 /// as you usually call this within a keystroke handler we also ensure that
757 /// the current action is recorded.
758 pub fn stop_recording(&mut self, cx: &mut ViewContext<Self>) {
759 let globals = Vim::globals(cx);
760 if globals.dot_recording {
761 globals.stop_recording_after_next_action = true;
762 }
763 }
764
765 /// Stops recording actions immediately rather than waiting until after the
766 /// next action to stop recording.
767 ///
768 /// This doesn't include the current action.
769 pub fn stop_recording_immediately(
770 &mut self,
771 action: Box<dyn Action>,
772 cx: &mut ViewContext<Self>,
773 ) {
774 let globals = Vim::globals(cx);
775 if globals.dot_recording {
776 globals
777 .recorded_actions
778 .push(ReplayableAction::Action(action.boxed_clone()));
779 globals.dot_recording = false;
780 globals.stop_recording_after_next_action = false;
781 }
782 }
783
784 /// Explicitly record one action (equivalents to start_recording and stop_recording)
785 pub fn record_current_action(&mut self, cx: &mut ViewContext<Self>) {
786 self.start_recording(cx);
787 self.stop_recording(cx);
788 }
789
790 fn push_count_digit(&mut self, number: usize, cx: &mut ViewContext<Self>) {
791 if self.active_operator().is_some() {
792 let post_count = self.post_count.unwrap_or(0);
793
794 self.post_count = Some(
795 post_count
796 .checked_mul(10)
797 .and_then(|post_count| post_count.checked_add(number))
798 .unwrap_or(post_count),
799 )
800 } else {
801 let pre_count = self.pre_count.unwrap_or(0);
802
803 self.pre_count = Some(
804 pre_count
805 .checked_mul(10)
806 .and_then(|pre_count| pre_count.checked_add(number))
807 .unwrap_or(pre_count),
808 )
809 }
810 // update the keymap so that 0 works
811 self.sync_vim_settings(cx)
812 }
813
814 fn select_register(&mut self, register: Arc<str>, cx: &mut ViewContext<Self>) {
815 if register.chars().count() == 1 {
816 self.selected_register
817 .replace(register.chars().next().unwrap());
818 }
819 self.operator_stack.clear();
820 self.sync_vim_settings(cx);
821 }
822
823 fn maybe_pop_operator(&mut self) -> Option<Operator> {
824 self.operator_stack.pop()
825 }
826
827 fn pop_operator(&mut self, cx: &mut ViewContext<Self>) -> Operator {
828 let popped_operator = self.operator_stack.pop()
829 .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
830 self.sync_vim_settings(cx);
831 popped_operator
832 }
833
834 fn clear_operator(&mut self, cx: &mut ViewContext<Self>) {
835 self.take_count(cx);
836 self.selected_register.take();
837 self.operator_stack.clear();
838 self.sync_vim_settings(cx);
839 }
840
841 fn active_operator(&self) -> Option<Operator> {
842 self.operator_stack.last().cloned()
843 }
844
845 fn transaction_begun(&mut self, transaction_id: TransactionId, _: &mut ViewContext<Self>) {
846 let mode = if (self.mode == Mode::Insert
847 || self.mode == Mode::Replace
848 || self.mode == Mode::Normal)
849 && self.current_tx.is_none()
850 {
851 self.current_tx = Some(transaction_id);
852 self.last_mode
853 } else {
854 self.mode
855 };
856 if mode == Mode::VisualLine || mode == Mode::VisualBlock {
857 self.undo_modes.insert(transaction_id, mode);
858 }
859 }
860
861 fn transaction_undone(&mut self, transaction_id: &TransactionId, cx: &mut ViewContext<Self>) {
862 match self.mode {
863 Mode::VisualLine | Mode::VisualBlock | Mode::Visual => {
864 self.update_editor(cx, |vim, editor, cx| {
865 let original_mode = vim.undo_modes.get(transaction_id);
866 editor.change_selections(None, cx, |s| match original_mode {
867 Some(Mode::VisualLine) => {
868 s.move_with(|map, selection| {
869 selection.collapse_to(
870 map.prev_line_boundary(selection.start.to_point(map)).1,
871 SelectionGoal::None,
872 )
873 });
874 }
875 Some(Mode::VisualBlock) => {
876 let mut first = s.first_anchor();
877 first.collapse_to(first.start, first.goal);
878 s.select_anchors(vec![first]);
879 }
880 _ => {
881 s.move_with(|map, selection| {
882 selection.collapse_to(
883 map.clip_at_line_end(selection.start),
884 selection.goal,
885 );
886 });
887 }
888 });
889 });
890 self.switch_mode(Mode::Normal, true, cx)
891 }
892 Mode::Normal => {
893 self.update_editor(cx, |_, editor, cx| {
894 editor.change_selections(None, cx, |s| {
895 s.move_with(|map, selection| {
896 selection
897 .collapse_to(map.clip_at_line_end(selection.end), selection.goal)
898 })
899 })
900 });
901 }
902 Mode::Insert | Mode::Replace => {}
903 }
904 }
905
906 fn local_selections_changed(&mut self, cx: &mut ViewContext<Self>) {
907 let Some(editor) = self.editor() else { return };
908
909 if editor.read(cx).leader_peer_id().is_some() {
910 return;
911 }
912
913 let newest = editor.read(cx).selections.newest_anchor().clone();
914 let is_multicursor = editor.read(cx).selections.count() > 1;
915 if self.mode == Mode::Insert && self.current_tx.is_some() {
916 if self.current_anchor.is_none() {
917 self.current_anchor = Some(newest);
918 } else if self.current_anchor.as_ref().unwrap() != &newest {
919 if let Some(tx_id) = self.current_tx.take() {
920 self.update_editor(cx, |_, editor, cx| {
921 editor.group_until_transaction(tx_id, cx)
922 });
923 }
924 }
925 } else if self.mode == Mode::Normal && newest.start != newest.end {
926 if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
927 self.switch_mode(Mode::VisualBlock, false, cx);
928 } else {
929 self.switch_mode(Mode::Visual, false, cx)
930 }
931 } else if newest.start == newest.end
932 && !is_multicursor
933 && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&self.mode)
934 {
935 self.switch_mode(Mode::Normal, true, cx);
936 }
937 }
938
939 fn input_ignored(&mut self, text: Arc<str>, cx: &mut ViewContext<Self>) {
940 if text.is_empty() {
941 return;
942 }
943
944 match self.active_operator() {
945 Some(Operator::FindForward { before }) => {
946 let find = Motion::FindForward {
947 before,
948 char: text.chars().next().unwrap(),
949 mode: if VimSettings::get_global(cx).use_multiline_find {
950 FindRange::MultiLine
951 } else {
952 FindRange::SingleLine
953 },
954 smartcase: VimSettings::get_global(cx).use_smartcase_find,
955 };
956 Vim::globals(cx).last_find = Some(find.clone());
957 self.motion(find, cx)
958 }
959 Some(Operator::FindBackward { after }) => {
960 let find = Motion::FindBackward {
961 after,
962 char: text.chars().next().unwrap(),
963 mode: if VimSettings::get_global(cx).use_multiline_find {
964 FindRange::MultiLine
965 } else {
966 FindRange::SingleLine
967 },
968 smartcase: VimSettings::get_global(cx).use_smartcase_find,
969 };
970 Vim::globals(cx).last_find = Some(find.clone());
971 self.motion(find, cx)
972 }
973 Some(Operator::Replace) => match self.mode {
974 Mode::Normal => self.normal_replace(text, cx),
975 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
976 self.visual_replace(text, cx)
977 }
978 _ => self.clear_operator(cx),
979 },
980 Some(Operator::Digraph { first_char }) => {
981 if let Some(first_char) = first_char {
982 if let Some(second_char) = text.chars().next() {
983 self.insert_digraph(first_char, second_char, cx);
984 }
985 } else {
986 let first_char = text.chars().next();
987 self.pop_operator(cx);
988 self.push_operator(Operator::Digraph { first_char }, cx);
989 }
990 }
991 Some(Operator::AddSurrounds { target }) => match self.mode {
992 Mode::Normal => {
993 if let Some(target) = target {
994 self.add_surrounds(text, target, cx);
995 self.clear_operator(cx);
996 }
997 }
998 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
999 self.add_surrounds(text, SurroundsType::Selection, cx);
1000 self.clear_operator(cx);
1001 }
1002 _ => self.clear_operator(cx),
1003 },
1004 Some(Operator::ChangeSurrounds { target }) => match self.mode {
1005 Mode::Normal => {
1006 if let Some(target) = target {
1007 self.change_surrounds(text, target, cx);
1008 self.clear_operator(cx);
1009 }
1010 }
1011 _ => self.clear_operator(cx),
1012 },
1013 Some(Operator::DeleteSurrounds) => match self.mode {
1014 Mode::Normal => {
1015 self.delete_surrounds(text, cx);
1016 self.clear_operator(cx);
1017 }
1018 _ => self.clear_operator(cx),
1019 },
1020 Some(Operator::Mark) => self.create_mark(text, false, cx),
1021 Some(Operator::RecordRegister) => {
1022 self.record_register(text.chars().next().unwrap(), cx)
1023 }
1024 Some(Operator::ReplayRegister) => {
1025 self.replay_register(text.chars().next().unwrap(), cx)
1026 }
1027 Some(Operator::Register) => match self.mode {
1028 Mode::Insert => {
1029 self.update_editor(cx, |_, editor, cx| {
1030 if let Some(register) = Vim::update_globals(cx, |globals, cx| {
1031 globals.read_register(text.chars().next(), Some(editor), cx)
1032 }) {
1033 editor.do_paste(
1034 ®ister.text.to_string(),
1035 register.clipboard_selections.clone(),
1036 false,
1037 cx,
1038 )
1039 }
1040 });
1041 self.clear_operator(cx);
1042 }
1043 _ => {
1044 self.select_register(text, cx);
1045 }
1046 },
1047 Some(Operator::Jump { line }) => self.jump(text, line, cx),
1048 _ => {
1049 if self.mode == Mode::Replace {
1050 self.multi_replace(text, cx)
1051 }
1052 }
1053 }
1054 }
1055
1056 fn sync_vim_settings(&mut self, cx: &mut ViewContext<Self>) {
1057 self.update_editor(cx, |vim, editor, cx| {
1058 editor.set_cursor_shape(vim.cursor_shape(), cx);
1059 editor.set_clip_at_line_ends(vim.clip_at_line_ends(), cx);
1060 editor.set_collapse_matches(true);
1061 editor.set_input_enabled(vim.editor_input_enabled());
1062 editor.set_autoindent(vim.should_autoindent());
1063 editor.selections.line_mode = matches!(vim.mode, Mode::VisualLine);
1064 editor.set_inline_completions_enabled(matches!(vim.mode, Mode::Insert | Mode::Replace));
1065 });
1066 cx.notify()
1067 }
1068}
1069
1070impl Settings for VimModeSetting {
1071 const KEY: Option<&'static str> = Some("vim_mode");
1072
1073 type FileContent = Option<bool>;
1074
1075 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1076 Ok(Self(sources.user.copied().flatten().unwrap_or(
1077 sources.default.ok_or_else(Self::missing_default)?,
1078 )))
1079 }
1080}
1081
1082/// Controls when to use system clipboard.
1083#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
1084#[serde(rename_all = "snake_case")]
1085pub enum UseSystemClipboard {
1086 /// Don't use system clipboard.
1087 Never,
1088 /// Use system clipboard.
1089 Always,
1090 /// Use system clipboard for yank operations.
1091 OnYank,
1092}
1093
1094#[derive(Deserialize)]
1095struct VimSettings {
1096 pub toggle_relative_line_numbers: bool,
1097 pub use_system_clipboard: UseSystemClipboard,
1098 pub use_multiline_find: bool,
1099 pub use_smartcase_find: bool,
1100 pub custom_digraphs: HashMap<String, Arc<str>>,
1101}
1102
1103#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
1104struct VimSettingsContent {
1105 pub toggle_relative_line_numbers: Option<bool>,
1106 pub use_system_clipboard: Option<UseSystemClipboard>,
1107 pub use_multiline_find: Option<bool>,
1108 pub use_smartcase_find: Option<bool>,
1109 pub custom_digraphs: Option<HashMap<String, Arc<str>>>,
1110}
1111
1112impl Settings for VimSettings {
1113 const KEY: Option<&'static str> = Some("vim");
1114
1115 type FileContent = VimSettingsContent;
1116
1117 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1118 sources.json_merge()
1119 }
1120}