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