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
1326 }
1327 }
1328 Mode::HelixNormal => cursor_shape.normal,
1329 Mode::Replace => cursor_shape.replace,
1330 Mode::Visual | Mode::VisualLine | Mode::VisualBlock | Mode::HelixSelect => {
1331 cursor_shape.visual
1332 }
1333 Mode::Insert => match cursor_shape.insert {
1334 InsertModeCursorShape::Explicit(shape) => shape,
1335 InsertModeCursorShape::Inherit => {
1336 let editor_settings = EditorSettings::get_global(cx);
1337 editor_settings.cursor_shape.unwrap_or_default()
1338 }
1339 },
1340 }
1341 }
1342
1343 pub fn editor_input_enabled(&self) -> bool {
1344 match self.mode {
1345 Mode::Insert => {
1346 if let Some(operator) = self.operator_stack.last() {
1347 !operator.is_waiting(self.mode)
1348 } else {
1349 true
1350 }
1351 }
1352 Mode::Normal
1353 | Mode::HelixNormal
1354 | Mode::Replace
1355 | Mode::Visual
1356 | Mode::VisualLine
1357 | Mode::VisualBlock
1358 | Mode::HelixSelect => false,
1359 }
1360 }
1361
1362 pub fn should_autoindent(&self) -> bool {
1363 !(self.mode == Mode::Insert && self.last_mode == Mode::VisualBlock)
1364 }
1365
1366 pub fn clip_at_line_ends(&self) -> bool {
1367 match self.mode {
1368 Mode::Insert
1369 | Mode::Visual
1370 | Mode::VisualLine
1371 | Mode::VisualBlock
1372 | Mode::Replace
1373 | Mode::HelixNormal
1374 | Mode::HelixSelect => false,
1375 Mode::Normal => true,
1376 }
1377 }
1378
1379 pub fn extend_key_context(&self, context: &mut KeyContext, cx: &App) {
1380 let mut mode = match self.mode {
1381 Mode::Normal => "normal",
1382 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => "visual",
1383 Mode::Insert => "insert",
1384 Mode::Replace => "replace",
1385 Mode::HelixNormal => "helix_normal",
1386 Mode::HelixSelect => "helix_select",
1387 }
1388 .to_string();
1389
1390 let mut operator_id = "none";
1391
1392 let active_operator = self.active_operator();
1393 if active_operator.is_none() && cx.global::<VimGlobals>().pre_count.is_some()
1394 || active_operator.is_some() && cx.global::<VimGlobals>().post_count.is_some()
1395 {
1396 context.add("VimCount");
1397 }
1398
1399 if let Some(active_operator) = active_operator {
1400 if active_operator.is_waiting(self.mode) {
1401 if matches!(active_operator, Operator::Literal { .. }) {
1402 mode = "literal".to_string();
1403 } else {
1404 mode = "waiting".to_string();
1405 }
1406 } else {
1407 operator_id = active_operator.id();
1408 mode = "operator".to_string();
1409 }
1410 }
1411
1412 if mode == "normal"
1413 || mode == "visual"
1414 || mode == "operator"
1415 || mode == "helix_normal"
1416 || mode == "helix_select"
1417 {
1418 context.add("VimControl");
1419 }
1420 context.set("vim_mode", mode);
1421 context.set("vim_operator", operator_id);
1422 }
1423
1424 fn focused(&mut self, preserve_selection: bool, window: &mut Window, cx: &mut Context<Self>) {
1425 let Some(editor) = self.editor() else {
1426 return;
1427 };
1428 let newest_selection_empty = editor.update(cx, |editor, cx| {
1429 editor
1430 .selections
1431 .newest::<MultiBufferOffset>(&editor.display_snapshot(cx))
1432 .is_empty()
1433 });
1434 let editor = editor.read(cx);
1435 let editor_mode = editor.mode();
1436
1437 if editor_mode.is_full()
1438 && !newest_selection_empty
1439 && self.mode == Mode::Normal
1440 // When following someone, don't switch vim mode.
1441 && editor.leader_id().is_none()
1442 {
1443 if preserve_selection {
1444 self.switch_mode(Mode::Visual, true, window, cx);
1445 } else {
1446 self.update_editor(cx, |_, editor, cx| {
1447 editor.set_clip_at_line_ends(false, cx);
1448 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1449 s.move_with(|_, selection| {
1450 selection.collapse_to(selection.start, selection.goal)
1451 })
1452 });
1453 });
1454 }
1455 }
1456
1457 cx.emit(VimEvent::Focused);
1458 self.sync_vim_settings(window, cx);
1459
1460 if VimSettings::get_global(cx).toggle_relative_line_numbers {
1461 if let Some(old_vim) = Vim::globals(cx).focused_vim() {
1462 if old_vim.entity_id() != cx.entity().entity_id() {
1463 old_vim.update(cx, |vim, cx| {
1464 vim.update_editor(cx, |_, editor, cx| {
1465 editor.set_relative_line_number(None, cx)
1466 });
1467 });
1468
1469 self.update_editor(cx, |vim, editor, cx| {
1470 let is_relative = vim.mode != Mode::Insert;
1471 editor.set_relative_line_number(Some(is_relative), cx)
1472 });
1473 }
1474 } else {
1475 self.update_editor(cx, |vim, editor, cx| {
1476 let is_relative = vim.mode != Mode::Insert;
1477 editor.set_relative_line_number(Some(is_relative), cx)
1478 });
1479 }
1480 }
1481 Vim::globals(cx).focused_vim = Some(cx.entity().downgrade());
1482 }
1483
1484 fn blurred(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1485 self.stop_recording_immediately(NormalBefore.boxed_clone(), cx);
1486 self.store_visual_marks(window, cx);
1487 self.clear_operator(window, cx);
1488 self.update_editor(cx, |vim, editor, cx| {
1489 if vim.cursor_shape(cx) == CursorShape::Block {
1490 editor.set_cursor_shape(CursorShape::Hollow, cx);
1491 }
1492 });
1493 }
1494
1495 fn cursor_shape_changed(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1496 self.update_editor(cx, |vim, editor, cx| {
1497 editor.set_cursor_shape(vim.cursor_shape(cx), cx);
1498 });
1499 }
1500
1501 fn update_editor<S>(
1502 &mut self,
1503 cx: &mut Context<Self>,
1504 update: impl FnOnce(&mut Self, &mut Editor, &mut Context<Editor>) -> S,
1505 ) -> Option<S> {
1506 let editor = self.editor.upgrade()?;
1507 Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
1508 }
1509
1510 fn editor_selections(&mut self, _: &mut Window, cx: &mut Context<Self>) -> Vec<Range<Anchor>> {
1511 self.update_editor(cx, |_, editor, _| {
1512 editor
1513 .selections
1514 .disjoint_anchors_arc()
1515 .iter()
1516 .map(|selection| selection.tail()..selection.head())
1517 .collect()
1518 })
1519 .unwrap_or_default()
1520 }
1521
1522 fn editor_cursor_word(
1523 &mut self,
1524 window: &mut Window,
1525 cx: &mut Context<Self>,
1526 ) -> Option<String> {
1527 self.update_editor(cx, |_, editor, cx| {
1528 let snapshot = &editor.snapshot(window, cx);
1529 let selection = editor
1530 .selections
1531 .newest::<MultiBufferOffset>(&snapshot.display_snapshot);
1532
1533 let snapshot = snapshot.buffer_snapshot();
1534 let (range, kind) =
1535 snapshot.surrounding_word(selection.start, Some(CharScopeContext::Completion));
1536 if kind == Some(CharKind::Word) {
1537 let text: String = snapshot.text_for_range(range).collect();
1538 if !text.trim().is_empty() {
1539 return Some(text);
1540 }
1541 }
1542
1543 None
1544 })
1545 .unwrap_or_default()
1546 }
1547
1548 /// When doing an action that modifies the buffer, we start recording so that `.`
1549 /// will replay the action.
1550 pub fn start_recording(&mut self, cx: &mut Context<Self>) {
1551 Vim::update_globals(cx, |globals, cx| {
1552 if !globals.dot_replaying {
1553 globals.dot_recording = true;
1554 globals.recording_actions = Default::default();
1555 globals.recording_count = None;
1556
1557 let selections = self.editor().map(|editor| {
1558 editor.update(cx, |editor, cx| {
1559 let snapshot = editor.display_snapshot(cx);
1560
1561 (
1562 editor.selections.oldest::<Point>(&snapshot),
1563 editor.selections.newest::<Point>(&snapshot),
1564 )
1565 })
1566 });
1567
1568 if let Some((oldest, newest)) = selections {
1569 globals.recorded_selection = match self.mode {
1570 Mode::Visual if newest.end.row == newest.start.row => {
1571 RecordedSelection::SingleLine {
1572 cols: newest.end.column - newest.start.column,
1573 }
1574 }
1575 Mode::Visual => RecordedSelection::Visual {
1576 rows: newest.end.row - newest.start.row,
1577 cols: newest.end.column,
1578 },
1579 Mode::VisualLine => RecordedSelection::VisualLine {
1580 rows: newest.end.row - newest.start.row,
1581 },
1582 Mode::VisualBlock => RecordedSelection::VisualBlock {
1583 rows: newest.end.row.abs_diff(oldest.start.row),
1584 cols: newest.end.column.abs_diff(oldest.start.column),
1585 },
1586 _ => RecordedSelection::None,
1587 }
1588 } else {
1589 globals.recorded_selection = RecordedSelection::None;
1590 }
1591 }
1592 })
1593 }
1594
1595 pub fn stop_replaying(&mut self, cx: &mut Context<Self>) {
1596 let globals = Vim::globals(cx);
1597 globals.dot_replaying = false;
1598 if let Some(replayer) = globals.replayer.take() {
1599 replayer.stop();
1600 }
1601 }
1602
1603 /// When finishing an action that modifies the buffer, stop recording.
1604 /// as you usually call this within a keystroke handler we also ensure that
1605 /// the current action is recorded.
1606 pub fn stop_recording(&mut self, cx: &mut Context<Self>) {
1607 let globals = Vim::globals(cx);
1608 if globals.dot_recording {
1609 globals.stop_recording_after_next_action = true;
1610 }
1611 self.exit_temporary_mode = self.temp_mode;
1612 }
1613
1614 /// Stops recording actions immediately rather than waiting until after the
1615 /// next action to stop recording.
1616 ///
1617 /// This doesn't include the current action.
1618 pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>, cx: &mut Context<Self>) {
1619 let globals = Vim::globals(cx);
1620 if globals.dot_recording {
1621 globals
1622 .recording_actions
1623 .push(ReplayableAction::Action(action.boxed_clone()));
1624 globals.recorded_actions = mem::take(&mut globals.recording_actions);
1625 globals.recorded_count = globals.recording_count.take();
1626 globals.dot_recording = false;
1627 globals.stop_recording_after_next_action = false;
1628 }
1629 self.exit_temporary_mode = self.temp_mode;
1630 }
1631
1632 /// Explicitly record one action (equivalents to start_recording and stop_recording)
1633 pub fn record_current_action(&mut self, cx: &mut Context<Self>) {
1634 self.start_recording(cx);
1635 self.stop_recording(cx);
1636 }
1637
1638 fn push_count_digit(&mut self, number: usize, window: &mut Window, cx: &mut Context<Self>) {
1639 if self.active_operator().is_some() {
1640 let post_count = Vim::globals(cx).post_count.unwrap_or(0);
1641
1642 Vim::globals(cx).post_count = Some(
1643 post_count
1644 .checked_mul(10)
1645 .and_then(|post_count| post_count.checked_add(number))
1646 .filter(|post_count| *post_count < isize::MAX as usize)
1647 .unwrap_or(post_count),
1648 )
1649 } else {
1650 let pre_count = Vim::globals(cx).pre_count.unwrap_or(0);
1651
1652 Vim::globals(cx).pre_count = Some(
1653 pre_count
1654 .checked_mul(10)
1655 .and_then(|pre_count| pre_count.checked_add(number))
1656 .filter(|pre_count| *pre_count < isize::MAX as usize)
1657 .unwrap_or(pre_count),
1658 )
1659 }
1660 // update the keymap so that 0 works
1661 self.sync_vim_settings(window, cx)
1662 }
1663
1664 fn select_register(&mut self, register: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
1665 if register.chars().count() == 1 {
1666 self.selected_register
1667 .replace(register.chars().next().unwrap());
1668 }
1669 self.operator_stack.clear();
1670 self.sync_vim_settings(window, cx);
1671 }
1672
1673 fn maybe_pop_operator(&mut self) -> Option<Operator> {
1674 self.operator_stack.pop()
1675 }
1676
1677 fn pop_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Operator {
1678 let popped_operator = self.operator_stack.pop()
1679 .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
1680 self.sync_vim_settings(window, cx);
1681 popped_operator
1682 }
1683
1684 fn clear_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1685 Vim::take_count(cx);
1686 Vim::take_forced_motion(cx);
1687 self.selected_register.take();
1688 self.operator_stack.clear();
1689 self.sync_vim_settings(window, cx);
1690 }
1691
1692 fn active_operator(&self) -> Option<Operator> {
1693 self.operator_stack.last().cloned()
1694 }
1695
1696 fn transaction_begun(
1697 &mut self,
1698 transaction_id: TransactionId,
1699 _window: &mut Window,
1700 _: &mut Context<Self>,
1701 ) {
1702 let mode = if (self.mode == Mode::Insert
1703 || self.mode == Mode::Replace
1704 || self.mode == Mode::Normal)
1705 && self.current_tx.is_none()
1706 {
1707 self.current_tx = Some(transaction_id);
1708 self.last_mode
1709 } else {
1710 self.mode
1711 };
1712 if mode == Mode::VisualLine || mode == Mode::VisualBlock {
1713 self.undo_modes.insert(transaction_id, mode);
1714 }
1715 }
1716
1717 fn transaction_undone(
1718 &mut self,
1719 transaction_id: &TransactionId,
1720 window: &mut Window,
1721 cx: &mut Context<Self>,
1722 ) {
1723 match self.mode {
1724 Mode::VisualLine | Mode::VisualBlock | Mode::Visual | Mode::HelixSelect => {
1725 self.update_editor(cx, |vim, editor, cx| {
1726 let original_mode = vim.undo_modes.get(transaction_id);
1727 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1728 match original_mode {
1729 Some(Mode::VisualLine) => {
1730 s.move_with(|map, selection| {
1731 selection.collapse_to(
1732 map.prev_line_boundary(selection.start.to_point(map)).1,
1733 SelectionGoal::None,
1734 )
1735 });
1736 }
1737 Some(Mode::VisualBlock) => {
1738 let mut first = s.first_anchor();
1739 first.collapse_to(first.start, first.goal);
1740 s.select_anchors(vec![first]);
1741 }
1742 _ => {
1743 s.move_with(|map, selection| {
1744 selection.collapse_to(
1745 map.clip_at_line_end(selection.start),
1746 selection.goal,
1747 );
1748 });
1749 }
1750 }
1751 });
1752 });
1753 self.switch_mode(Mode::Normal, true, window, cx)
1754 }
1755 Mode::Normal => {
1756 self.update_editor(cx, |_, editor, cx| {
1757 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1758 s.move_with(|map, selection| {
1759 selection
1760 .collapse_to(map.clip_at_line_end(selection.end), selection.goal)
1761 })
1762 })
1763 });
1764 }
1765 Mode::Insert | Mode::Replace | Mode::HelixNormal => {}
1766 }
1767 }
1768
1769 fn local_selections_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1770 let Some(editor) = self.editor() else { return };
1771
1772 if editor.read(cx).leader_id().is_some() {
1773 return;
1774 }
1775
1776 let newest = editor.read(cx).selections.newest_anchor().clone();
1777 let is_multicursor = editor.read(cx).selections.count() > 1;
1778 if self.mode == Mode::Insert && self.current_tx.is_some() {
1779 if self.current_anchor.is_none() {
1780 self.current_anchor = Some(newest);
1781 } else if self.current_anchor.as_ref().unwrap() != &newest
1782 && let Some(tx_id) = self.current_tx.take()
1783 {
1784 self.update_editor(cx, |_, editor, cx| {
1785 editor.group_until_transaction(tx_id, cx)
1786 });
1787 }
1788 } else if self.mode == Mode::Normal && newest.start != newest.end {
1789 if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
1790 self.switch_mode(Mode::VisualBlock, false, window, cx);
1791 } else {
1792 self.switch_mode(Mode::Visual, false, window, cx)
1793 }
1794 } else if newest.start == newest.end
1795 && !is_multicursor
1796 && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&self.mode)
1797 {
1798 self.switch_mode(Mode::Normal, false, window, cx);
1799 }
1800 }
1801
1802 fn input_ignored(&mut self, text: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
1803 if text.is_empty() {
1804 return;
1805 }
1806
1807 match self.active_operator() {
1808 Some(Operator::FindForward { before, multiline }) => {
1809 let find = Motion::FindForward {
1810 before,
1811 char: text.chars().next().unwrap(),
1812 mode: if multiline {
1813 FindRange::MultiLine
1814 } else {
1815 FindRange::SingleLine
1816 },
1817 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1818 };
1819 Vim::globals(cx).last_find = Some(find.clone());
1820 self.motion(find, window, cx)
1821 }
1822 Some(Operator::FindBackward { after, multiline }) => {
1823 let find = Motion::FindBackward {
1824 after,
1825 char: text.chars().next().unwrap(),
1826 mode: if multiline {
1827 FindRange::MultiLine
1828 } else {
1829 FindRange::SingleLine
1830 },
1831 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1832 };
1833 Vim::globals(cx).last_find = Some(find.clone());
1834 self.motion(find, window, cx)
1835 }
1836 Some(Operator::Sneak { first_char }) => {
1837 if let Some(first_char) = first_char {
1838 if let Some(second_char) = text.chars().next() {
1839 let sneak = Motion::Sneak {
1840 first_char,
1841 second_char,
1842 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1843 };
1844 Vim::globals(cx).last_find = Some(sneak.clone());
1845 self.motion(sneak, window, cx)
1846 }
1847 } else {
1848 let first_char = text.chars().next();
1849 self.pop_operator(window, cx);
1850 self.push_operator(Operator::Sneak { first_char }, window, cx);
1851 }
1852 }
1853 Some(Operator::SneakBackward { first_char }) => {
1854 if let Some(first_char) = first_char {
1855 if let Some(second_char) = text.chars().next() {
1856 let sneak = Motion::SneakBackward {
1857 first_char,
1858 second_char,
1859 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1860 };
1861 Vim::globals(cx).last_find = Some(sneak.clone());
1862 self.motion(sneak, window, cx)
1863 }
1864 } else {
1865 let first_char = text.chars().next();
1866 self.pop_operator(window, cx);
1867 self.push_operator(Operator::SneakBackward { first_char }, window, cx);
1868 }
1869 }
1870 Some(Operator::Replace) => match self.mode {
1871 Mode::Normal => self.normal_replace(text, window, cx),
1872 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1873 self.visual_replace(text, window, cx)
1874 }
1875 Mode::HelixNormal => self.helix_replace(&text, window, cx),
1876 _ => self.clear_operator(window, cx),
1877 },
1878 Some(Operator::Digraph { first_char }) => {
1879 if let Some(first_char) = first_char {
1880 if let Some(second_char) = text.chars().next() {
1881 self.insert_digraph(first_char, second_char, window, cx);
1882 }
1883 } else {
1884 let first_char = text.chars().next();
1885 self.pop_operator(window, cx);
1886 self.push_operator(Operator::Digraph { first_char }, window, cx);
1887 }
1888 }
1889 Some(Operator::Literal { prefix }) => {
1890 self.handle_literal_input(prefix.unwrap_or_default(), &text, window, cx)
1891 }
1892 Some(Operator::AddSurrounds { target }) => match self.mode {
1893 Mode::Normal => {
1894 if let Some(target) = target {
1895 self.add_surrounds(text, target, window, cx);
1896 self.clear_operator(window, cx);
1897 }
1898 }
1899 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1900 self.add_surrounds(text, SurroundsType::Selection, window, cx);
1901 self.clear_operator(window, cx);
1902 }
1903 _ => self.clear_operator(window, cx),
1904 },
1905 Some(Operator::ChangeSurrounds { target, opening }) => match self.mode {
1906 Mode::Normal => {
1907 if let Some(target) = target {
1908 self.change_surrounds(text, target, opening, window, cx);
1909 self.clear_operator(window, cx);
1910 }
1911 }
1912 _ => self.clear_operator(window, cx),
1913 },
1914 Some(Operator::DeleteSurrounds) => match self.mode {
1915 Mode::Normal => {
1916 self.delete_surrounds(text, window, cx);
1917 self.clear_operator(window, cx);
1918 }
1919 _ => self.clear_operator(window, cx),
1920 },
1921 Some(Operator::HelixSurroundAdd) => match self.mode {
1922 Mode::HelixNormal | Mode::HelixSelect => {
1923 self.update_editor(cx, |_, editor, cx| {
1924 editor.change_selections(Default::default(), window, cx, |s| {
1925 s.move_with(|map, selection| {
1926 if selection.is_empty() {
1927 selection.end = movement::right(map, selection.start);
1928 }
1929 });
1930 });
1931 });
1932 self.helix_surround_add(&text, window, cx);
1933 self.switch_mode(Mode::HelixNormal, false, window, cx);
1934 self.clear_operator(window, cx);
1935 }
1936 _ => self.clear_operator(window, cx),
1937 },
1938 Some(Operator::HelixSurroundReplace {
1939 replaced_char: Some(old),
1940 }) => match self.mode {
1941 Mode::HelixNormal | Mode::HelixSelect => {
1942 if let Some(new_char) = text.chars().next() {
1943 self.helix_surround_replace(old, new_char, window, cx);
1944 }
1945 self.clear_operator(window, cx);
1946 }
1947 _ => self.clear_operator(window, cx),
1948 },
1949 Some(Operator::HelixSurroundReplace {
1950 replaced_char: None,
1951 }) => match self.mode {
1952 Mode::HelixNormal | Mode::HelixSelect => {
1953 if let Some(ch) = text.chars().next() {
1954 self.pop_operator(window, cx);
1955 self.push_operator(
1956 Operator::HelixSurroundReplace {
1957 replaced_char: Some(ch),
1958 },
1959 window,
1960 cx,
1961 );
1962 }
1963 }
1964 _ => self.clear_operator(window, cx),
1965 },
1966 Some(Operator::HelixSurroundDelete) => match self.mode {
1967 Mode::HelixNormal | Mode::HelixSelect => {
1968 if let Some(ch) = text.chars().next() {
1969 self.helix_surround_delete(ch, window, cx);
1970 }
1971 self.clear_operator(window, cx);
1972 }
1973 _ => self.clear_operator(window, cx),
1974 },
1975 Some(Operator::Mark) => self.create_mark(text, window, cx),
1976 Some(Operator::RecordRegister) => {
1977 self.record_register(text.chars().next().unwrap(), window, cx)
1978 }
1979 Some(Operator::ReplayRegister) => {
1980 self.replay_register(text.chars().next().unwrap(), window, cx)
1981 }
1982 Some(Operator::Register) => match self.mode {
1983 Mode::Insert => {
1984 self.update_editor(cx, |_, editor, cx| {
1985 if let Some(register) = Vim::update_globals(cx, |globals, cx| {
1986 globals.read_register(text.chars().next(), Some(editor), cx)
1987 }) {
1988 editor.do_paste(
1989 ®ister.text.to_string(),
1990 register.clipboard_selections,
1991 false,
1992 window,
1993 cx,
1994 )
1995 }
1996 });
1997 self.clear_operator(window, cx);
1998 }
1999 _ => {
2000 self.select_register(text, window, cx);
2001 }
2002 },
2003 Some(Operator::Jump { line }) => self.jump(text, line, true, window, cx),
2004 _ => {
2005 if self.mode == Mode::Replace {
2006 self.multi_replace(text, window, cx)
2007 }
2008
2009 if self.mode == Mode::Normal {
2010 self.update_editor(cx, |_, editor, cx| {
2011 editor.accept_edit_prediction(
2012 &editor::actions::AcceptEditPrediction {},
2013 window,
2014 cx,
2015 );
2016 });
2017 }
2018 }
2019 }
2020 }
2021
2022 fn sync_vim_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2023 self.update_editor(cx, |vim, editor, cx| {
2024 editor.set_cursor_shape(vim.cursor_shape(cx), cx);
2025 editor.set_clip_at_line_ends(vim.clip_at_line_ends(), cx);
2026 let collapse_matches = !HelixModeSetting::get_global(cx).0;
2027 editor.set_collapse_matches(collapse_matches);
2028 editor.set_input_enabled(vim.editor_input_enabled());
2029 editor.set_autoindent(vim.should_autoindent());
2030 editor.set_cursor_offset_on_selection(vim.mode.is_visual());
2031 editor
2032 .selections
2033 .set_line_mode(matches!(vim.mode, Mode::VisualLine));
2034
2035 let hide_edit_predictions = !matches!(vim.mode, Mode::Insert | Mode::Replace);
2036 editor.set_edit_predictions_hidden_for_vim_mode(hide_edit_predictions, window, cx);
2037 });
2038 cx.notify()
2039 }
2040}
2041
2042#[derive(RegisterSetting)]
2043struct VimSettings {
2044 pub default_mode: Mode,
2045 pub toggle_relative_line_numbers: bool,
2046 pub use_system_clipboard: settings::UseSystemClipboard,
2047 pub use_smartcase_find: bool,
2048 pub custom_digraphs: HashMap<String, Arc<str>>,
2049 pub highlight_on_yank_duration: u64,
2050 pub cursor_shape: CursorShapeSettings,
2051}
2052
2053/// Cursor shape configuration for insert mode.
2054#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2055pub enum InsertModeCursorShape {
2056 /// Inherit cursor shape from the editor's base cursor_shape setting.
2057 /// This allows users to set their preferred editor cursor and have
2058 /// it automatically apply to vim insert mode.
2059 Inherit,
2060 /// Use an explicit cursor shape for insert mode.
2061 Explicit(CursorShape),
2062}
2063
2064/// The settings for cursor shape.
2065#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2066pub struct CursorShapeSettings {
2067 /// Cursor shape for the normal mode.
2068 ///
2069 /// Default: block
2070 pub normal: CursorShape,
2071 /// Cursor shape for the replace mode.
2072 ///
2073 /// Default: underline
2074 pub replace: CursorShape,
2075 /// Cursor shape for the visual mode.
2076 ///
2077 /// Default: block
2078 pub visual: CursorShape,
2079 /// Cursor shape for the insert mode.
2080 ///
2081 /// Default: Inherit (follows editor.cursor_shape)
2082 pub insert: InsertModeCursorShape,
2083}
2084
2085impl From<settings::VimInsertModeCursorShape> for InsertModeCursorShape {
2086 fn from(shape: settings::VimInsertModeCursorShape) -> Self {
2087 match shape {
2088 settings::VimInsertModeCursorShape::Inherit => InsertModeCursorShape::Inherit,
2089 settings::VimInsertModeCursorShape::Bar => {
2090 InsertModeCursorShape::Explicit(CursorShape::Bar)
2091 }
2092 settings::VimInsertModeCursorShape::Block => {
2093 InsertModeCursorShape::Explicit(CursorShape::Block)
2094 }
2095 settings::VimInsertModeCursorShape::Underline => {
2096 InsertModeCursorShape::Explicit(CursorShape::Underline)
2097 }
2098 settings::VimInsertModeCursorShape::Hollow => {
2099 InsertModeCursorShape::Explicit(CursorShape::Hollow)
2100 }
2101 }
2102 }
2103}
2104
2105impl From<settings::CursorShapeSettings> for CursorShapeSettings {
2106 fn from(settings: settings::CursorShapeSettings) -> Self {
2107 Self {
2108 normal: settings.normal.unwrap().into(),
2109 replace: settings.replace.unwrap().into(),
2110 visual: settings.visual.unwrap().into(),
2111 insert: settings.insert.unwrap().into(),
2112 }
2113 }
2114}
2115
2116impl From<settings::ModeContent> for Mode {
2117 fn from(mode: ModeContent) -> Self {
2118 match mode {
2119 ModeContent::Normal => Self::Normal,
2120 ModeContent::Insert => Self::Insert,
2121 }
2122 }
2123}
2124
2125impl Settings for VimSettings {
2126 fn from_settings(content: &settings::SettingsContent) -> Self {
2127 let vim = content.vim.clone().unwrap();
2128 Self {
2129 default_mode: vim.default_mode.unwrap().into(),
2130 toggle_relative_line_numbers: vim.toggle_relative_line_numbers.unwrap(),
2131 use_system_clipboard: vim.use_system_clipboard.unwrap(),
2132 use_smartcase_find: vim.use_smartcase_find.unwrap(),
2133 custom_digraphs: vim.custom_digraphs.unwrap(),
2134 highlight_on_yank_duration: vim.highlight_on_yank_duration.unwrap(),
2135 cursor_shape: vim.cursor_shape.unwrap().into(),
2136 }
2137 }
2138}