1//! Vim support for Zed.
2
3#[cfg(test)]
4mod test;
5
6mod change_list;
7mod command;
8mod digraph;
9mod helix;
10mod indent;
11mod insert;
12mod mode_indicator;
13mod motion;
14mod normal;
15mod object;
16mod replace;
17mod rewrap;
18mod state;
19mod surrounds;
20mod visual;
21
22use collections::HashMap;
23use editor::{
24 Anchor, Bias, Editor, EditorEvent, EditorSettings, HideMouseCursorOrigin, SelectionEffects,
25 ToPoint,
26 movement::{self, FindRange},
27};
28use gpui::{
29 Action, App, AppContext, Axis, Context, Entity, EventEmitter, KeyContext, KeystrokeEvent,
30 Render, Subscription, Task, WeakEntity, Window, actions,
31};
32use insert::{NormalBefore, TemporaryNormal};
33use language::{
34 CharKind, CharScopeContext, CursorShape, Point, Selection, SelectionGoal, TransactionId,
35};
36pub use mode_indicator::ModeIndicator;
37use motion::Motion;
38use normal::search::SearchSubmit;
39use object::Object;
40use schemars::JsonSchema;
41use serde::Deserialize;
42pub use settings::{
43 ModeContent, Settings, SettingsStore, UseSystemClipboard, update_settings_file,
44};
45use state::{Mode, ObjectScope, Operator, RecordedSelection, SearchState, VimGlobals};
46use std::{mem, ops::Range, sync::Arc};
47use surrounds::SurroundsType;
48use theme::ThemeSettings;
49use ui::{IntoElement, SharedString, px};
50use util::serde::default_true;
51use vim_mode_setting::HelixModeSetting;
52use vim_mode_setting::VimModeSetting;
53use workspace::{self, Pane, Workspace};
54
55use crate::{
56 normal::{GoToPreviousTab, GoToTab},
57 state::ReplayableAction,
58};
59
60/// Number is used to manage vim's count. Pushing a digit
61/// multiplies the current value by 10 and adds the digit.
62#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
63#[action(namespace = vim)]
64struct Number(usize);
65
66#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
67#[action(namespace = vim)]
68struct SelectRegister(String);
69
70#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
71#[action(namespace = vim)]
72#[serde(deny_unknown_fields)]
73struct PushObject {
74 around: bool,
75 #[serde(default = "default_true")]
76 whitespace: bool,
77}
78
79#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
80#[action(namespace = vim)]
81#[serde(deny_unknown_fields)]
82struct PushFindForward {
83 before: bool,
84 multiline: bool,
85}
86
87#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
88#[action(namespace = vim)]
89#[serde(deny_unknown_fields)]
90struct PushFindBackward {
91 after: bool,
92 multiline: bool,
93}
94
95#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
96#[action(namespace = vim)]
97#[serde(deny_unknown_fields)]
98/// Selects the next object.
99struct PushHelixNext {
100 around: bool,
101}
102
103#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
104#[action(namespace = vim)]
105#[serde(deny_unknown_fields)]
106/// Selects the previous object.
107struct PushHelixPrevious {
108 around: bool,
109}
110
111#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
112#[action(namespace = vim)]
113#[serde(deny_unknown_fields)]
114struct PushSneak {
115 first_char: Option<char>,
116}
117
118#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
119#[action(namespace = vim)]
120#[serde(deny_unknown_fields)]
121struct PushSneakBackward {
122 first_char: Option<char>,
123}
124
125#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
126#[action(namespace = vim)]
127#[serde(deny_unknown_fields)]
128struct PushAddSurrounds;
129
130#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
131#[action(namespace = vim)]
132#[serde(deny_unknown_fields)]
133struct PushChangeSurrounds {
134 target: Option<Object>,
135}
136
137#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
138#[action(namespace = vim)]
139#[serde(deny_unknown_fields)]
140struct PushJump {
141 line: bool,
142}
143
144#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
145#[action(namespace = vim)]
146#[serde(deny_unknown_fields)]
147struct PushDigraph {
148 first_char: Option<char>,
149}
150
151#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
152#[action(namespace = vim)]
153#[serde(deny_unknown_fields)]
154struct PushLiteral {
155 prefix: Option<String>,
156}
157
158actions!(
159 vim,
160 [
161 /// Switches to normal mode.
162 SwitchToNormalMode,
163 /// Switches to insert mode.
164 SwitchToInsertMode,
165 /// Switches to replace mode.
166 SwitchToReplaceMode,
167 /// Switches to visual mode.
168 SwitchToVisualMode,
169 /// Switches to visual line mode.
170 SwitchToVisualLineMode,
171 /// Switches to visual block mode.
172 SwitchToVisualBlockMode,
173 /// Switches to Helix-style normal mode.
174 SwitchToHelixNormalMode,
175 /// Clears any pending operators.
176 ClearOperators,
177 /// Clears the exchange register.
178 ClearExchange,
179 /// Inserts a tab character.
180 Tab,
181 /// Inserts a newline.
182 Enter,
183 /// Selects inner text object.
184 InnerObject,
185 /// Maximizes the current pane.
186 MaximizePane,
187 /// Opens the default keymap file.
188 OpenDefaultKeymap,
189 /// Resets all pane sizes to default.
190 ResetPaneSizes,
191 /// Resizes the pane to the right.
192 ResizePaneRight,
193 /// Resizes the pane to the left.
194 ResizePaneLeft,
195 /// Resizes the pane upward.
196 ResizePaneUp,
197 /// Resizes the pane downward.
198 ResizePaneDown,
199 /// Starts a change operation.
200 PushChange,
201 /// Starts a delete operation.
202 PushDelete,
203 /// Exchanges text regions.
204 Exchange,
205 /// Starts a yank operation.
206 PushYank,
207 /// Starts a replace operation.
208 PushReplace,
209 /// Deletes surrounding characters.
210 PushDeleteSurrounds,
211 /// Sets a mark at the current position.
212 PushMark,
213 /// Toggles the marks view.
214 ToggleMarksView,
215 /// Starts a forced motion.
216 PushForcedMotion,
217 /// Starts an indent operation.
218 PushIndent,
219 /// Starts an outdent operation.
220 PushOutdent,
221 /// Starts an auto-indent operation.
222 PushAutoIndent,
223 /// Starts a rewrap operation.
224 PushRewrap,
225 /// Starts a shell command operation.
226 PushShellCommand,
227 /// Converts to lowercase.
228 PushLowercase,
229 /// Converts to uppercase.
230 PushUppercase,
231 /// Toggles case.
232 PushOppositeCase,
233 /// Applies ROT13 encoding.
234 PushRot13,
235 /// Applies ROT47 encoding.
236 PushRot47,
237 /// Toggles the registers view.
238 ToggleRegistersView,
239 /// Selects a register.
240 PushRegister,
241 /// Starts recording to a register.
242 PushRecordRegister,
243 /// Replays a register.
244 PushReplayRegister,
245 /// Replaces with register contents.
246 PushReplaceWithRegister,
247 /// Toggles comments.
248 PushToggleComments,
249 /// Selects (count) next menu item
250 MenuSelectNext,
251 /// Selects (count) previous menu item
252 MenuSelectPrevious,
253 /// Clears count or toggles project panel focus
254 ToggleProjectPanelFocus,
255 /// Starts a match operation.
256 PushHelixMatch,
257 ]
258);
259
260// in the workspace namespace so it's not filtered out when vim is disabled.
261actions!(
262 workspace,
263 [
264 /// Toggles Vim mode on or off.
265 ToggleVimMode,
266 ]
267);
268
269/// Initializes the `vim` crate.
270pub fn init(cx: &mut App) {
271 vim_mode_setting::init(cx);
272 VimSettings::register(cx);
273 VimGlobals::register(cx);
274
275 cx.observe_new(Vim::register).detach();
276
277 cx.observe_new(|workspace: &mut Workspace, _, _| {
278 workspace.register_action(|workspace, _: &ToggleVimMode, _, cx| {
279 let fs = workspace.app_state().fs.clone();
280 let currently_enabled = Vim::enabled(cx);
281 update_settings_file(fs, cx, move |setting, _| {
282 setting.vim_mode = Some(!currently_enabled)
283 })
284 });
285
286 workspace.register_action(|_, _: &MenuSelectNext, window, cx| {
287 let count = Vim::take_count(cx).unwrap_or(1);
288
289 for _ in 0..count {
290 window.dispatch_action(menu::SelectNext.boxed_clone(), cx);
291 }
292 });
293
294 workspace.register_action(|_, _: &MenuSelectPrevious, window, cx| {
295 let count = Vim::take_count(cx).unwrap_or(1);
296
297 for _ in 0..count {
298 window.dispatch_action(menu::SelectPrevious.boxed_clone(), cx);
299 }
300 });
301
302 workspace.register_action(|_, _: &ToggleProjectPanelFocus, window, cx| {
303 if Vim::take_count(cx).is_none() {
304 window.dispatch_action(project_panel::ToggleFocus.boxed_clone(), cx);
305 }
306 });
307
308 workspace.register_action(|workspace, n: &Number, window, cx| {
309 let vim = workspace
310 .focused_pane(window, cx)
311 .read(cx)
312 .active_item()
313 .and_then(|item| item.act_as::<Editor>(cx))
314 .and_then(|editor| editor.read(cx).addon::<VimAddon>().cloned());
315 if let Some(vim) = vim {
316 let digit = n.0;
317 vim.entity.update(cx, |_, cx| {
318 cx.defer_in(window, move |vim, window, cx| {
319 vim.push_count_digit(digit, window, cx)
320 })
321 });
322 } else {
323 let count = Vim::globals(cx).pre_count.unwrap_or(0);
324 Vim::globals(cx).pre_count = Some(
325 count
326 .checked_mul(10)
327 .and_then(|c| c.checked_add(n.0))
328 .unwrap_or(count),
329 );
330 };
331 });
332
333 workspace.register_action(|_, _: &OpenDefaultKeymap, _, cx| {
334 cx.emit(workspace::Event::OpenBundledFile {
335 text: settings::vim_keymap(),
336 title: "Default Vim Bindings",
337 language: "JSON",
338 });
339 });
340
341 workspace.register_action(|workspace, _: &ResetPaneSizes, _, cx| {
342 workspace.reset_pane_sizes(cx);
343 });
344
345 workspace.register_action(|workspace, _: &MaximizePane, window, cx| {
346 let pane = workspace.active_pane();
347 let Some(size) = workspace.bounding_box_for_pane(pane) else {
348 return;
349 };
350
351 let theme = ThemeSettings::get_global(cx);
352 let height = theme.buffer_font_size(cx) * theme.buffer_line_height.value();
353
354 let desired_size = if let Some(count) = Vim::take_count(cx) {
355 height * count
356 } else {
357 px(10000.)
358 };
359 workspace.resize_pane(Axis::Vertical, desired_size - size.size.height, window, cx)
360 });
361
362 workspace.register_action(|workspace, _: &ResizePaneRight, window, cx| {
363 let count = Vim::take_count(cx).unwrap_or(1) as f32;
364 Vim::take_forced_motion(cx);
365 let theme = ThemeSettings::get_global(cx);
366 let font_id = window.text_system().resolve_font(&theme.buffer_font);
367 let Ok(width) = window
368 .text_system()
369 .advance(font_id, theme.buffer_font_size(cx), 'm')
370 else {
371 return;
372 };
373 workspace.resize_pane(Axis::Horizontal, width.width * count, window, cx);
374 });
375
376 workspace.register_action(|workspace, _: &ResizePaneLeft, window, cx| {
377 let count = Vim::take_count(cx).unwrap_or(1) as f32;
378 Vim::take_forced_motion(cx);
379 let theme = ThemeSettings::get_global(cx);
380 let font_id = window.text_system().resolve_font(&theme.buffer_font);
381 let Ok(width) = window
382 .text_system()
383 .advance(font_id, theme.buffer_font_size(cx), 'm')
384 else {
385 return;
386 };
387 workspace.resize_pane(Axis::Horizontal, -width.width * count, window, cx);
388 });
389
390 workspace.register_action(|workspace, _: &ResizePaneUp, window, cx| {
391 let count = Vim::take_count(cx).unwrap_or(1) as f32;
392 Vim::take_forced_motion(cx);
393 let theme = ThemeSettings::get_global(cx);
394 let height = theme.buffer_font_size(cx) * theme.buffer_line_height.value();
395 workspace.resize_pane(Axis::Vertical, height * count, window, cx);
396 });
397
398 workspace.register_action(|workspace, _: &ResizePaneDown, window, cx| {
399 let count = Vim::take_count(cx).unwrap_or(1) as f32;
400 Vim::take_forced_motion(cx);
401 let theme = ThemeSettings::get_global(cx);
402 let height = theme.buffer_font_size(cx) * theme.buffer_line_height.value();
403 workspace.resize_pane(Axis::Vertical, -height * count, window, cx);
404 });
405
406 workspace.register_action(|workspace, _: &SearchSubmit, window, cx| {
407 let vim = workspace
408 .focused_pane(window, cx)
409 .read(cx)
410 .active_item()
411 .and_then(|item| item.act_as::<Editor>(cx))
412 .and_then(|editor| editor.read(cx).addon::<VimAddon>().cloned());
413 let Some(vim) = vim else { return };
414 vim.entity.update(cx, |_, cx| {
415 cx.defer_in(window, |vim, window, cx| vim.search_submit(window, cx))
416 })
417 });
418 workspace.register_action(|_, _: &GoToTab, window, cx| {
419 let count = Vim::take_count(cx);
420 Vim::take_forced_motion(cx);
421
422 if let Some(tab_index) = count {
423 // <count>gt goes to tab <count> (1-based).
424 let zero_based_index = tab_index.saturating_sub(1);
425 window.dispatch_action(
426 workspace::pane::ActivateItem(zero_based_index).boxed_clone(),
427 cx,
428 );
429 } else {
430 // If no count is provided, go to the next tab.
431 window.dispatch_action(workspace::pane::ActivateNextItem.boxed_clone(), cx);
432 }
433 });
434
435 workspace.register_action(|workspace, _: &GoToPreviousTab, window, cx| {
436 let count = Vim::take_count(cx);
437 Vim::take_forced_motion(cx);
438
439 if let Some(count) = count {
440 // gT with count goes back that many tabs with wraparound (not the same as gt!).
441 let pane = workspace.active_pane().read(cx);
442 let item_count = pane.items().count();
443 if item_count > 0 {
444 let current_index = pane.active_item_index();
445 let target_index = (current_index as isize - count as isize)
446 .rem_euclid(item_count as isize)
447 as usize;
448 window.dispatch_action(
449 workspace::pane::ActivateItem(target_index).boxed_clone(),
450 cx,
451 );
452 }
453 } else {
454 // No count provided, go to the previous tab.
455 window.dispatch_action(workspace::pane::ActivatePreviousItem.boxed_clone(), cx);
456 }
457 });
458 })
459 .detach();
460}
461
462#[derive(Clone)]
463pub(crate) struct VimAddon {
464 pub(crate) entity: Entity<Vim>,
465}
466
467impl editor::Addon for VimAddon {
468 fn extend_key_context(&self, key_context: &mut KeyContext, cx: &App) {
469 self.entity.read(cx).extend_key_context(key_context, cx)
470 }
471
472 fn to_any(&self) -> &dyn std::any::Any {
473 self
474 }
475}
476
477/// The state pertaining to Vim mode.
478pub(crate) struct Vim {
479 pub(crate) mode: Mode,
480 pub last_mode: Mode,
481 pub temp_mode: bool,
482 pub status_label: Option<SharedString>,
483 pub exit_temporary_mode: bool,
484
485 operator_stack: Vec<Operator>,
486 pub(crate) replacements: Vec<(Range<editor::Anchor>, String)>,
487
488 pub(crate) stored_visual_mode: Option<(Mode, Vec<bool>)>,
489
490 pub(crate) current_tx: Option<TransactionId>,
491 pub(crate) current_anchor: Option<Selection<Anchor>>,
492 pub(crate) undo_modes: HashMap<TransactionId, Mode>,
493 pub(crate) undo_last_line_tx: Option<TransactionId>,
494
495 selected_register: Option<char>,
496 pub search: SearchState,
497
498 editor: WeakEntity<Editor>,
499
500 last_command: Option<String>,
501 running_command: Option<Task<()>>,
502 _subscriptions: Vec<Subscription>,
503}
504
505// Hack: Vim intercepts events dispatched to a window and updates the view in response.
506// This means it needs a VisualContext. The easiest way to satisfy that constraint is
507// to make Vim a "View" that is just never actually rendered.
508impl Render for Vim {
509 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
510 gpui::Empty
511 }
512}
513
514enum VimEvent {
515 Focused,
516}
517impl EventEmitter<VimEvent> for Vim {}
518
519impl Vim {
520 /// The namespace for Vim actions.
521 const NAMESPACE: &'static str = "vim";
522
523 pub fn new(window: &mut Window, cx: &mut Context<Editor>) -> Entity<Self> {
524 let editor = cx.entity();
525
526 let initial_vim_mode = VimSettings::get_global(cx).default_mode;
527 let (mode, last_mode) = if HelixModeSetting::get_global(cx).0 {
528 let initial_helix_mode = match initial_vim_mode {
529 Mode::Normal => Mode::HelixNormal,
530 Mode::Insert => Mode::Insert,
531 // Otherwise, we panic with a note that we should never get there due to the
532 // possible values of VimSettings::get_global(cx).default_mode being either Mode::Normal or Mode::Insert.
533 _ => unreachable!("Invalid default mode"),
534 };
535 (initial_helix_mode, Mode::HelixNormal)
536 } else {
537 (initial_vim_mode, Mode::Normal)
538 };
539
540 cx.new(|cx| Vim {
541 mode,
542 last_mode,
543 temp_mode: false,
544 exit_temporary_mode: false,
545 operator_stack: Vec::new(),
546 replacements: Vec::new(),
547
548 stored_visual_mode: None,
549 current_tx: None,
550 undo_last_line_tx: None,
551 current_anchor: None,
552 undo_modes: HashMap::default(),
553
554 status_label: None,
555 selected_register: None,
556 search: SearchState::default(),
557
558 last_command: None,
559 running_command: None,
560
561 editor: editor.downgrade(),
562 _subscriptions: vec![
563 cx.observe_keystrokes(Self::observe_keystrokes),
564 cx.subscribe_in(&editor, window, |this, _, event, window, cx| {
565 this.handle_editor_event(event, window, cx)
566 }),
567 ],
568 })
569 }
570
571 fn register(editor: &mut Editor, window: Option<&mut Window>, cx: &mut Context<Editor>) {
572 let Some(window) = window else {
573 return;
574 };
575
576 if !editor.use_modal_editing() {
577 return;
578 }
579
580 let mut was_enabled = Vim::enabled(cx);
581 let mut was_toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;
582 cx.observe_global_in::<SettingsStore>(window, move |editor, window, cx| {
583 let enabled = Vim::enabled(cx);
584 let toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;
585 if enabled && was_enabled && (toggle != was_toggle) {
586 if toggle {
587 let is_relative = editor
588 .addon::<VimAddon>()
589 .map(|vim| vim.entity.read(cx).mode != Mode::Insert);
590 editor.set_relative_line_number(is_relative, cx)
591 } else {
592 editor.set_relative_line_number(None, cx)
593 }
594 }
595 was_toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;
596 if was_enabled == enabled {
597 return;
598 }
599 was_enabled = enabled;
600 if enabled {
601 Self::activate(editor, window, cx)
602 } else {
603 Self::deactivate(editor, cx)
604 }
605 })
606 .detach();
607 if was_enabled {
608 Self::activate(editor, window, cx)
609 }
610 }
611
612 fn activate(editor: &mut Editor, window: &mut Window, cx: &mut Context<Editor>) {
613 let vim = Vim::new(window, cx);
614
615 if !editor.mode().is_full() {
616 vim.update(cx, |vim, _| {
617 vim.mode = Mode::Insert;
618 });
619 }
620
621 editor.register_addon(VimAddon {
622 entity: vim.clone(),
623 });
624
625 vim.update(cx, |_, cx| {
626 Vim::action(editor, cx, |vim, _: &SwitchToNormalMode, window, cx| {
627 vim.switch_mode(Mode::Normal, false, window, cx)
628 });
629
630 Vim::action(editor, cx, |vim, _: &SwitchToInsertMode, window, cx| {
631 vim.switch_mode(Mode::Insert, false, window, cx)
632 });
633
634 Vim::action(editor, cx, |vim, _: &SwitchToReplaceMode, window, cx| {
635 vim.switch_mode(Mode::Replace, false, window, cx)
636 });
637
638 Vim::action(editor, cx, |vim, _: &SwitchToVisualMode, window, cx| {
639 vim.switch_mode(Mode::Visual, false, window, cx)
640 });
641
642 Vim::action(editor, cx, |vim, _: &SwitchToVisualLineMode, window, cx| {
643 vim.switch_mode(Mode::VisualLine, false, window, cx)
644 });
645
646 Vim::action(
647 editor,
648 cx,
649 |vim, _: &SwitchToVisualBlockMode, window, cx| {
650 vim.switch_mode(Mode::VisualBlock, false, window, cx)
651 },
652 );
653
654 Vim::action(
655 editor,
656 cx,
657 |vim, _: &SwitchToHelixNormalMode, window, cx| {
658 vim.switch_mode(Mode::HelixNormal, false, window, cx)
659 },
660 );
661 Vim::action(editor, cx, |_, _: &PushForcedMotion, _, cx| {
662 Vim::globals(cx).forced_motion = true;
663 });
664 Vim::action(editor, cx, |vim, action: &PushObject, window, cx| {
665 let scope = ObjectScope::from_action(action);
666 vim.push_operator(Operator::Object { scope }, window, cx)
667 });
668
669 Vim::action(editor, cx, |vim, action: &PushFindForward, window, cx| {
670 vim.push_operator(
671 Operator::FindForward {
672 before: action.before,
673 multiline: action.multiline,
674 },
675 window,
676 cx,
677 )
678 });
679
680 Vim::action(editor, cx, |vim, action: &PushFindBackward, window, cx| {
681 vim.push_operator(
682 Operator::FindBackward {
683 after: action.after,
684 multiline: action.multiline,
685 },
686 window,
687 cx,
688 )
689 });
690
691 Vim::action(editor, cx, |vim, action: &PushSneak, window, cx| {
692 vim.push_operator(
693 Operator::Sneak {
694 first_char: action.first_char,
695 },
696 window,
697 cx,
698 )
699 });
700
701 Vim::action(editor, cx, |vim, action: &PushSneakBackward, window, cx| {
702 vim.push_operator(
703 Operator::SneakBackward {
704 first_char: action.first_char,
705 },
706 window,
707 cx,
708 )
709 });
710
711 Vim::action(editor, cx, |vim, _: &PushAddSurrounds, window, cx| {
712 vim.push_operator(Operator::AddSurrounds { target: None }, window, cx)
713 });
714
715 Vim::action(
716 editor,
717 cx,
718 |vim, action: &PushChangeSurrounds, window, cx| {
719 vim.push_operator(
720 Operator::ChangeSurrounds {
721 target: action.target,
722 opening: false,
723 },
724 window,
725 cx,
726 )
727 },
728 );
729
730 Vim::action(editor, cx, |vim, action: &PushJump, window, cx| {
731 vim.push_operator(Operator::Jump { line: action.line }, window, cx)
732 });
733
734 Vim::action(editor, cx, |vim, action: &PushDigraph, window, cx| {
735 vim.push_operator(
736 Operator::Digraph {
737 first_char: action.first_char,
738 },
739 window,
740 cx,
741 )
742 });
743
744 Vim::action(editor, cx, |vim, action: &PushLiteral, window, cx| {
745 vim.push_operator(
746 Operator::Literal {
747 prefix: action.prefix.clone(),
748 },
749 window,
750 cx,
751 )
752 });
753
754 Vim::action(editor, cx, |vim, _: &PushChange, window, cx| {
755 vim.push_operator(Operator::Change, window, cx)
756 });
757
758 Vim::action(editor, cx, |vim, _: &PushDelete, window, cx| {
759 vim.push_operator(Operator::Delete, window, cx)
760 });
761
762 Vim::action(editor, cx, |vim, _: &PushYank, window, cx| {
763 vim.push_operator(Operator::Yank, window, cx)
764 });
765
766 Vim::action(editor, cx, |vim, _: &PushReplace, window, cx| {
767 vim.push_operator(Operator::Replace, window, cx)
768 });
769
770 Vim::action(editor, cx, |vim, _: &PushDeleteSurrounds, window, cx| {
771 vim.push_operator(Operator::DeleteSurrounds, window, cx)
772 });
773
774 Vim::action(editor, cx, |vim, _: &PushMark, window, cx| {
775 vim.push_operator(Operator::Mark, window, cx)
776 });
777
778 Vim::action(editor, cx, |vim, _: &PushIndent, window, cx| {
779 vim.push_operator(Operator::Indent, window, cx)
780 });
781
782 Vim::action(editor, cx, |vim, _: &PushOutdent, window, cx| {
783 vim.push_operator(Operator::Outdent, window, cx)
784 });
785
786 Vim::action(editor, cx, |vim, _: &PushAutoIndent, window, cx| {
787 vim.push_operator(Operator::AutoIndent, window, cx)
788 });
789
790 Vim::action(editor, cx, |vim, _: &PushRewrap, window, cx| {
791 vim.push_operator(Operator::Rewrap, window, cx)
792 });
793
794 Vim::action(editor, cx, |vim, _: &PushShellCommand, window, cx| {
795 vim.push_operator(Operator::ShellCommand, window, cx)
796 });
797
798 Vim::action(editor, cx, |vim, _: &PushLowercase, window, cx| {
799 vim.push_operator(Operator::Lowercase, window, cx)
800 });
801
802 Vim::action(editor, cx, |vim, _: &PushUppercase, window, cx| {
803 vim.push_operator(Operator::Uppercase, window, cx)
804 });
805
806 Vim::action(editor, cx, |vim, _: &PushOppositeCase, window, cx| {
807 vim.push_operator(Operator::OppositeCase, window, cx)
808 });
809
810 Vim::action(editor, cx, |vim, _: &PushRot13, window, cx| {
811 vim.push_operator(Operator::Rot13, window, cx)
812 });
813
814 Vim::action(editor, cx, |vim, _: &PushRot47, window, cx| {
815 vim.push_operator(Operator::Rot47, window, cx)
816 });
817
818 Vim::action(editor, cx, |vim, _: &PushRegister, window, cx| {
819 vim.push_operator(Operator::Register, window, cx)
820 });
821
822 Vim::action(editor, cx, |vim, _: &PushRecordRegister, window, cx| {
823 vim.push_operator(Operator::RecordRegister, window, cx)
824 });
825
826 Vim::action(editor, cx, |vim, _: &PushReplayRegister, window, cx| {
827 vim.push_operator(Operator::ReplayRegister, window, cx)
828 });
829
830 Vim::action(
831 editor,
832 cx,
833 |vim, _: &PushReplaceWithRegister, window, cx| {
834 vim.push_operator(Operator::ReplaceWithRegister, window, cx)
835 },
836 );
837
838 Vim::action(editor, cx, |vim, _: &Exchange, window, cx| {
839 if vim.mode.is_visual() {
840 vim.exchange_visual(window, cx)
841 } else {
842 vim.push_operator(Operator::Exchange, window, cx)
843 }
844 });
845
846 Vim::action(editor, cx, |vim, _: &ClearExchange, window, cx| {
847 vim.clear_exchange(window, cx)
848 });
849
850 Vim::action(editor, cx, |vim, _: &PushToggleComments, window, cx| {
851 vim.push_operator(Operator::ToggleComments, window, cx)
852 });
853
854 Vim::action(editor, cx, |vim, _: &ClearOperators, window, cx| {
855 vim.clear_operator(window, cx)
856 });
857 Vim::action(editor, cx, |vim, n: &Number, window, cx| {
858 vim.push_count_digit(n.0, window, cx);
859 });
860 Vim::action(editor, cx, |vim, _: &Tab, window, cx| {
861 vim.input_ignored(" ".into(), window, cx)
862 });
863 Vim::action(
864 editor,
865 cx,
866 |vim, action: &editor::actions::AcceptEditPrediction, window, cx| {
867 vim.update_editor(cx, |_, editor, cx| {
868 editor.accept_edit_prediction(action, window, cx);
869 });
870 // In non-insertion modes, predictions will be hidden and instead a jump will be
871 // displayed (and performed by `accept_edit_prediction`). This switches to
872 // insert mode so that the prediction is displayed after the jump.
873 match vim.mode {
874 Mode::Replace => {}
875 _ => vim.switch_mode(Mode::Insert, true, window, cx),
876 };
877 },
878 );
879 Vim::action(editor, cx, |vim, _: &Enter, window, cx| {
880 vim.input_ignored("\n".into(), window, cx)
881 });
882 Vim::action(editor, cx, |vim, _: &PushHelixMatch, window, cx| {
883 vim.push_operator(Operator::HelixMatch, window, cx)
884 });
885 Vim::action(editor, cx, |vim, action: &PushHelixNext, window, cx| {
886 vim.push_operator(
887 Operator::HelixNext {
888 around: action.around,
889 },
890 window,
891 cx,
892 );
893 });
894 Vim::action(editor, cx, |vim, action: &PushHelixPrevious, window, cx| {
895 vim.push_operator(
896 Operator::HelixPrevious {
897 around: action.around,
898 },
899 window,
900 cx,
901 );
902 });
903
904 normal::register(editor, cx);
905 insert::register(editor, cx);
906 helix::register(editor, cx);
907 motion::register(editor, cx);
908 command::register(editor, cx);
909 replace::register(editor, cx);
910 indent::register(editor, cx);
911 rewrap::register(editor, cx);
912 object::register(editor, cx);
913 visual::register(editor, cx);
914 change_list::register(editor, cx);
915 digraph::register(editor, cx);
916
917 cx.defer_in(window, |vim, window, cx| {
918 vim.focused(false, window, cx);
919 })
920 })
921 }
922
923 fn deactivate(editor: &mut Editor, cx: &mut Context<Editor>) {
924 editor.set_cursor_shape(CursorShape::Bar, cx);
925 editor.set_clip_at_line_ends(false, cx);
926 editor.set_collapse_matches(false);
927 editor.set_input_enabled(true);
928 editor.set_autoindent(true);
929 editor.selections.set_line_mode(false);
930 editor.unregister_addon::<VimAddon>();
931 editor.set_relative_line_number(None, cx);
932 if let Some(vim) = Vim::globals(cx).focused_vim()
933 && vim.entity_id() == cx.entity().entity_id()
934 {
935 Vim::globals(cx).focused_vim = None;
936 }
937 }
938
939 /// Register an action on the editor.
940 pub fn action<A: Action>(
941 editor: &mut Editor,
942 cx: &mut Context<Vim>,
943 f: impl Fn(&mut Vim, &A, &mut Window, &mut Context<Vim>) + 'static,
944 ) {
945 let subscription = editor.register_action(cx.listener(f));
946 cx.on_release(|_, _| drop(subscription)).detach();
947 }
948
949 pub fn editor(&self) -> Option<Entity<Editor>> {
950 self.editor.upgrade()
951 }
952
953 pub fn workspace(&self, window: &mut Window) -> Option<Entity<Workspace>> {
954 window.root::<Workspace>().flatten()
955 }
956
957 pub fn pane(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Entity<Pane>> {
958 self.workspace(window)
959 .map(|workspace| workspace.read(cx).focused_pane(window, cx))
960 }
961
962 pub fn enabled(cx: &mut App) -> bool {
963 VimModeSetting::get_global(cx).0 || HelixModeSetting::get_global(cx).0
964 }
965
966 /// Called whenever an keystroke is typed so vim can observe all actions
967 /// and keystrokes accordingly.
968 fn observe_keystrokes(
969 &mut self,
970 keystroke_event: &KeystrokeEvent,
971 window: &mut Window,
972 cx: &mut Context<Self>,
973 ) {
974 if self.exit_temporary_mode {
975 self.exit_temporary_mode = false;
976 // Don't switch to insert mode if the action is temporary_normal.
977 if let Some(action) = keystroke_event.action.as_ref()
978 && action.as_any().downcast_ref::<TemporaryNormal>().is_some()
979 {
980 return;
981 }
982 self.switch_mode(Mode::Insert, false, window, cx)
983 }
984 if let Some(action) = keystroke_event.action.as_ref() {
985 // Keystroke is handled by the vim system, so continue forward
986 if action.name().starts_with("vim::") {
987 self.update_editor(cx, |_, editor, cx| {
988 editor.hide_mouse_cursor(HideMouseCursorOrigin::MovementAction, cx)
989 });
990
991 return;
992 }
993 } else if window.has_pending_keystrokes() || keystroke_event.keystroke.is_ime_in_progress()
994 {
995 return;
996 }
997
998 if let Some(operator) = self.active_operator() {
999 match operator {
1000 Operator::Literal { prefix } => {
1001 self.handle_literal_keystroke(
1002 keystroke_event,
1003 prefix.unwrap_or_default(),
1004 window,
1005 cx,
1006 );
1007 }
1008 _ if !operator.is_waiting(self.mode) => {
1009 self.clear_operator(window, cx);
1010 self.stop_recording_immediately(Box::new(ClearOperators), cx)
1011 }
1012 _ => {}
1013 }
1014 }
1015 }
1016
1017 fn handle_editor_event(
1018 &mut self,
1019 event: &EditorEvent,
1020 window: &mut Window,
1021 cx: &mut Context<Self>,
1022 ) {
1023 match event {
1024 EditorEvent::Focused => self.focused(true, window, cx),
1025 EditorEvent::Blurred => self.blurred(window, cx),
1026 EditorEvent::SelectionsChanged { local: true } => {
1027 self.local_selections_changed(window, cx);
1028 }
1029 EditorEvent::InputIgnored { text } => {
1030 self.input_ignored(text.clone(), window, cx);
1031 Vim::globals(cx).observe_insertion(text, None)
1032 }
1033 EditorEvent::InputHandled {
1034 text,
1035 utf16_range_to_replace: range_to_replace,
1036 } => Vim::globals(cx).observe_insertion(text, range_to_replace.clone()),
1037 EditorEvent::TransactionBegun { transaction_id } => {
1038 self.transaction_begun(*transaction_id, window, cx)
1039 }
1040 EditorEvent::TransactionUndone { transaction_id } => {
1041 self.transaction_undone(transaction_id, window, cx)
1042 }
1043 EditorEvent::Edited { .. } => self.push_to_change_list(window, cx),
1044 EditorEvent::FocusedIn => self.sync_vim_settings(window, cx),
1045 EditorEvent::CursorShapeChanged => self.cursor_shape_changed(window, cx),
1046 EditorEvent::PushedToNavHistory {
1047 anchor,
1048 is_deactivate,
1049 } => {
1050 self.update_editor(cx, |vim, editor, cx| {
1051 let mark = if *is_deactivate {
1052 "\"".to_string()
1053 } else {
1054 "'".to_string()
1055 };
1056 vim.set_mark(mark, vec![*anchor], editor.buffer(), window, cx);
1057 });
1058 }
1059 _ => {}
1060 }
1061 }
1062
1063 fn push_operator(&mut self, operator: Operator, window: &mut Window, cx: &mut Context<Self>) {
1064 if operator.starts_dot_recording() {
1065 self.start_recording(cx);
1066 }
1067 // Since these operations can only be entered with pre-operators,
1068 // we need to clear the previous operators when pushing,
1069 // so that the current stack is the most correct
1070 if matches!(
1071 operator,
1072 Operator::AddSurrounds { .. }
1073 | Operator::ChangeSurrounds { .. }
1074 | Operator::DeleteSurrounds
1075 | Operator::Exchange
1076 ) {
1077 self.operator_stack.clear();
1078 };
1079 self.operator_stack.push(operator);
1080 self.sync_vim_settings(window, cx);
1081 }
1082
1083 pub fn switch_mode(
1084 &mut self,
1085 mode: Mode,
1086 leave_selections: bool,
1087 window: &mut Window,
1088 cx: &mut Context<Self>,
1089 ) {
1090 if self.temp_mode && mode == Mode::Normal {
1091 self.temp_mode = false;
1092 self.switch_mode(Mode::Normal, leave_selections, window, cx);
1093 self.switch_mode(Mode::Insert, false, window, cx);
1094 return;
1095 } else if self.temp_mode
1096 && !matches!(mode, Mode::Visual | Mode::VisualLine | Mode::VisualBlock)
1097 {
1098 self.temp_mode = false;
1099 }
1100
1101 let last_mode = self.mode;
1102 let prior_mode = self.last_mode;
1103 let prior_tx = self.current_tx;
1104 self.status_label.take();
1105 self.last_mode = last_mode;
1106 self.mode = mode;
1107 self.operator_stack.clear();
1108 self.selected_register.take();
1109 self.cancel_running_command(window, cx);
1110 if mode == Mode::Normal || mode != last_mode {
1111 self.current_tx.take();
1112 self.current_anchor.take();
1113 self.update_editor(cx, |_, editor, _| {
1114 editor.clear_selection_drag_state();
1115 });
1116 }
1117 Vim::take_forced_motion(cx);
1118 if mode != Mode::Insert && mode != Mode::Replace {
1119 Vim::take_count(cx);
1120 }
1121
1122 // Sync editor settings like clip mode
1123 self.sync_vim_settings(window, cx);
1124
1125 if VimSettings::get_global(cx).toggle_relative_line_numbers
1126 && self.mode != self.last_mode
1127 && (self.mode == Mode::Insert || self.last_mode == Mode::Insert)
1128 {
1129 self.update_editor(cx, |vim, editor, cx| {
1130 let is_relative = vim.mode != Mode::Insert;
1131 editor.set_relative_line_number(Some(is_relative), cx)
1132 });
1133 }
1134 if HelixModeSetting::get_global(cx).0 {
1135 if self.mode == Mode::Normal {
1136 self.mode = Mode::HelixNormal
1137 } else if self.mode == Mode::Visual {
1138 self.mode = Mode::HelixSelect
1139 }
1140 }
1141
1142 if leave_selections {
1143 return;
1144 }
1145
1146 if !mode.is_visual() && last_mode.is_visual() {
1147 self.create_visual_marks(last_mode, window, cx);
1148 }
1149
1150 // Adjust selections
1151 self.update_editor(cx, |vim, editor, cx| {
1152 if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
1153 {
1154 vim.visual_block_motion(true, editor, window, cx, |_, point, goal| {
1155 Some((point, goal))
1156 })
1157 }
1158 if (last_mode == Mode::Insert || last_mode == Mode::Replace)
1159 && let Some(prior_tx) = prior_tx
1160 {
1161 editor.group_until_transaction(prior_tx, cx)
1162 }
1163
1164 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1165 // we cheat with visual block mode and use multiple cursors.
1166 // the cost of this cheat is we need to convert back to a single
1167 // cursor whenever vim would.
1168 if last_mode == Mode::VisualBlock
1169 && (mode != Mode::VisualBlock && mode != Mode::Insert)
1170 {
1171 let tail = s.oldest_anchor().tail();
1172 let head = s.newest_anchor().head();
1173 s.select_anchor_ranges(vec![tail..head]);
1174 } else if last_mode == Mode::Insert
1175 && prior_mode == Mode::VisualBlock
1176 && mode != Mode::VisualBlock
1177 {
1178 let pos = s.first_anchor().head();
1179 s.select_anchor_ranges(vec![pos..pos])
1180 }
1181
1182 let snapshot = s.display_map();
1183 if let Some(pending) = s.pending_anchor_mut()
1184 && pending.reversed
1185 && mode.is_visual()
1186 && !last_mode.is_visual()
1187 {
1188 let mut end = pending.end.to_point(&snapshot.buffer_snapshot());
1189 end = snapshot
1190 .buffer_snapshot()
1191 .clip_point(end + Point::new(0, 1), Bias::Right);
1192 pending.end = snapshot.buffer_snapshot().anchor_before(end);
1193 }
1194
1195 s.move_with(|map, selection| {
1196 if last_mode.is_visual() && !mode.is_visual() {
1197 let mut point = selection.head();
1198 if !selection.reversed && !selection.is_empty() {
1199 point = movement::left(map, selection.head());
1200 } else if selection.is_empty() {
1201 point = map.clip_point(point, Bias::Left);
1202 }
1203 selection.collapse_to(point, selection.goal)
1204 } else if !last_mode.is_visual() && mode.is_visual() && selection.is_empty() {
1205 selection.end = movement::right(map, selection.start);
1206 }
1207 });
1208 })
1209 });
1210 }
1211
1212 pub fn take_count(cx: &mut App) -> Option<usize> {
1213 let global_state = cx.global_mut::<VimGlobals>();
1214 if global_state.dot_replaying {
1215 return global_state.recorded_count;
1216 }
1217
1218 let count = if global_state.post_count.is_none() && global_state.pre_count.is_none() {
1219 return None;
1220 } else {
1221 Some(
1222 global_state.post_count.take().unwrap_or(1)
1223 * global_state.pre_count.take().unwrap_or(1),
1224 )
1225 };
1226
1227 if global_state.dot_recording {
1228 global_state.recorded_count = count;
1229 }
1230 count
1231 }
1232
1233 pub fn take_forced_motion(cx: &mut App) -> bool {
1234 let global_state = cx.global_mut::<VimGlobals>();
1235 let forced_motion = global_state.forced_motion;
1236 global_state.forced_motion = false;
1237 forced_motion
1238 }
1239
1240 pub fn cursor_shape(&self, cx: &mut App) -> CursorShape {
1241 let cursor_shape = VimSettings::get_global(cx).cursor_shape;
1242 match self.mode {
1243 Mode::Normal => {
1244 if let Some(operator) = self.operator_stack.last() {
1245 match operator {
1246 // Navigation operators -> Block cursor
1247 Operator::FindForward { .. }
1248 | Operator::FindBackward { .. }
1249 | Operator::Mark
1250 | Operator::Jump { .. }
1251 | Operator::Register
1252 | Operator::RecordRegister
1253 | Operator::ReplayRegister => CursorShape::Block,
1254
1255 // All other operators -> Underline cursor
1256 _ => CursorShape::Underline,
1257 }
1258 } else {
1259 cursor_shape.normal.unwrap_or(CursorShape::Block)
1260 }
1261 }
1262 Mode::HelixNormal => cursor_shape.normal.unwrap_or(CursorShape::Block),
1263 Mode::Replace => cursor_shape.replace.unwrap_or(CursorShape::Underline),
1264 Mode::Visual | Mode::VisualLine | Mode::VisualBlock | Mode::HelixSelect => {
1265 cursor_shape.visual.unwrap_or(CursorShape::Block)
1266 }
1267 Mode::Insert => cursor_shape.insert.unwrap_or({
1268 let editor_settings = EditorSettings::get_global(cx);
1269 editor_settings.cursor_shape.unwrap_or_default()
1270 }),
1271 }
1272 }
1273
1274 pub fn editor_input_enabled(&self) -> bool {
1275 match self.mode {
1276 Mode::Insert => {
1277 if let Some(operator) = self.operator_stack.last() {
1278 !operator.is_waiting(self.mode)
1279 } else {
1280 true
1281 }
1282 }
1283 Mode::Normal
1284 | Mode::HelixNormal
1285 | Mode::Replace
1286 | Mode::Visual
1287 | Mode::VisualLine
1288 | Mode::VisualBlock
1289 | Mode::HelixSelect => false,
1290 }
1291 }
1292
1293 pub fn should_autoindent(&self) -> bool {
1294 !(self.mode == Mode::Insert && self.last_mode == Mode::VisualBlock)
1295 }
1296
1297 pub fn clip_at_line_ends(&self) -> bool {
1298 match self.mode {
1299 Mode::Insert
1300 | Mode::Visual
1301 | Mode::VisualLine
1302 | Mode::VisualBlock
1303 | Mode::Replace
1304 | Mode::HelixNormal
1305 | Mode::HelixSelect => false,
1306 Mode::Normal => true,
1307 }
1308 }
1309
1310 pub fn extend_key_context(&self, context: &mut KeyContext, cx: &App) {
1311 let mut mode = match self.mode {
1312 Mode::Normal => "normal",
1313 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => "visual",
1314 Mode::Insert => "insert",
1315 Mode::Replace => "replace",
1316 Mode::HelixNormal => "helix_normal",
1317 Mode::HelixSelect => "helix_select",
1318 }
1319 .to_string();
1320
1321 let mut operator_id = "none";
1322
1323 let active_operator = self.active_operator();
1324 if active_operator.is_none() && cx.global::<VimGlobals>().pre_count.is_some()
1325 || active_operator.is_some() && cx.global::<VimGlobals>().post_count.is_some()
1326 {
1327 context.add("VimCount");
1328 }
1329
1330 if let Some(active_operator) = active_operator {
1331 if active_operator.is_waiting(self.mode) {
1332 if matches!(active_operator, Operator::Literal { .. }) {
1333 mode = "literal".to_string();
1334 } else {
1335 mode = "waiting".to_string();
1336 }
1337 } else {
1338 operator_id = active_operator.id();
1339 mode = "operator".to_string();
1340 }
1341 }
1342
1343 if mode == "normal"
1344 || mode == "visual"
1345 || mode == "operator"
1346 || mode == "helix_normal"
1347 || mode == "helix_select"
1348 {
1349 context.add("VimControl");
1350 }
1351 context.set("vim_mode", mode);
1352 context.set("vim_operator", operator_id);
1353 }
1354
1355 fn focused(&mut self, preserve_selection: bool, window: &mut Window, cx: &mut Context<Self>) {
1356 let Some(editor) = self.editor() else {
1357 return;
1358 };
1359 let newest_selection_empty = editor.update(cx, |editor, cx| {
1360 editor
1361 .selections
1362 .newest::<usize>(&editor.display_snapshot(cx))
1363 .is_empty()
1364 });
1365 let editor = editor.read(cx);
1366 let editor_mode = editor.mode();
1367
1368 if editor_mode.is_full()
1369 && !newest_selection_empty
1370 && self.mode == Mode::Normal
1371 // When following someone, don't switch vim mode.
1372 && editor.leader_id().is_none()
1373 {
1374 if preserve_selection {
1375 self.switch_mode(Mode::Visual, true, window, cx);
1376 } else {
1377 self.update_editor(cx, |_, editor, cx| {
1378 editor.set_clip_at_line_ends(false, cx);
1379 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1380 s.move_with(|_, selection| {
1381 selection.collapse_to(selection.start, selection.goal)
1382 })
1383 });
1384 });
1385 }
1386 }
1387
1388 cx.emit(VimEvent::Focused);
1389 self.sync_vim_settings(window, cx);
1390
1391 if VimSettings::get_global(cx).toggle_relative_line_numbers {
1392 if let Some(old_vim) = Vim::globals(cx).focused_vim() {
1393 if old_vim.entity_id() != cx.entity().entity_id() {
1394 old_vim.update(cx, |vim, cx| {
1395 vim.update_editor(cx, |_, editor, cx| {
1396 editor.set_relative_line_number(None, cx)
1397 });
1398 });
1399
1400 self.update_editor(cx, |vim, editor, cx| {
1401 let is_relative = vim.mode != Mode::Insert;
1402 editor.set_relative_line_number(Some(is_relative), cx)
1403 });
1404 }
1405 } else {
1406 self.update_editor(cx, |vim, editor, cx| {
1407 let is_relative = vim.mode != Mode::Insert;
1408 editor.set_relative_line_number(Some(is_relative), cx)
1409 });
1410 }
1411 }
1412 Vim::globals(cx).focused_vim = Some(cx.entity().downgrade());
1413 }
1414
1415 fn blurred(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1416 self.stop_recording_immediately(NormalBefore.boxed_clone(), cx);
1417 self.store_visual_marks(window, cx);
1418 self.clear_operator(window, cx);
1419 self.update_editor(cx, |vim, editor, cx| {
1420 if vim.cursor_shape(cx) == CursorShape::Block {
1421 editor.set_cursor_shape(CursorShape::Hollow, cx);
1422 }
1423 });
1424 }
1425
1426 fn cursor_shape_changed(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1427 self.update_editor(cx, |vim, editor, cx| {
1428 editor.set_cursor_shape(vim.cursor_shape(cx), cx);
1429 });
1430 }
1431
1432 fn update_editor<S>(
1433 &mut self,
1434 cx: &mut Context<Self>,
1435 update: impl FnOnce(&mut Self, &mut Editor, &mut Context<Editor>) -> S,
1436 ) -> Option<S> {
1437 let editor = self.editor.upgrade()?;
1438 Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
1439 }
1440
1441 fn editor_selections(&mut self, _: &mut Window, cx: &mut Context<Self>) -> Vec<Range<Anchor>> {
1442 self.update_editor(cx, |_, editor, _| {
1443 editor
1444 .selections
1445 .disjoint_anchors_arc()
1446 .iter()
1447 .map(|selection| selection.tail()..selection.head())
1448 .collect()
1449 })
1450 .unwrap_or_default()
1451 }
1452
1453 fn editor_cursor_word(
1454 &mut self,
1455 window: &mut Window,
1456 cx: &mut Context<Self>,
1457 ) -> Option<String> {
1458 self.update_editor(cx, |_, editor, cx| {
1459 let snapshot = &editor.snapshot(window, cx);
1460 let selection = editor
1461 .selections
1462 .newest::<usize>(&snapshot.display_snapshot);
1463
1464 let snapshot = snapshot.buffer_snapshot();
1465 let (range, kind) =
1466 snapshot.surrounding_word(selection.start, Some(CharScopeContext::Completion));
1467 if kind == Some(CharKind::Word) {
1468 let text: String = snapshot.text_for_range(range).collect();
1469 if !text.trim().is_empty() {
1470 return Some(text);
1471 }
1472 }
1473
1474 None
1475 })
1476 .unwrap_or_default()
1477 }
1478
1479 /// When doing an action that modifies the buffer, we start recording so that `.`
1480 /// will replay the action.
1481 pub fn start_recording(&mut self, cx: &mut Context<Self>) {
1482 Vim::update_globals(cx, |globals, cx| {
1483 if !globals.dot_replaying {
1484 globals.dot_recording = true;
1485 globals.recording_actions = Default::default();
1486 globals.recorded_count = None;
1487
1488 let selections = self.editor().map(|editor| {
1489 editor.update(cx, |editor, cx| {
1490 let snapshot = editor.display_snapshot(cx);
1491
1492 (
1493 editor.selections.oldest::<Point>(&snapshot),
1494 editor.selections.newest::<Point>(&snapshot),
1495 )
1496 })
1497 });
1498
1499 if let Some((oldest, newest)) = selections {
1500 globals.recorded_selection = match self.mode {
1501 Mode::Visual if newest.end.row == newest.start.row => {
1502 RecordedSelection::SingleLine {
1503 cols: newest.end.column - newest.start.column,
1504 }
1505 }
1506 Mode::Visual => RecordedSelection::Visual {
1507 rows: newest.end.row - newest.start.row,
1508 cols: newest.end.column,
1509 },
1510 Mode::VisualLine => RecordedSelection::VisualLine {
1511 rows: newest.end.row - newest.start.row,
1512 },
1513 Mode::VisualBlock => RecordedSelection::VisualBlock {
1514 rows: newest.end.row.abs_diff(oldest.start.row),
1515 cols: newest.end.column.abs_diff(oldest.start.column),
1516 },
1517 _ => RecordedSelection::None,
1518 }
1519 } else {
1520 globals.recorded_selection = RecordedSelection::None;
1521 }
1522 }
1523 })
1524 }
1525
1526 pub fn stop_replaying(&mut self, cx: &mut Context<Self>) {
1527 let globals = Vim::globals(cx);
1528 globals.dot_replaying = false;
1529 if let Some(replayer) = globals.replayer.take() {
1530 replayer.stop();
1531 }
1532 }
1533
1534 /// When finishing an action that modifies the buffer, stop recording.
1535 /// as you usually call this within a keystroke handler we also ensure that
1536 /// the current action is recorded.
1537 pub fn stop_recording(&mut self, cx: &mut Context<Self>) {
1538 let globals = Vim::globals(cx);
1539 if globals.dot_recording {
1540 globals.stop_recording_after_next_action = true;
1541 }
1542 self.exit_temporary_mode = self.temp_mode;
1543 }
1544
1545 /// Stops recording actions immediately rather than waiting until after the
1546 /// next action to stop recording.
1547 ///
1548 /// This doesn't include the current action.
1549 pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>, cx: &mut Context<Self>) {
1550 let globals = Vim::globals(cx);
1551 if globals.dot_recording {
1552 globals
1553 .recording_actions
1554 .push(ReplayableAction::Action(action.boxed_clone()));
1555 globals.recorded_actions = mem::take(&mut globals.recording_actions);
1556 globals.dot_recording = false;
1557 globals.stop_recording_after_next_action = false;
1558 }
1559 self.exit_temporary_mode = self.temp_mode;
1560 }
1561
1562 /// Explicitly record one action (equivalents to start_recording and stop_recording)
1563 pub fn record_current_action(&mut self, cx: &mut Context<Self>) {
1564 self.start_recording(cx);
1565 self.stop_recording(cx);
1566 }
1567
1568 fn push_count_digit(&mut self, number: usize, window: &mut Window, cx: &mut Context<Self>) {
1569 if self.active_operator().is_some() {
1570 let post_count = Vim::globals(cx).post_count.unwrap_or(0);
1571
1572 Vim::globals(cx).post_count = Some(
1573 post_count
1574 .checked_mul(10)
1575 .and_then(|post_count| post_count.checked_add(number))
1576 .filter(|post_count| *post_count < isize::MAX as usize)
1577 .unwrap_or(post_count),
1578 )
1579 } else {
1580 let pre_count = Vim::globals(cx).pre_count.unwrap_or(0);
1581
1582 Vim::globals(cx).pre_count = Some(
1583 pre_count
1584 .checked_mul(10)
1585 .and_then(|pre_count| pre_count.checked_add(number))
1586 .filter(|pre_count| *pre_count < isize::MAX as usize)
1587 .unwrap_or(pre_count),
1588 )
1589 }
1590 // update the keymap so that 0 works
1591 self.sync_vim_settings(window, cx)
1592 }
1593
1594 fn select_register(&mut self, register: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
1595 if register.chars().count() == 1 {
1596 self.selected_register
1597 .replace(register.chars().next().unwrap());
1598 }
1599 self.operator_stack.clear();
1600 self.sync_vim_settings(window, cx);
1601 }
1602
1603 fn maybe_pop_operator(&mut self) -> Option<Operator> {
1604 self.operator_stack.pop()
1605 }
1606
1607 fn pop_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Operator {
1608 let popped_operator = self.operator_stack.pop()
1609 .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
1610 self.sync_vim_settings(window, cx);
1611 popped_operator
1612 }
1613
1614 fn clear_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1615 Vim::take_count(cx);
1616 Vim::take_forced_motion(cx);
1617 self.selected_register.take();
1618 self.operator_stack.clear();
1619 self.sync_vim_settings(window, cx);
1620 }
1621
1622 fn active_operator(&self) -> Option<Operator> {
1623 self.operator_stack.last().cloned()
1624 }
1625
1626 fn transaction_begun(
1627 &mut self,
1628 transaction_id: TransactionId,
1629 _window: &mut Window,
1630 _: &mut Context<Self>,
1631 ) {
1632 let mode = if (self.mode == Mode::Insert
1633 || self.mode == Mode::Replace
1634 || self.mode == Mode::Normal)
1635 && self.current_tx.is_none()
1636 {
1637 self.current_tx = Some(transaction_id);
1638 self.last_mode
1639 } else {
1640 self.mode
1641 };
1642 if mode == Mode::VisualLine || mode == Mode::VisualBlock {
1643 self.undo_modes.insert(transaction_id, mode);
1644 }
1645 }
1646
1647 fn transaction_undone(
1648 &mut self,
1649 transaction_id: &TransactionId,
1650 window: &mut Window,
1651 cx: &mut Context<Self>,
1652 ) {
1653 match self.mode {
1654 Mode::VisualLine | Mode::VisualBlock | Mode::Visual | Mode::HelixSelect => {
1655 self.update_editor(cx, |vim, editor, cx| {
1656 let original_mode = vim.undo_modes.get(transaction_id);
1657 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1658 match original_mode {
1659 Some(Mode::VisualLine) => {
1660 s.move_with(|map, selection| {
1661 selection.collapse_to(
1662 map.prev_line_boundary(selection.start.to_point(map)).1,
1663 SelectionGoal::None,
1664 )
1665 });
1666 }
1667 Some(Mode::VisualBlock) => {
1668 let mut first = s.first_anchor();
1669 first.collapse_to(first.start, first.goal);
1670 s.select_anchors(vec![first]);
1671 }
1672 _ => {
1673 s.move_with(|map, selection| {
1674 selection.collapse_to(
1675 map.clip_at_line_end(selection.start),
1676 selection.goal,
1677 );
1678 });
1679 }
1680 }
1681 });
1682 });
1683 self.switch_mode(Mode::Normal, true, window, cx)
1684 }
1685 Mode::Normal => {
1686 self.update_editor(cx, |_, editor, cx| {
1687 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1688 s.move_with(|map, selection| {
1689 selection
1690 .collapse_to(map.clip_at_line_end(selection.end), selection.goal)
1691 })
1692 })
1693 });
1694 }
1695 Mode::Insert | Mode::Replace | Mode::HelixNormal => {}
1696 }
1697 }
1698
1699 fn local_selections_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1700 let Some(editor) = self.editor() else { return };
1701
1702 if editor.read(cx).leader_id().is_some() {
1703 return;
1704 }
1705
1706 let newest = editor.read(cx).selections.newest_anchor().clone();
1707 let is_multicursor = editor.read(cx).selections.count() > 1;
1708 if self.mode == Mode::Insert && self.current_tx.is_some() {
1709 if self.current_anchor.is_none() {
1710 self.current_anchor = Some(newest);
1711 } else if self.current_anchor.as_ref().unwrap() != &newest
1712 && let Some(tx_id) = self.current_tx.take()
1713 {
1714 self.update_editor(cx, |_, editor, cx| {
1715 editor.group_until_transaction(tx_id, cx)
1716 });
1717 }
1718 } else if self.mode == Mode::Normal && newest.start != newest.end {
1719 if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
1720 self.switch_mode(Mode::VisualBlock, false, window, cx);
1721 } else {
1722 self.switch_mode(Mode::Visual, false, window, cx)
1723 }
1724 } else if newest.start == newest.end
1725 && !is_multicursor
1726 && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&self.mode)
1727 {
1728 self.switch_mode(Mode::Normal, false, window, cx);
1729 }
1730 }
1731
1732 fn input_ignored(&mut self, text: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
1733 if text.is_empty() {
1734 return;
1735 }
1736
1737 match self.active_operator() {
1738 Some(Operator::FindForward { before, multiline }) => {
1739 let find = Motion::FindForward {
1740 before,
1741 char: text.chars().next().unwrap(),
1742 mode: if multiline {
1743 FindRange::MultiLine
1744 } else {
1745 FindRange::SingleLine
1746 },
1747 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1748 };
1749 Vim::globals(cx).last_find = Some(find.clone());
1750 self.motion(find, window, cx)
1751 }
1752 Some(Operator::FindBackward { after, multiline }) => {
1753 let find = Motion::FindBackward {
1754 after,
1755 char: text.chars().next().unwrap(),
1756 mode: if multiline {
1757 FindRange::MultiLine
1758 } else {
1759 FindRange::SingleLine
1760 },
1761 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1762 };
1763 Vim::globals(cx).last_find = Some(find.clone());
1764 self.motion(find, window, cx)
1765 }
1766 Some(Operator::Sneak { first_char }) => {
1767 if let Some(first_char) = first_char {
1768 if let Some(second_char) = text.chars().next() {
1769 let sneak = Motion::Sneak {
1770 first_char,
1771 second_char,
1772 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1773 };
1774 Vim::globals(cx).last_find = Some(sneak.clone());
1775 self.motion(sneak, window, cx)
1776 }
1777 } else {
1778 let first_char = text.chars().next();
1779 self.pop_operator(window, cx);
1780 self.push_operator(Operator::Sneak { first_char }, window, cx);
1781 }
1782 }
1783 Some(Operator::SneakBackward { first_char }) => {
1784 if let Some(first_char) = first_char {
1785 if let Some(second_char) = text.chars().next() {
1786 let sneak = Motion::SneakBackward {
1787 first_char,
1788 second_char,
1789 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1790 };
1791 Vim::globals(cx).last_find = Some(sneak.clone());
1792 self.motion(sneak, window, cx)
1793 }
1794 } else {
1795 let first_char = text.chars().next();
1796 self.pop_operator(window, cx);
1797 self.push_operator(Operator::SneakBackward { first_char }, window, cx);
1798 }
1799 }
1800 Some(Operator::Replace) => match self.mode {
1801 Mode::Normal => self.normal_replace(text, window, cx),
1802 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1803 self.visual_replace(text, window, cx)
1804 }
1805 Mode::HelixNormal => self.helix_replace(&text, window, cx),
1806 _ => self.clear_operator(window, cx),
1807 },
1808 Some(Operator::Digraph { first_char }) => {
1809 if let Some(first_char) = first_char {
1810 if let Some(second_char) = text.chars().next() {
1811 self.insert_digraph(first_char, second_char, window, cx);
1812 }
1813 } else {
1814 let first_char = text.chars().next();
1815 self.pop_operator(window, cx);
1816 self.push_operator(Operator::Digraph { first_char }, window, cx);
1817 }
1818 }
1819 Some(Operator::Literal { prefix }) => {
1820 self.handle_literal_input(prefix.unwrap_or_default(), &text, window, cx)
1821 }
1822 Some(Operator::AddSurrounds { target }) => match self.mode {
1823 Mode::Normal => {
1824 if let Some(target) = target {
1825 self.add_surrounds(text, target, window, cx);
1826 self.clear_operator(window, cx);
1827 }
1828 }
1829 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1830 self.add_surrounds(text, SurroundsType::Selection, window, cx);
1831 self.clear_operator(window, cx);
1832 }
1833 _ => self.clear_operator(window, cx),
1834 },
1835 Some(Operator::ChangeSurrounds { target, opening }) => match self.mode {
1836 Mode::Normal => {
1837 if let Some(target) = target {
1838 self.change_surrounds(text, target, opening, window, cx);
1839 self.clear_operator(window, cx);
1840 }
1841 }
1842 _ => self.clear_operator(window, cx),
1843 },
1844 Some(Operator::DeleteSurrounds) => match self.mode {
1845 Mode::Normal => {
1846 self.delete_surrounds(text, window, cx);
1847 self.clear_operator(window, cx);
1848 }
1849 _ => self.clear_operator(window, cx),
1850 },
1851 Some(Operator::Mark) => self.create_mark(text, window, cx),
1852 Some(Operator::RecordRegister) => {
1853 self.record_register(text.chars().next().unwrap(), window, cx)
1854 }
1855 Some(Operator::ReplayRegister) => {
1856 self.replay_register(text.chars().next().unwrap(), window, cx)
1857 }
1858 Some(Operator::Register) => match self.mode {
1859 Mode::Insert => {
1860 self.update_editor(cx, |_, editor, cx| {
1861 if let Some(register) = Vim::update_globals(cx, |globals, cx| {
1862 globals.read_register(text.chars().next(), Some(editor), cx)
1863 }) {
1864 editor.do_paste(
1865 ®ister.text.to_string(),
1866 register.clipboard_selections,
1867 false,
1868 window,
1869 cx,
1870 )
1871 }
1872 });
1873 self.clear_operator(window, cx);
1874 }
1875 _ => {
1876 self.select_register(text, window, cx);
1877 }
1878 },
1879 Some(Operator::Jump { line }) => self.jump(text, line, true, window, cx),
1880 _ => {
1881 if self.mode == Mode::Replace {
1882 self.multi_replace(text, window, cx)
1883 }
1884
1885 if self.mode == Mode::Normal {
1886 self.update_editor(cx, |_, editor, cx| {
1887 editor.accept_edit_prediction(
1888 &editor::actions::AcceptEditPrediction {},
1889 window,
1890 cx,
1891 );
1892 });
1893 }
1894 }
1895 }
1896 }
1897
1898 fn sync_vim_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1899 self.update_editor(cx, |vim, editor, cx| {
1900 editor.set_cursor_shape(vim.cursor_shape(cx), cx);
1901 editor.set_clip_at_line_ends(vim.clip_at_line_ends(), cx);
1902 editor.set_collapse_matches(true);
1903 editor.set_input_enabled(vim.editor_input_enabled());
1904 editor.set_autoindent(vim.should_autoindent());
1905 editor
1906 .selections
1907 .set_line_mode(matches!(vim.mode, Mode::VisualLine));
1908
1909 let hide_edit_predictions = !matches!(vim.mode, Mode::Insert | Mode::Replace);
1910 editor.set_edit_predictions_hidden_for_vim_mode(hide_edit_predictions, window, cx);
1911 });
1912 cx.notify()
1913 }
1914}
1915
1916struct VimSettings {
1917 pub default_mode: Mode,
1918 pub toggle_relative_line_numbers: bool,
1919 pub use_system_clipboard: settings::UseSystemClipboard,
1920 pub use_smartcase_find: bool,
1921 pub custom_digraphs: HashMap<String, Arc<str>>,
1922 pub highlight_on_yank_duration: u64,
1923 pub cursor_shape: CursorShapeSettings,
1924}
1925
1926/// The settings for cursor shape.
1927#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1928pub struct CursorShapeSettings {
1929 /// Cursor shape for the normal mode.
1930 ///
1931 /// Default: block
1932 pub normal: Option<CursorShape>,
1933 /// Cursor shape for the replace mode.
1934 ///
1935 /// Default: underline
1936 pub replace: Option<CursorShape>,
1937 /// Cursor shape for the visual mode.
1938 ///
1939 /// Default: block
1940 pub visual: Option<CursorShape>,
1941 /// Cursor shape for the insert mode.
1942 ///
1943 /// The default value follows the primary cursor_shape.
1944 pub insert: Option<CursorShape>,
1945}
1946
1947impl From<settings::CursorShapeSettings> for CursorShapeSettings {
1948 fn from(settings: settings::CursorShapeSettings) -> Self {
1949 Self {
1950 normal: settings.normal.map(Into::into),
1951 replace: settings.replace.map(Into::into),
1952 visual: settings.visual.map(Into::into),
1953 insert: settings.insert.map(Into::into),
1954 }
1955 }
1956}
1957
1958impl From<settings::ModeContent> for Mode {
1959 fn from(mode: ModeContent) -> Self {
1960 match mode {
1961 ModeContent::Normal => Self::Normal,
1962 ModeContent::Insert => Self::Insert,
1963 }
1964 }
1965}
1966
1967impl Settings for VimSettings {
1968 fn from_settings(content: &settings::SettingsContent) -> Self {
1969 let vim = content.vim.clone().unwrap();
1970 Self {
1971 default_mode: vim.default_mode.unwrap().into(),
1972 toggle_relative_line_numbers: vim.toggle_relative_line_numbers.unwrap(),
1973 use_system_clipboard: vim.use_system_clipboard.unwrap(),
1974 use_smartcase_find: vim.use_smartcase_find.unwrap(),
1975 custom_digraphs: vim.custom_digraphs.unwrap(),
1976 highlight_on_yank_duration: vim.highlight_on_yank_duration.unwrap(),
1977 cursor_shape: vim.cursor_shape.unwrap().into(),
1978 }
1979 }
1980}