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