1//! Vim support for Zed.
2
3#[cfg(test)]
4mod test;
5
6mod change_list;
7mod command;
8mod digraph;
9mod helix;
10mod indent;
11mod insert;
12mod mode_indicator;
13mod motion;
14mod normal;
15mod object;
16mod replace;
17mod rewrap;
18mod state;
19mod surrounds;
20mod visual;
21
22use crate::normal::paste::Paste as VimPaste;
23use collections::HashMap;
24use editor::{
25 Anchor, Bias, Editor, EditorEvent, EditorSettings, HideMouseCursorOrigin, MultiBufferOffset,
26 SelectionEffects,
27 actions::Paste,
28 display_map::ToDisplayPoint,
29 movement::{self, FindRange},
30};
31use gpui::{
32 Action, App, AppContext, Axis, Context, Entity, EventEmitter, KeyContext, KeystrokeEvent,
33 Render, Subscription, Task, WeakEntity, Window, actions,
34};
35use insert::{NormalBefore, TemporaryNormal};
36use language::{
37 CharKind, CharScopeContext, CursorShape, Point, Selection, SelectionGoal, TransactionId,
38};
39pub use mode_indicator::ModeIndicator;
40use motion::Motion;
41use multi_buffer::ToPoint as _;
42use normal::search::SearchSubmit;
43use object::Object;
44use schemars::JsonSchema;
45use search::BufferSearchBar;
46use serde::Deserialize;
47use settings::RegisterSetting;
48pub use settings::{
49 ModeContent, Settings, SettingsStore, UseSystemClipboard, update_settings_file,
50};
51use state::{Mode, Operator, RecordedSelection, SearchState, VimGlobals};
52use std::{mem, ops::Range, sync::Arc};
53use surrounds::SurroundsType;
54use theme_settings::ThemeSettings;
55use ui::{IntoElement, SharedString, px};
56use vim_mode_setting::HelixModeSetting;
57use vim_mode_setting::VimModeSetting;
58use workspace::{self, Pane, Workspace};
59
60use crate::{
61 normal::{GoToPreviousTab, GoToTab},
62 state::ReplayableAction,
63};
64
65/// Number is used to manage vim's count. Pushing a digit
66/// multiplies the current value by 10 and adds the digit.
67#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
68#[action(namespace = vim)]
69struct Number(usize);
70
71#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
72#[action(namespace = vim)]
73struct SelectRegister(String);
74
75#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
76#[action(namespace = vim)]
77#[serde(deny_unknown_fields)]
78struct PushObject {
79 around: bool,
80}
81
82#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
83#[action(namespace = vim)]
84#[serde(deny_unknown_fields)]
85struct PushFindForward {
86 before: bool,
87 multiline: bool,
88}
89
90#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
91#[action(namespace = vim)]
92#[serde(deny_unknown_fields)]
93struct PushFindBackward {
94 after: bool,
95 multiline: bool,
96}
97
98#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
99#[action(namespace = vim)]
100#[serde(deny_unknown_fields)]
101/// Selects the next object.
102struct PushHelixNext {
103 around: bool,
104}
105
106#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
107#[action(namespace = vim)]
108#[serde(deny_unknown_fields)]
109/// Selects the previous object.
110struct PushHelixPrevious {
111 around: bool,
112}
113
114#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
115#[action(namespace = vim)]
116#[serde(deny_unknown_fields)]
117struct PushSneak {
118 first_char: Option<char>,
119}
120
121#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
122#[action(namespace = vim)]
123#[serde(deny_unknown_fields)]
124struct PushSneakBackward {
125 first_char: Option<char>,
126}
127
128#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
129#[action(namespace = vim)]
130#[serde(deny_unknown_fields)]
131struct PushAddSurrounds;
132
133#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
134#[action(namespace = vim)]
135#[serde(deny_unknown_fields)]
136struct PushChangeSurrounds {
137 target: Option<Object>,
138}
139
140#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
141#[action(namespace = vim)]
142#[serde(deny_unknown_fields)]
143struct PushJump {
144 line: bool,
145}
146
147#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
148#[action(namespace = vim)]
149#[serde(deny_unknown_fields)]
150struct PushDigraph {
151 first_char: Option<char>,
152}
153
154#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
155#[action(namespace = vim)]
156#[serde(deny_unknown_fields)]
157struct PushLiteral {
158 prefix: Option<String>,
159}
160
161actions!(
162 vim,
163 [
164 /// Switches to normal mode.
165 SwitchToNormalMode,
166 /// Switches to insert mode.
167 SwitchToInsertMode,
168 /// Switches to replace mode.
169 SwitchToReplaceMode,
170 /// Switches to visual mode.
171 SwitchToVisualMode,
172 /// Switches to visual line mode.
173 SwitchToVisualLineMode,
174 /// Switches to visual block mode.
175 SwitchToVisualBlockMode,
176 /// Switches to Helix-style normal mode.
177 SwitchToHelixNormalMode,
178 /// Clears any pending operators.
179 ClearOperators,
180 /// Clears the exchange register.
181 ClearExchange,
182 /// Inserts a tab character.
183 Tab,
184 /// Inserts a newline.
185 Enter,
186 /// Selects inner text object.
187 InnerObject,
188 /// Maximizes the current pane.
189 MaximizePane,
190 /// Resets all pane sizes to default.
191 ResetPaneSizes,
192 /// Resizes the pane to the right.
193 ResizePaneRight,
194 /// Resizes the pane to the left.
195 ResizePaneLeft,
196 /// Resizes the pane upward.
197 ResizePaneUp,
198 /// Resizes the pane downward.
199 ResizePaneDown,
200 /// Starts a change operation.
201 PushChange,
202 /// Starts a delete operation.
203 PushDelete,
204 /// Exchanges text regions.
205 Exchange,
206 /// Starts a yank operation.
207 PushYank,
208 /// Starts a replace operation.
209 PushReplace,
210 /// Deletes surrounding characters.
211 PushDeleteSurrounds,
212 /// Sets a mark at the current position.
213 PushMark,
214 /// Toggles the marks view.
215 ToggleMarksView,
216 /// Starts a forced motion.
217 PushForcedMotion,
218 /// Starts an indent operation.
219 PushIndent,
220 /// Starts an outdent operation.
221 PushOutdent,
222 /// Starts an auto-indent operation.
223 PushAutoIndent,
224 /// Starts a rewrap operation.
225 PushRewrap,
226 /// Starts a shell command operation.
227 PushShellCommand,
228 /// Converts to lowercase.
229 PushLowercase,
230 /// Converts to uppercase.
231 PushUppercase,
232 /// Toggles case.
233 PushOppositeCase,
234 /// Applies ROT13 encoding.
235 PushRot13,
236 /// Applies ROT47 encoding.
237 PushRot47,
238 /// Toggles the registers view.
239 ToggleRegistersView,
240 /// Selects a register.
241 PushRegister,
242 /// Starts recording to a register.
243 PushRecordRegister,
244 /// Replays a register.
245 PushReplayRegister,
246 /// Replaces with register contents.
247 PushReplaceWithRegister,
248 /// Toggles comments.
249 PushToggleComments,
250 /// Selects (count) next menu item
251 MenuSelectNext,
252 /// Selects (count) previous menu item
253 MenuSelectPrevious,
254 /// Clears count or toggles project panel focus
255 ToggleProjectPanelFocus,
256 /// Starts a match operation.
257 PushHelixMatch,
258 /// 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 },
772 window,
773 cx,
774 )
775 },
776 );
777
778 Vim::action(editor, cx, |vim, action: &PushJump, window, cx| {
779 vim.push_operator(Operator::Jump { line: action.line }, window, cx)
780 });
781
782 Vim::action(editor, cx, |vim, action: &PushDigraph, window, cx| {
783 vim.push_operator(
784 Operator::Digraph {
785 first_char: action.first_char,
786 },
787 window,
788 cx,
789 )
790 });
791
792 Vim::action(editor, cx, |vim, action: &PushLiteral, window, cx| {
793 vim.push_operator(
794 Operator::Literal {
795 prefix: action.prefix.clone(),
796 },
797 window,
798 cx,
799 )
800 });
801
802 Vim::action(editor, cx, |vim, _: &PushChange, window, cx| {
803 vim.push_operator(Operator::Change, window, cx)
804 });
805
806 Vim::action(editor, cx, |vim, _: &PushDelete, window, cx| {
807 vim.push_operator(Operator::Delete, window, cx)
808 });
809
810 Vim::action(editor, cx, |vim, _: &PushYank, window, cx| {
811 vim.push_operator(Operator::Yank, window, cx)
812 });
813
814 Vim::action(editor, cx, |vim, _: &PushReplace, window, cx| {
815 vim.push_operator(Operator::Replace, window, cx)
816 });
817
818 Vim::action(editor, cx, |vim, _: &PushDeleteSurrounds, window, cx| {
819 vim.push_operator(Operator::DeleteSurrounds, window, cx)
820 });
821
822 Vim::action(editor, cx, |vim, _: &PushMark, window, cx| {
823 vim.push_operator(Operator::Mark, window, cx)
824 });
825
826 Vim::action(editor, cx, |vim, _: &PushIndent, window, cx| {
827 vim.push_operator(Operator::Indent, window, cx)
828 });
829
830 Vim::action(editor, cx, |vim, _: &PushOutdent, window, cx| {
831 vim.push_operator(Operator::Outdent, window, cx)
832 });
833
834 Vim::action(editor, cx, |vim, _: &PushAutoIndent, window, cx| {
835 vim.push_operator(Operator::AutoIndent, window, cx)
836 });
837
838 Vim::action(editor, cx, |vim, _: &PushRewrap, window, cx| {
839 vim.push_operator(Operator::Rewrap, window, cx)
840 });
841
842 Vim::action(editor, cx, |vim, _: &PushShellCommand, window, cx| {
843 vim.push_operator(Operator::ShellCommand, window, cx)
844 });
845
846 Vim::action(editor, cx, |vim, _: &PushLowercase, window, cx| {
847 vim.push_operator(Operator::Lowercase, window, cx)
848 });
849
850 Vim::action(editor, cx, |vim, _: &PushUppercase, window, cx| {
851 vim.push_operator(Operator::Uppercase, window, cx)
852 });
853
854 Vim::action(editor, cx, |vim, _: &PushOppositeCase, window, cx| {
855 vim.push_operator(Operator::OppositeCase, window, cx)
856 });
857
858 Vim::action(editor, cx, |vim, _: &PushRot13, window, cx| {
859 vim.push_operator(Operator::Rot13, window, cx)
860 });
861
862 Vim::action(editor, cx, |vim, _: &PushRot47, window, cx| {
863 vim.push_operator(Operator::Rot47, window, cx)
864 });
865
866 Vim::action(editor, cx, |vim, _: &PushRegister, window, cx| {
867 vim.push_operator(Operator::Register, window, cx)
868 });
869
870 Vim::action(editor, cx, |vim, _: &PushRecordRegister, window, cx| {
871 vim.push_operator(Operator::RecordRegister, window, cx)
872 });
873
874 Vim::action(editor, cx, |vim, _: &PushReplayRegister, window, cx| {
875 vim.push_operator(Operator::ReplayRegister, window, cx)
876 });
877
878 Vim::action(
879 editor,
880 cx,
881 |vim, _: &PushReplaceWithRegister, window, cx| {
882 vim.push_operator(Operator::ReplaceWithRegister, window, cx)
883 },
884 );
885
886 Vim::action(editor, cx, |vim, _: &Exchange, window, cx| {
887 if vim.mode.is_visual() {
888 vim.exchange_visual(window, cx)
889 } else {
890 vim.push_operator(Operator::Exchange, window, cx)
891 }
892 });
893
894 Vim::action(editor, cx, |vim, _: &ClearExchange, window, cx| {
895 vim.clear_exchange(window, cx)
896 });
897
898 Vim::action(editor, cx, |vim, _: &PushToggleComments, window, cx| {
899 vim.push_operator(Operator::ToggleComments, window, cx)
900 });
901
902 Vim::action(editor, cx, |vim, _: &ClearOperators, window, cx| {
903 vim.clear_operator(window, cx)
904 });
905 Vim::action(editor, cx, |vim, n: &Number, window, cx| {
906 vim.push_count_digit(n.0, window, cx);
907 });
908 Vim::action(editor, cx, |vim, _: &Tab, window, cx| {
909 vim.input_ignored(" ".into(), window, cx)
910 });
911 Vim::action(
912 editor,
913 cx,
914 |vim, action: &editor::actions::AcceptEditPrediction, window, cx| {
915 vim.update_editor(cx, |_, editor, cx| {
916 editor.accept_edit_prediction(action, window, cx);
917 });
918 // In non-insertion modes, predictions will be hidden and instead a jump will be
919 // displayed (and performed by `accept_edit_prediction`). This switches to
920 // insert mode so that the prediction is displayed after the jump.
921 match vim.mode {
922 Mode::Replace => {}
923 _ => vim.switch_mode(Mode::Insert, true, window, cx),
924 };
925 },
926 );
927 Vim::action(editor, cx, |vim, _: &Enter, window, cx| {
928 vim.input_ignored("\n".into(), window, cx)
929 });
930 Vim::action(editor, cx, |vim, _: &PushHelixMatch, window, cx| {
931 vim.push_operator(Operator::HelixMatch, window, cx)
932 });
933 Vim::action(editor, cx, |vim, action: &PushHelixNext, window, cx| {
934 vim.push_operator(
935 Operator::HelixNext {
936 around: action.around,
937 },
938 window,
939 cx,
940 );
941 });
942 Vim::action(editor, cx, |vim, action: &PushHelixPrevious, window, cx| {
943 vim.push_operator(
944 Operator::HelixPrevious {
945 around: action.around,
946 },
947 window,
948 cx,
949 );
950 });
951
952 Vim::action(
953 editor,
954 cx,
955 |vim, _: &editor::actions::Paste, window, cx| match vim.mode {
956 Mode::Replace => vim.paste_replace(window, cx),
957 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
958 vim.selected_register.replace('+');
959 vim.paste(&VimPaste::default(), window, cx);
960 }
961 _ => {
962 vim.update_editor(cx, |_, editor, cx| editor.paste(&Paste, window, cx));
963 }
964 },
965 );
966
967 normal::register(editor, cx);
968 insert::register(editor, cx);
969 helix::register(editor, cx);
970 motion::register(editor, cx);
971 command::register(editor, cx);
972 replace::register(editor, cx);
973 indent::register(editor, cx);
974 rewrap::register(editor, cx);
975 object::register(editor, cx);
976 visual::register(editor, cx);
977 change_list::register(editor, cx);
978 digraph::register(editor, cx);
979
980 if editor.is_focused(window) {
981 cx.defer_in(window, |vim, window, cx| {
982 vim.focused(false, window, cx);
983 })
984 }
985 })
986 }
987
988 fn deactivate(editor: &mut Editor, cx: &mut Context<Editor>) {
989 editor.set_cursor_shape(
990 EditorSettings::get_global(cx)
991 .cursor_shape
992 .unwrap_or_default(),
993 cx,
994 );
995 editor.set_clip_at_line_ends(false, cx);
996 editor.set_collapse_matches(false);
997 editor.set_input_enabled(true);
998 editor.set_expects_character_input(true);
999 editor.set_autoindent(true);
1000 editor.selections.set_line_mode(false);
1001 editor.unregister_addon::<VimAddon>();
1002 editor.set_relative_line_number(None, cx);
1003 if let Some(vim) = Vim::globals(cx).focused_vim()
1004 && vim.entity_id() == cx.entity().entity_id()
1005 {
1006 Vim::globals(cx).focused_vim = None;
1007 }
1008 }
1009
1010 /// Register an action on the editor.
1011 pub fn action<A: Action>(
1012 editor: &mut Editor,
1013 cx: &mut Context<Vim>,
1014 f: impl Fn(&mut Vim, &A, &mut Window, &mut Context<Vim>) + 'static,
1015 ) {
1016 let subscription = editor.register_action(cx.listener(move |vim, action, window, cx| {
1017 if !Vim::globals(cx).dot_replaying {
1018 if vim.status_label.take().is_some() {
1019 cx.notify();
1020 }
1021 }
1022 f(vim, action, window, cx);
1023 }));
1024 cx.on_release(|_, _| drop(subscription)).detach();
1025 }
1026
1027 pub fn editor(&self) -> Option<Entity<Editor>> {
1028 self.editor.upgrade()
1029 }
1030
1031 pub fn workspace(&self, window: &Window, cx: &App) -> Option<Entity<Workspace>> {
1032 Workspace::for_window(window, cx)
1033 }
1034
1035 pub fn pane(&self, window: &Window, cx: &Context<Self>) -> Option<Entity<Pane>> {
1036 self.workspace(window, cx)
1037 .map(|workspace| workspace.read(cx).focused_pane(window, cx))
1038 }
1039
1040 pub fn enabled(cx: &mut App) -> bool {
1041 VimModeSetting::get_global(cx).0 || HelixModeSetting::get_global(cx).0
1042 }
1043
1044 /// Called whenever an keystroke is typed so vim can observe all actions
1045 /// and keystrokes accordingly.
1046 fn observe_keystrokes(
1047 &mut self,
1048 keystroke_event: &KeystrokeEvent,
1049 window: &mut Window,
1050 cx: &mut Context<Self>,
1051 ) {
1052 if self.exit_temporary_mode {
1053 self.exit_temporary_mode = false;
1054 // Don't switch to insert mode if the action is temporary_normal.
1055 if let Some(action) = keystroke_event.action.as_ref()
1056 && action.as_any().downcast_ref::<TemporaryNormal>().is_some()
1057 {
1058 return;
1059 }
1060 self.switch_mode(Mode::Insert, false, window, cx)
1061 }
1062 if let Some(action) = keystroke_event.action.as_ref() {
1063 // Keystroke is handled by the vim system, so continue forward
1064 if action.name().starts_with("vim::") {
1065 self.update_editor(cx, |_, editor, cx| {
1066 editor.hide_mouse_cursor(HideMouseCursorOrigin::MovementAction, cx)
1067 });
1068
1069 return;
1070 }
1071 } else if window.has_pending_keystrokes() || keystroke_event.keystroke.is_ime_in_progress()
1072 {
1073 return;
1074 }
1075
1076 if let Some(operator) = self.active_operator() {
1077 match operator {
1078 Operator::Literal { prefix } => {
1079 self.handle_literal_keystroke(
1080 keystroke_event,
1081 prefix.unwrap_or_default(),
1082 window,
1083 cx,
1084 );
1085 }
1086 _ if !operator.is_waiting(self.mode) => {
1087 self.clear_operator(window, cx);
1088 self.stop_recording_immediately(Box::new(ClearOperators), cx)
1089 }
1090 _ => {}
1091 }
1092 }
1093 }
1094
1095 fn handle_editor_event(
1096 &mut self,
1097 event: &EditorEvent,
1098 window: &mut Window,
1099 cx: &mut Context<Self>,
1100 ) {
1101 match event {
1102 EditorEvent::Focused => self.focused(true, window, cx),
1103 EditorEvent::Blurred => self.blurred(window, cx),
1104 EditorEvent::SelectionsChanged { local: true } => {
1105 self.local_selections_changed(window, cx);
1106 }
1107 EditorEvent::InputIgnored { text } => {
1108 self.input_ignored(text.clone(), window, cx);
1109 Vim::globals(cx).observe_insertion(text, None)
1110 }
1111 EditorEvent::InputHandled {
1112 text,
1113 utf16_range_to_replace: range_to_replace,
1114 } => Vim::globals(cx).observe_insertion(text, range_to_replace.clone()),
1115 EditorEvent::TransactionBegun { transaction_id } => {
1116 self.transaction_begun(*transaction_id, window, cx)
1117 }
1118 EditorEvent::TransactionUndone { transaction_id } => {
1119 self.transaction_undone(transaction_id, window, cx)
1120 }
1121 EditorEvent::Edited { .. } => self.push_to_change_list(window, cx),
1122 EditorEvent::FocusedIn => self.sync_vim_settings(window, cx),
1123 EditorEvent::CursorShapeChanged => self.cursor_shape_changed(window, cx),
1124 EditorEvent::PushedToNavHistory {
1125 anchor,
1126 is_deactivate,
1127 } => {
1128 self.update_editor(cx, |vim, editor, cx| {
1129 let mark = if *is_deactivate {
1130 "\"".to_string()
1131 } else {
1132 "'".to_string()
1133 };
1134 vim.set_mark(mark, vec![*anchor], editor.buffer(), window, cx);
1135 });
1136 }
1137 _ => {}
1138 }
1139 }
1140
1141 fn push_operator(&mut self, operator: Operator, window: &mut Window, cx: &mut Context<Self>) {
1142 if operator.starts_dot_recording() {
1143 self.start_recording(cx);
1144 }
1145 // Since these operations can only be entered with pre-operators,
1146 // we need to clear the previous operators when pushing,
1147 // so that the current stack is the most correct
1148 if matches!(
1149 operator,
1150 Operator::AddSurrounds { .. }
1151 | Operator::ChangeSurrounds { .. }
1152 | Operator::DeleteSurrounds
1153 | Operator::Exchange
1154 ) {
1155 self.operator_stack.clear();
1156 };
1157 self.operator_stack.push(operator);
1158 self.sync_vim_settings(window, cx);
1159 }
1160
1161 pub fn switch_mode(
1162 &mut self,
1163 mode: Mode,
1164 leave_selections: bool,
1165 window: &mut Window,
1166 cx: &mut Context<Self>,
1167 ) {
1168 if self.temp_mode && mode == Mode::Normal {
1169 self.temp_mode = false;
1170 self.switch_mode(Mode::Normal, leave_selections, window, cx);
1171 self.switch_mode(Mode::Insert, false, window, cx);
1172 return;
1173 } else if self.temp_mode
1174 && !matches!(mode, Mode::Visual | Mode::VisualLine | Mode::VisualBlock)
1175 {
1176 self.temp_mode = false;
1177 }
1178
1179 let last_mode = self.mode;
1180 let prior_mode = self.last_mode;
1181 let prior_tx = self.current_tx;
1182 self.last_mode = last_mode;
1183 self.mode = mode;
1184 self.operator_stack.clear();
1185 self.selected_register.take();
1186 self.cancel_running_command(window, cx);
1187 if mode == Mode::Normal || mode != last_mode {
1188 self.current_tx.take();
1189 self.current_anchor.take();
1190 self.update_editor(cx, |_, editor, _| {
1191 editor.clear_selection_drag_state();
1192 });
1193 }
1194 Vim::take_forced_motion(cx);
1195 if mode != Mode::Insert && mode != Mode::Replace {
1196 Vim::take_count(cx);
1197 }
1198
1199 // Sync editor settings like clip mode
1200 self.sync_vim_settings(window, cx);
1201
1202 if VimSettings::get_global(cx).toggle_relative_line_numbers
1203 && self.mode != self.last_mode
1204 && (self.mode == Mode::Insert || self.last_mode == Mode::Insert)
1205 {
1206 self.update_editor(cx, |vim, editor, cx| {
1207 let is_relative = vim.mode != Mode::Insert;
1208 editor.set_relative_line_number(Some(is_relative), cx)
1209 });
1210 }
1211 if HelixModeSetting::get_global(cx).0 {
1212 if self.mode == Mode::Normal {
1213 self.mode = Mode::HelixNormal
1214 } else if self.mode == Mode::Visual {
1215 self.mode = Mode::HelixSelect
1216 }
1217 }
1218
1219 if leave_selections {
1220 return;
1221 }
1222
1223 if !mode.is_visual() && last_mode.is_visual() && !last_mode.is_helix() {
1224 self.create_visual_marks(last_mode, window, cx);
1225 }
1226
1227 // Adjust selections
1228 self.update_editor(cx, |vim, editor, cx| {
1229 if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
1230 {
1231 vim.visual_block_motion(true, editor, window, cx, &mut |_, point, goal| {
1232 Some((point, goal))
1233 })
1234 }
1235 if (last_mode == Mode::Insert || last_mode == Mode::Replace)
1236 && let Some(prior_tx) = prior_tx
1237 {
1238 editor.group_until_transaction(prior_tx, cx)
1239 }
1240
1241 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1242 // we cheat with visual block mode and use multiple cursors.
1243 // the cost of this cheat is we need to convert back to a single
1244 // cursor whenever vim would.
1245 if last_mode == Mode::VisualBlock
1246 && (mode != Mode::VisualBlock && mode != Mode::Insert)
1247 {
1248 let tail = s.oldest_anchor().tail();
1249 let head = s.newest_anchor().head();
1250 s.select_anchor_ranges(vec![tail..head]);
1251 } else if last_mode == Mode::Insert
1252 && prior_mode == Mode::VisualBlock
1253 && mode != Mode::VisualBlock
1254 {
1255 let pos = s.first_anchor().head();
1256 s.select_anchor_ranges(vec![pos..pos])
1257 }
1258
1259 let mut should_extend_pending = false;
1260 if !last_mode.is_visual()
1261 && mode.is_visual()
1262 && let Some(pending) = s.pending_anchor()
1263 {
1264 let snapshot = s.display_snapshot();
1265 let is_empty = pending
1266 .start
1267 .cmp(&pending.end, &snapshot.buffer_snapshot())
1268 .is_eq();
1269 should_extend_pending = pending.reversed
1270 && !is_empty
1271 && vim.extended_pending_selection_id != Some(pending.id);
1272 };
1273
1274 if should_extend_pending {
1275 let snapshot = s.display_snapshot();
1276 s.change_with(&snapshot, |map| {
1277 if let Some(pending) = map.pending_anchor_mut() {
1278 let end = pending.end.to_point(&snapshot.buffer_snapshot());
1279 let end = end.to_display_point(&snapshot);
1280 let new_end = movement::right(&snapshot, end);
1281 pending.end = snapshot
1282 .buffer_snapshot()
1283 .anchor_before(new_end.to_point(&snapshot));
1284 }
1285 });
1286 vim.extended_pending_selection_id = s.pending_anchor().map(|p| p.id)
1287 }
1288
1289 s.move_with(&mut |map, selection| {
1290 if last_mode.is_visual() && !last_mode.is_helix() && !mode.is_visual() {
1291 let mut point = selection.head();
1292 if !selection.reversed && !selection.is_empty() {
1293 point = movement::left(map, selection.head());
1294 } else if selection.is_empty() {
1295 point = map.clip_point(point, Bias::Left);
1296 }
1297 selection.collapse_to(point, selection.goal)
1298 } else if !last_mode.is_visual() && mode.is_visual() {
1299 if selection.is_empty() {
1300 selection.end = movement::right(map, selection.start);
1301 }
1302 }
1303 });
1304 })
1305 });
1306 }
1307
1308 pub fn take_count(cx: &mut App) -> Option<usize> {
1309 let global_state = cx.global_mut::<VimGlobals>();
1310 if global_state.dot_replaying {
1311 return global_state.recorded_count;
1312 }
1313
1314 let count = if global_state.post_count.is_none() && global_state.pre_count.is_none() {
1315 return None;
1316 } else {
1317 Some(
1318 global_state.post_count.take().unwrap_or(1)
1319 * global_state.pre_count.take().unwrap_or(1),
1320 )
1321 };
1322
1323 if global_state.dot_recording {
1324 global_state.recording_count = count;
1325 }
1326 count
1327 }
1328
1329 pub fn take_forced_motion(cx: &mut App) -> bool {
1330 let global_state = cx.global_mut::<VimGlobals>();
1331 let forced_motion = global_state.forced_motion;
1332 global_state.forced_motion = false;
1333 forced_motion
1334 }
1335
1336 pub fn cursor_shape(&self, cx: &App) -> CursorShape {
1337 let cursor_shape = VimSettings::get_global(cx).cursor_shape;
1338 match self.mode {
1339 Mode::Normal => {
1340 if let Some(operator) = self.operator_stack.last() {
1341 match operator {
1342 // Navigation operators -> Block cursor
1343 Operator::FindForward { .. }
1344 | Operator::FindBackward { .. }
1345 | Operator::Mark
1346 | Operator::Jump { .. }
1347 | Operator::Register
1348 | Operator::RecordRegister
1349 | Operator::ReplayRegister => CursorShape::Block,
1350
1351 // All other operators -> Underline cursor
1352 _ => CursorShape::Underline,
1353 }
1354 } else {
1355 cursor_shape.normal
1356 }
1357 }
1358 Mode::HelixNormal => cursor_shape.normal,
1359 Mode::Replace => cursor_shape.replace,
1360 Mode::Visual | Mode::VisualLine | Mode::VisualBlock | Mode::HelixSelect => {
1361 cursor_shape.visual
1362 }
1363 Mode::Insert => match cursor_shape.insert {
1364 InsertModeCursorShape::Explicit(shape) => shape,
1365 InsertModeCursorShape::Inherit => {
1366 let editor_settings = EditorSettings::get_global(cx);
1367 editor_settings.cursor_shape.unwrap_or_default()
1368 }
1369 },
1370 }
1371 }
1372
1373 fn expects_character_input(&self) -> bool {
1374 if let Some(operator) = self.operator_stack.last() {
1375 if operator.is_waiting(self.mode) {
1376 return true;
1377 }
1378 }
1379 self.editor_input_enabled()
1380 }
1381
1382 pub fn editor_input_enabled(&self) -> bool {
1383 match self.mode {
1384 Mode::Insert => {
1385 if let Some(operator) = self.operator_stack.last() {
1386 !operator.is_waiting(self.mode)
1387 } else {
1388 true
1389 }
1390 }
1391 Mode::Normal
1392 | Mode::HelixNormal
1393 | Mode::Replace
1394 | Mode::Visual
1395 | Mode::VisualLine
1396 | Mode::VisualBlock
1397 | Mode::HelixSelect => false,
1398 }
1399 }
1400
1401 pub fn should_autoindent(&self) -> bool {
1402 !(self.mode == Mode::Insert && self.last_mode == Mode::VisualBlock)
1403 }
1404
1405 pub fn clip_at_line_ends(&self) -> bool {
1406 match self.mode {
1407 Mode::Insert
1408 | Mode::Visual
1409 | Mode::VisualLine
1410 | Mode::VisualBlock
1411 | Mode::Replace
1412 | Mode::HelixNormal
1413 | Mode::HelixSelect => false,
1414 Mode::Normal => true,
1415 }
1416 }
1417
1418 pub fn extend_key_context(&self, context: &mut KeyContext, cx: &App) {
1419 let mut mode = match self.mode {
1420 Mode::Normal => "normal",
1421 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => "visual",
1422 Mode::Insert => "insert",
1423 Mode::Replace => "replace",
1424 Mode::HelixNormal => "helix_normal",
1425 Mode::HelixSelect => "helix_select",
1426 }
1427 .to_string();
1428
1429 let mut operator_id = "none";
1430
1431 let active_operator = self.active_operator();
1432 if active_operator.is_none() && cx.global::<VimGlobals>().pre_count.is_some()
1433 || active_operator.is_some() && cx.global::<VimGlobals>().post_count.is_some()
1434 {
1435 context.add("VimCount");
1436 }
1437
1438 if let Some(active_operator) = active_operator {
1439 if active_operator.is_waiting(self.mode) {
1440 if matches!(active_operator, Operator::Literal { .. }) {
1441 mode = "literal".to_string();
1442 } else {
1443 mode = "waiting".to_string();
1444 }
1445 } else {
1446 operator_id = active_operator.id();
1447 mode = "operator".to_string();
1448 }
1449 }
1450
1451 if mode == "normal"
1452 || mode == "visual"
1453 || mode == "operator"
1454 || mode == "helix_normal"
1455 || mode == "helix_select"
1456 {
1457 context.add("VimControl");
1458 }
1459 context.set("vim_mode", mode);
1460 context.set("vim_operator", operator_id);
1461 }
1462
1463 fn focused(&mut self, preserve_selection: bool, window: &mut Window, cx: &mut Context<Self>) {
1464 // If editor gains focus while search bar is still open (not dismissed),
1465 // the user has explicitly navigated away - clear prior_selections so we
1466 // don't restore to the old position if they later dismiss the search.
1467 if !self.search.prior_selections.is_empty() {
1468 if let Some(pane) = self.pane(window, cx) {
1469 let search_still_open = pane
1470 .read(cx)
1471 .toolbar()
1472 .read(cx)
1473 .item_of_type::<BufferSearchBar>()
1474 .is_some_and(|bar| !bar.read(cx).is_dismissed());
1475 if search_still_open {
1476 self.search.prior_selections.clear();
1477 }
1478 }
1479 }
1480
1481 let Some(editor) = self.editor() else {
1482 return;
1483 };
1484 let newest_selection_empty = editor.update(cx, |editor, cx| {
1485 editor
1486 .selections
1487 .newest::<MultiBufferOffset>(&editor.display_snapshot(cx))
1488 .is_empty()
1489 });
1490 let editor = editor.read(cx);
1491 let editor_mode = editor.mode();
1492
1493 if editor_mode.is_full()
1494 && !newest_selection_empty
1495 && self.mode == Mode::Normal
1496 // When following someone, don't switch vim mode.
1497 && editor.leader_id().is_none()
1498 {
1499 if preserve_selection {
1500 self.switch_mode(Mode::Visual, true, window, cx);
1501 } else {
1502 self.update_editor(cx, |_, editor, cx| {
1503 editor.set_clip_at_line_ends(false, cx);
1504 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1505 s.move_with(&mut |_, selection| {
1506 selection.collapse_to(selection.start, selection.goal)
1507 })
1508 });
1509 });
1510 }
1511 }
1512
1513 cx.emit(VimEvent::Focused);
1514 self.sync_vim_settings(window, cx);
1515
1516 if VimSettings::get_global(cx).toggle_relative_line_numbers {
1517 if let Some(old_vim) = Vim::globals(cx).focused_vim() {
1518 if old_vim.entity_id() != cx.entity().entity_id() {
1519 old_vim.update(cx, |vim, cx| {
1520 vim.update_editor(cx, |_, editor, cx| {
1521 editor.set_relative_line_number(None, cx)
1522 });
1523 });
1524
1525 self.update_editor(cx, |vim, editor, cx| {
1526 let is_relative = vim.mode != Mode::Insert;
1527 editor.set_relative_line_number(Some(is_relative), cx)
1528 });
1529 }
1530 } else {
1531 self.update_editor(cx, |vim, editor, cx| {
1532 let is_relative = vim.mode != Mode::Insert;
1533 editor.set_relative_line_number(Some(is_relative), cx)
1534 });
1535 }
1536 }
1537 Vim::globals(cx).focused_vim = Some(cx.entity().downgrade());
1538 }
1539
1540 fn blurred(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1541 self.stop_recording_immediately(NormalBefore.boxed_clone(), cx);
1542 self.store_visual_marks(window, cx);
1543 self.clear_operator(window, cx);
1544 self.update_editor(cx, |vim, editor, cx| {
1545 if vim.cursor_shape(cx) == CursorShape::Block {
1546 editor.set_cursor_shape(CursorShape::Hollow, cx);
1547 }
1548 });
1549 }
1550
1551 fn cursor_shape_changed(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1552 self.update_editor(cx, |vim, editor, cx| {
1553 editor.set_cursor_shape(vim.cursor_shape(cx), cx);
1554 });
1555 }
1556
1557 fn update_editor<S>(
1558 &mut self,
1559 cx: &mut Context<Self>,
1560 update: impl FnOnce(&mut Self, &mut Editor, &mut Context<Editor>) -> S,
1561 ) -> Option<S> {
1562 let editor = self.editor.upgrade()?;
1563 Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
1564 }
1565
1566 fn editor_selections(&mut self, _: &mut Window, cx: &mut Context<Self>) -> Vec<Range<Anchor>> {
1567 self.update_editor(cx, |_, editor, _| {
1568 editor
1569 .selections
1570 .disjoint_anchors_arc()
1571 .iter()
1572 .map(|selection| selection.tail()..selection.head())
1573 .collect()
1574 })
1575 .unwrap_or_default()
1576 }
1577
1578 fn editor_cursor_word(
1579 &mut self,
1580 window: &mut Window,
1581 cx: &mut Context<Self>,
1582 ) -> Option<String> {
1583 self.update_editor(cx, |_, editor, cx| {
1584 let snapshot = &editor.snapshot(window, cx);
1585 let selection = editor
1586 .selections
1587 .newest::<MultiBufferOffset>(&snapshot.display_snapshot);
1588
1589 let snapshot = snapshot.buffer_snapshot();
1590 let (range, kind) =
1591 snapshot.surrounding_word(selection.start, Some(CharScopeContext::Completion));
1592 if kind == Some(CharKind::Word) {
1593 let text: String = snapshot.text_for_range(range).collect();
1594 if !text.trim().is_empty() {
1595 return Some(text);
1596 }
1597 }
1598
1599 None
1600 })
1601 .unwrap_or_default()
1602 }
1603
1604 /// When doing an action that modifies the buffer, we start recording so that `.`
1605 /// will replay the action.
1606 pub fn start_recording(&mut self, cx: &mut Context<Self>) {
1607 Vim::update_globals(cx, |globals, cx| {
1608 if !globals.dot_replaying {
1609 globals.dot_recording = true;
1610 globals.recording_actions = Default::default();
1611 globals.recording_count = None;
1612 globals.recording_register_for_dot = self.selected_register;
1613
1614 let selections = self.editor().map(|editor| {
1615 editor.update(cx, |editor, cx| {
1616 let snapshot = editor.display_snapshot(cx);
1617
1618 (
1619 editor.selections.oldest::<Point>(&snapshot),
1620 editor.selections.newest::<Point>(&snapshot),
1621 )
1622 })
1623 });
1624
1625 if let Some((oldest, newest)) = selections {
1626 globals.recorded_selection = match self.mode {
1627 Mode::Visual if newest.end.row == newest.start.row => {
1628 RecordedSelection::SingleLine {
1629 cols: newest.end.column - newest.start.column,
1630 }
1631 }
1632 Mode::Visual => RecordedSelection::Visual {
1633 rows: newest.end.row - newest.start.row,
1634 cols: newest.end.column,
1635 },
1636 Mode::VisualLine => RecordedSelection::VisualLine {
1637 rows: newest.end.row - newest.start.row,
1638 },
1639 Mode::VisualBlock => RecordedSelection::VisualBlock {
1640 rows: newest.end.row.abs_diff(oldest.start.row),
1641 cols: newest.end.column.abs_diff(oldest.start.column),
1642 },
1643 _ => RecordedSelection::None,
1644 }
1645 } else {
1646 globals.recorded_selection = RecordedSelection::None;
1647 }
1648 }
1649 })
1650 }
1651
1652 pub fn stop_replaying(&mut self, cx: &mut Context<Self>) {
1653 let globals = Vim::globals(cx);
1654 globals.dot_replaying = false;
1655 if let Some(replayer) = globals.replayer.take() {
1656 replayer.stop();
1657 }
1658 }
1659
1660 /// When finishing an action that modifies the buffer, stop recording.
1661 /// as you usually call this within a keystroke handler we also ensure that
1662 /// the current action is recorded.
1663 pub fn stop_recording(&mut self, cx: &mut Context<Self>) {
1664 let globals = Vim::globals(cx);
1665 if globals.dot_recording {
1666 globals.stop_recording_after_next_action = true;
1667 }
1668 self.exit_temporary_mode = self.temp_mode;
1669 }
1670
1671 /// Stops recording actions immediately rather than waiting until after the
1672 /// next action to stop recording.
1673 ///
1674 /// This doesn't include the current action.
1675 pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>, cx: &mut Context<Self>) {
1676 let globals = Vim::globals(cx);
1677 if globals.dot_recording {
1678 globals
1679 .recording_actions
1680 .push(ReplayableAction::Action(action.boxed_clone()));
1681 globals.recorded_actions = mem::take(&mut globals.recording_actions);
1682 globals.recorded_count = globals.recording_count.take();
1683 globals.dot_recording = false;
1684 globals.stop_recording_after_next_action = false;
1685 }
1686 self.exit_temporary_mode = self.temp_mode;
1687 }
1688
1689 /// Explicitly record one action (equivalents to start_recording and stop_recording)
1690 pub fn record_current_action(&mut self, cx: &mut Context<Self>) {
1691 self.start_recording(cx);
1692 self.stop_recording(cx);
1693 }
1694
1695 fn push_count_digit(&mut self, number: usize, window: &mut Window, cx: &mut Context<Self>) {
1696 if self.active_operator().is_some() {
1697 let post_count = Vim::globals(cx).post_count.unwrap_or(0);
1698
1699 Vim::globals(cx).post_count = Some(
1700 post_count
1701 .checked_mul(10)
1702 .and_then(|post_count| post_count.checked_add(number))
1703 .filter(|post_count| *post_count < isize::MAX as usize)
1704 .unwrap_or(post_count),
1705 )
1706 } else {
1707 let pre_count = Vim::globals(cx).pre_count.unwrap_or(0);
1708
1709 Vim::globals(cx).pre_count = Some(
1710 pre_count
1711 .checked_mul(10)
1712 .and_then(|pre_count| pre_count.checked_add(number))
1713 .filter(|pre_count| *pre_count < isize::MAX as usize)
1714 .unwrap_or(pre_count),
1715 )
1716 }
1717 // update the keymap so that 0 works
1718 self.sync_vim_settings(window, cx)
1719 }
1720
1721 fn select_register(&mut self, register: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
1722 if register.chars().count() == 1 {
1723 self.selected_register
1724 .replace(register.chars().next().unwrap());
1725 }
1726 self.operator_stack.clear();
1727 self.sync_vim_settings(window, cx);
1728 }
1729
1730 fn maybe_pop_operator(&mut self) -> Option<Operator> {
1731 self.operator_stack.pop()
1732 }
1733
1734 fn pop_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Operator {
1735 let popped_operator = self.operator_stack.pop()
1736 .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
1737 self.sync_vim_settings(window, cx);
1738 popped_operator
1739 }
1740
1741 fn clear_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1742 Vim::take_count(cx);
1743 Vim::take_forced_motion(cx);
1744 self.selected_register.take();
1745 self.operator_stack.clear();
1746 self.sync_vim_settings(window, cx);
1747 }
1748
1749 fn active_operator(&self) -> Option<Operator> {
1750 self.operator_stack.last().cloned()
1751 }
1752
1753 fn transaction_begun(
1754 &mut self,
1755 transaction_id: TransactionId,
1756 _window: &mut Window,
1757 _: &mut Context<Self>,
1758 ) {
1759 let mode = if (self.mode == Mode::Insert
1760 || self.mode == Mode::Replace
1761 || self.mode == Mode::Normal)
1762 && self.current_tx.is_none()
1763 {
1764 self.current_tx = Some(transaction_id);
1765 self.last_mode
1766 } else {
1767 self.mode
1768 };
1769 if mode == Mode::VisualLine || mode == Mode::VisualBlock {
1770 self.undo_modes.insert(transaction_id, mode);
1771 }
1772 }
1773
1774 fn transaction_undone(
1775 &mut self,
1776 transaction_id: &TransactionId,
1777 window: &mut Window,
1778 cx: &mut Context<Self>,
1779 ) {
1780 match self.mode {
1781 Mode::VisualLine | Mode::VisualBlock | Mode::Visual | Mode::HelixSelect => {
1782 self.update_editor(cx, |vim, editor, cx| {
1783 let original_mode = vim.undo_modes.get(transaction_id);
1784 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1785 match original_mode {
1786 Some(Mode::VisualLine) => {
1787 s.move_with(&mut |map, selection| {
1788 selection.collapse_to(
1789 map.prev_line_boundary(selection.start.to_point(map)).1,
1790 SelectionGoal::None,
1791 )
1792 });
1793 }
1794 Some(Mode::VisualBlock) => {
1795 let mut first = s.first_anchor();
1796 first.collapse_to(first.start, first.goal);
1797 s.select_anchors(vec![first]);
1798 }
1799 _ => {
1800 s.move_with(&mut |map, selection| {
1801 selection.collapse_to(
1802 map.clip_at_line_end(selection.start),
1803 selection.goal,
1804 );
1805 });
1806 }
1807 }
1808 });
1809 });
1810 self.switch_mode(Mode::Normal, true, window, cx)
1811 }
1812 Mode::Normal => {
1813 self.update_editor(cx, |_, editor, cx| {
1814 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1815 s.move_with(&mut |map, selection| {
1816 selection
1817 .collapse_to(map.clip_at_line_end(selection.end), selection.goal)
1818 })
1819 })
1820 });
1821 }
1822 Mode::Insert | Mode::Replace | Mode::HelixNormal => {}
1823 }
1824 }
1825
1826 fn local_selections_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1827 let Some(editor) = self.editor() else { return };
1828
1829 if editor.read(cx).leader_id().is_some() {
1830 return;
1831 }
1832
1833 let newest = editor.read(cx).selections.newest_anchor().clone();
1834 let is_multicursor = editor.read(cx).selections.count() > 1;
1835 if self.mode == Mode::Insert && self.current_tx.is_some() {
1836 if let Some(current_anchor) = &self.current_anchor {
1837 if current_anchor != &newest
1838 && let Some(tx_id) = self.current_tx.take()
1839 {
1840 self.update_editor(cx, |_, editor, cx| {
1841 editor.group_until_transaction(tx_id, cx)
1842 });
1843 }
1844 } else {
1845 self.current_anchor = Some(newest);
1846 }
1847 } else if self.mode == Mode::Normal && newest.start != newest.end {
1848 if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
1849 self.switch_mode(Mode::VisualBlock, false, window, cx);
1850 } else {
1851 self.switch_mode(Mode::Visual, false, window, cx)
1852 }
1853 } else if newest.start == newest.end
1854 && !is_multicursor
1855 && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&self.mode)
1856 {
1857 self.switch_mode(Mode::Normal, false, window, cx);
1858 }
1859 }
1860
1861 fn input_ignored(&mut self, text: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
1862 if text.is_empty() {
1863 return;
1864 }
1865
1866 match self.active_operator() {
1867 Some(Operator::FindForward { before, multiline }) => {
1868 let find = Motion::FindForward {
1869 before,
1870 char: text.chars().next().unwrap(),
1871 mode: if multiline {
1872 FindRange::MultiLine
1873 } else {
1874 FindRange::SingleLine
1875 },
1876 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1877 };
1878 Vim::globals(cx).last_find = Some(find.clone());
1879 self.motion(find, window, cx)
1880 }
1881 Some(Operator::FindBackward { after, multiline }) => {
1882 let find = Motion::FindBackward {
1883 after,
1884 char: text.chars().next().unwrap(),
1885 mode: if multiline {
1886 FindRange::MultiLine
1887 } else {
1888 FindRange::SingleLine
1889 },
1890 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1891 };
1892 Vim::globals(cx).last_find = Some(find.clone());
1893 self.motion(find, window, cx)
1894 }
1895 Some(Operator::Sneak { first_char }) => {
1896 if let Some(first_char) = first_char {
1897 if let Some(second_char) = text.chars().next() {
1898 let sneak = Motion::Sneak {
1899 first_char,
1900 second_char,
1901 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1902 };
1903 Vim::globals(cx).last_find = Some(sneak.clone());
1904 self.motion(sneak, window, cx)
1905 }
1906 } else {
1907 let first_char = text.chars().next();
1908 self.pop_operator(window, cx);
1909 self.push_operator(Operator::Sneak { first_char }, window, cx);
1910 }
1911 }
1912 Some(Operator::SneakBackward { first_char }) => {
1913 if let Some(first_char) = first_char {
1914 if let Some(second_char) = text.chars().next() {
1915 let sneak = Motion::SneakBackward {
1916 first_char,
1917 second_char,
1918 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1919 };
1920 Vim::globals(cx).last_find = Some(sneak.clone());
1921 self.motion(sneak, window, cx)
1922 }
1923 } else {
1924 let first_char = text.chars().next();
1925 self.pop_operator(window, cx);
1926 self.push_operator(Operator::SneakBackward { first_char }, window, cx);
1927 }
1928 }
1929 Some(Operator::Replace) => match self.mode {
1930 Mode::Normal => self.normal_replace(text, window, cx),
1931 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1932 self.visual_replace(text, window, cx)
1933 }
1934 Mode::HelixNormal => self.helix_replace(&text, window, cx),
1935 _ => self.clear_operator(window, cx),
1936 },
1937 Some(Operator::Digraph { first_char }) => {
1938 if let Some(first_char) = first_char {
1939 if let Some(second_char) = text.chars().next() {
1940 self.insert_digraph(first_char, second_char, window, cx);
1941 }
1942 } else {
1943 let first_char = text.chars().next();
1944 self.pop_operator(window, cx);
1945 self.push_operator(Operator::Digraph { first_char }, window, cx);
1946 }
1947 }
1948 Some(Operator::Literal { prefix }) => {
1949 self.handle_literal_input(prefix.unwrap_or_default(), &text, window, cx)
1950 }
1951 Some(Operator::AddSurrounds { target }) => match self.mode {
1952 Mode::Normal => {
1953 if let Some(target) = target {
1954 self.add_surrounds(text, target, window, cx);
1955 self.clear_operator(window, cx);
1956 }
1957 }
1958 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1959 self.add_surrounds(text, SurroundsType::Selection, window, cx);
1960 self.clear_operator(window, cx);
1961 }
1962 _ => self.clear_operator(window, cx),
1963 },
1964 Some(Operator::ChangeSurrounds { target, opening }) => match self.mode {
1965 Mode::Normal => {
1966 if let Some(target) = target {
1967 self.change_surrounds(text, target, opening, window, cx);
1968 self.clear_operator(window, cx);
1969 }
1970 }
1971 _ => self.clear_operator(window, cx),
1972 },
1973 Some(Operator::DeleteSurrounds) => match self.mode {
1974 Mode::Normal => {
1975 self.delete_surrounds(text, window, cx);
1976 self.clear_operator(window, cx);
1977 }
1978 _ => self.clear_operator(window, cx),
1979 },
1980 Some(Operator::HelixSurroundAdd) => match self.mode {
1981 Mode::HelixNormal | Mode::HelixSelect => {
1982 self.update_editor(cx, |_, editor, cx| {
1983 editor.change_selections(Default::default(), window, cx, |s| {
1984 s.move_with(&mut |map, selection| {
1985 if selection.is_empty() {
1986 selection.end = movement::right(map, selection.start);
1987 }
1988 });
1989 });
1990 });
1991 self.helix_surround_add(&text, window, cx);
1992 self.switch_mode(Mode::HelixNormal, false, window, cx);
1993 self.clear_operator(window, cx);
1994 }
1995 _ => self.clear_operator(window, cx),
1996 },
1997 Some(Operator::HelixSurroundReplace {
1998 replaced_char: Some(old),
1999 }) => match self.mode {
2000 Mode::HelixNormal | Mode::HelixSelect => {
2001 if let Some(new_char) = text.chars().next() {
2002 self.helix_surround_replace(old, new_char, window, cx);
2003 }
2004 self.clear_operator(window, cx);
2005 }
2006 _ => self.clear_operator(window, cx),
2007 },
2008 Some(Operator::HelixSurroundReplace {
2009 replaced_char: None,
2010 }) => match self.mode {
2011 Mode::HelixNormal | Mode::HelixSelect => {
2012 if let Some(ch) = text.chars().next() {
2013 self.pop_operator(window, cx);
2014 self.push_operator(
2015 Operator::HelixSurroundReplace {
2016 replaced_char: Some(ch),
2017 },
2018 window,
2019 cx,
2020 );
2021 }
2022 }
2023 _ => self.clear_operator(window, cx),
2024 },
2025 Some(Operator::HelixSurroundDelete) => match self.mode {
2026 Mode::HelixNormal | Mode::HelixSelect => {
2027 if let Some(ch) = text.chars().next() {
2028 self.helix_surround_delete(ch, window, cx);
2029 }
2030 self.clear_operator(window, cx);
2031 }
2032 _ => self.clear_operator(window, cx),
2033 },
2034 Some(Operator::Mark) => self.create_mark(text, window, cx),
2035 Some(Operator::RecordRegister) => {
2036 self.record_register(text.chars().next().unwrap(), window, cx)
2037 }
2038 Some(Operator::ReplayRegister) => {
2039 self.replay_register(text.chars().next().unwrap(), window, cx)
2040 }
2041 Some(Operator::Register) => match self.mode {
2042 Mode::Insert => {
2043 self.update_editor(cx, |_, editor, cx| {
2044 if let Some(register) = Vim::update_globals(cx, |globals, cx| {
2045 globals.read_register(text.chars().next(), Some(editor), cx)
2046 }) {
2047 editor.do_paste(
2048 ®ister.text.to_string(),
2049 register.clipboard_selections,
2050 false,
2051 window,
2052 cx,
2053 )
2054 }
2055 });
2056 self.clear_operator(window, cx);
2057 }
2058 _ => {
2059 self.select_register(text, window, cx);
2060 }
2061 },
2062 Some(Operator::Jump { line }) => self.jump(text, line, true, window, cx),
2063 _ => {
2064 if self.mode == Mode::Replace {
2065 self.multi_replace(text, window, cx)
2066 }
2067
2068 if self.mode == Mode::Normal {
2069 self.update_editor(cx, |_, editor, cx| {
2070 editor.accept_edit_prediction(
2071 &editor::actions::AcceptEditPrediction {},
2072 window,
2073 cx,
2074 );
2075 });
2076 }
2077 }
2078 }
2079 }
2080
2081 fn sync_vim_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2082 let state = self.state_for_editor_settings(cx);
2083 self.update_editor(cx, |_, editor, cx| {
2084 Vim::sync_vim_settings_to_editor(&state, editor, window, cx);
2085 });
2086 cx.notify()
2087 }
2088
2089 fn state_for_editor_settings(&self, cx: &App) -> VimEditorSettingsState {
2090 VimEditorSettingsState {
2091 cursor_shape: self.cursor_shape(cx),
2092 clip_at_line_ends: self.clip_at_line_ends(),
2093 collapse_matches: !HelixModeSetting::get_global(cx).0 && !self.search.cmd_f_search,
2094 input_enabled: self.editor_input_enabled(),
2095 expects_character_input: self.expects_character_input(),
2096 autoindent: self.should_autoindent(),
2097 cursor_offset_on_selection: self.mode.is_visual() || self.mode.is_helix(),
2098 line_mode: matches!(self.mode, Mode::VisualLine),
2099 hide_edit_predictions: !matches!(self.mode, Mode::Insert | Mode::Replace),
2100 }
2101 }
2102
2103 fn sync_vim_settings_to_editor(
2104 state: &VimEditorSettingsState,
2105 editor: &mut Editor,
2106 window: &mut Window,
2107 cx: &mut Context<Editor>,
2108 ) {
2109 editor.set_cursor_shape(state.cursor_shape, cx);
2110 editor.set_clip_at_line_ends(state.clip_at_line_ends, cx);
2111 editor.set_collapse_matches(state.collapse_matches);
2112 editor.set_input_enabled(state.input_enabled);
2113 editor.set_expects_character_input(state.expects_character_input);
2114 editor.set_autoindent(state.autoindent);
2115 editor.set_cursor_offset_on_selection(state.cursor_offset_on_selection);
2116 editor.selections.set_line_mode(state.line_mode);
2117 editor.set_edit_predictions_hidden_for_vim_mode(state.hide_edit_predictions, window, cx);
2118 }
2119
2120 fn set_status_label(&mut self, label: impl Into<SharedString>, cx: &mut Context<Editor>) {
2121 self.status_label = Some(label.into());
2122 cx.notify();
2123 }
2124}
2125
2126struct VimEditorSettingsState {
2127 cursor_shape: CursorShape,
2128 clip_at_line_ends: bool,
2129 collapse_matches: bool,
2130 input_enabled: bool,
2131 expects_character_input: bool,
2132 autoindent: bool,
2133 cursor_offset_on_selection: bool,
2134 line_mode: bool,
2135 hide_edit_predictions: bool,
2136}
2137
2138#[derive(Clone, RegisterSetting)]
2139struct VimSettings {
2140 pub default_mode: Mode,
2141 pub toggle_relative_line_numbers: bool,
2142 pub use_system_clipboard: settings::UseSystemClipboard,
2143 pub use_smartcase_find: bool,
2144 pub use_regex_search: bool,
2145 pub gdefault: bool,
2146 pub custom_digraphs: HashMap<String, Arc<str>>,
2147 pub highlight_on_yank_duration: u64,
2148 pub cursor_shape: CursorShapeSettings,
2149}
2150
2151/// Cursor shape configuration for insert mode.
2152#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2153pub enum InsertModeCursorShape {
2154 /// Inherit cursor shape from the editor's base cursor_shape setting.
2155 /// This allows users to set their preferred editor cursor and have
2156 /// it automatically apply to vim insert mode.
2157 Inherit,
2158 /// Use an explicit cursor shape for insert mode.
2159 Explicit(CursorShape),
2160}
2161
2162/// The settings for cursor shape.
2163#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2164pub struct CursorShapeSettings {
2165 /// Cursor shape for the normal mode.
2166 ///
2167 /// Default: block
2168 pub normal: CursorShape,
2169 /// Cursor shape for the replace mode.
2170 ///
2171 /// Default: underline
2172 pub replace: CursorShape,
2173 /// Cursor shape for the visual mode.
2174 ///
2175 /// Default: block
2176 pub visual: CursorShape,
2177 /// Cursor shape for the insert mode.
2178 ///
2179 /// Default: Inherit (follows editor.cursor_shape)
2180 pub insert: InsertModeCursorShape,
2181}
2182
2183impl From<settings::VimInsertModeCursorShape> for InsertModeCursorShape {
2184 fn from(shape: settings::VimInsertModeCursorShape) -> Self {
2185 match shape {
2186 settings::VimInsertModeCursorShape::Inherit => InsertModeCursorShape::Inherit,
2187 settings::VimInsertModeCursorShape::Bar => {
2188 InsertModeCursorShape::Explicit(CursorShape::Bar)
2189 }
2190 settings::VimInsertModeCursorShape::Block => {
2191 InsertModeCursorShape::Explicit(CursorShape::Block)
2192 }
2193 settings::VimInsertModeCursorShape::Underline => {
2194 InsertModeCursorShape::Explicit(CursorShape::Underline)
2195 }
2196 settings::VimInsertModeCursorShape::Hollow => {
2197 InsertModeCursorShape::Explicit(CursorShape::Hollow)
2198 }
2199 }
2200 }
2201}
2202
2203impl From<settings::CursorShapeSettings> for CursorShapeSettings {
2204 fn from(settings: settings::CursorShapeSettings) -> Self {
2205 Self {
2206 normal: settings.normal.unwrap().into(),
2207 replace: settings.replace.unwrap().into(),
2208 visual: settings.visual.unwrap().into(),
2209 insert: settings.insert.unwrap().into(),
2210 }
2211 }
2212}
2213
2214impl From<settings::ModeContent> for Mode {
2215 fn from(mode: ModeContent) -> Self {
2216 match mode {
2217 ModeContent::Normal => Self::Normal,
2218 ModeContent::Insert => Self::Insert,
2219 }
2220 }
2221}
2222
2223impl Settings for VimSettings {
2224 fn from_settings(content: &settings::SettingsContent) -> Self {
2225 let vim = content.vim.clone().unwrap();
2226 Self {
2227 default_mode: vim.default_mode.unwrap().into(),
2228 toggle_relative_line_numbers: vim.toggle_relative_line_numbers.unwrap(),
2229 use_system_clipboard: vim.use_system_clipboard.unwrap(),
2230 use_smartcase_find: vim.use_smartcase_find.unwrap(),
2231 use_regex_search: vim.use_regex_search.unwrap(),
2232 gdefault: vim.gdefault.unwrap(),
2233 custom_digraphs: vim.custom_digraphs.unwrap(),
2234 highlight_on_yank_duration: vim.highlight_on_yank_duration.unwrap(),
2235 cursor_shape: vim.cursor_shape.unwrap().into(),
2236 }
2237 }
2238}