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