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