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