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