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