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