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