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