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