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