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_expects_character_input(true);
982 editor.set_autoindent(true);
983 editor.selections.set_line_mode(false);
984 editor.unregister_addon::<VimAddon>();
985 editor.set_relative_line_number(None, cx);
986 if let Some(vim) = Vim::globals(cx).focused_vim()
987 && vim.entity_id() == cx.entity().entity_id()
988 {
989 Vim::globals(cx).focused_vim = None;
990 }
991 }
992
993 /// Register an action on the editor.
994 pub fn action<A: Action>(
995 editor: &mut Editor,
996 cx: &mut Context<Vim>,
997 f: impl Fn(&mut Vim, &A, &mut Window, &mut Context<Vim>) + 'static,
998 ) {
999 let subscription = editor.register_action(cx.listener(move |vim, action, window, cx| {
1000 if !Vim::globals(cx).dot_replaying {
1001 if vim.status_label.take().is_some() {
1002 cx.notify();
1003 }
1004 }
1005 f(vim, action, window, cx);
1006 }));
1007 cx.on_release(|_, _| drop(subscription)).detach();
1008 }
1009
1010 pub fn editor(&self) -> Option<Entity<Editor>> {
1011 self.editor.upgrade()
1012 }
1013
1014 pub fn workspace(&self, window: &Window, cx: &App) -> Option<Entity<Workspace>> {
1015 Workspace::for_window(window, cx)
1016 }
1017
1018 pub fn pane(&self, window: &Window, cx: &Context<Self>) -> Option<Entity<Pane>> {
1019 self.workspace(window, cx)
1020 .map(|workspace| workspace.read(cx).focused_pane(window, cx))
1021 }
1022
1023 pub fn enabled(cx: &mut App) -> bool {
1024 VimModeSetting::get_global(cx).0 || HelixModeSetting::get_global(cx).0
1025 }
1026
1027 /// Called whenever an keystroke is typed so vim can observe all actions
1028 /// and keystrokes accordingly.
1029 fn observe_keystrokes(
1030 &mut self,
1031 keystroke_event: &KeystrokeEvent,
1032 window: &mut Window,
1033 cx: &mut Context<Self>,
1034 ) {
1035 if self.exit_temporary_mode {
1036 self.exit_temporary_mode = false;
1037 // Don't switch to insert mode if the action is temporary_normal.
1038 if let Some(action) = keystroke_event.action.as_ref()
1039 && action.as_any().downcast_ref::<TemporaryNormal>().is_some()
1040 {
1041 return;
1042 }
1043 self.switch_mode(Mode::Insert, false, window, cx)
1044 }
1045 if let Some(action) = keystroke_event.action.as_ref() {
1046 // Keystroke is handled by the vim system, so continue forward
1047 if action.name().starts_with("vim::") {
1048 self.update_editor(cx, |_, editor, cx| {
1049 editor.hide_mouse_cursor(HideMouseCursorOrigin::MovementAction, cx)
1050 });
1051
1052 return;
1053 }
1054 } else if window.has_pending_keystrokes() || keystroke_event.keystroke.is_ime_in_progress()
1055 {
1056 return;
1057 }
1058
1059 if let Some(operator) = self.active_operator() {
1060 match operator {
1061 Operator::Literal { prefix } => {
1062 self.handle_literal_keystroke(
1063 keystroke_event,
1064 prefix.unwrap_or_default(),
1065 window,
1066 cx,
1067 );
1068 }
1069 _ if !operator.is_waiting(self.mode) => {
1070 self.clear_operator(window, cx);
1071 self.stop_recording_immediately(Box::new(ClearOperators), cx)
1072 }
1073 _ => {}
1074 }
1075 }
1076 }
1077
1078 fn handle_editor_event(
1079 &mut self,
1080 event: &EditorEvent,
1081 window: &mut Window,
1082 cx: &mut Context<Self>,
1083 ) {
1084 match event {
1085 EditorEvent::Focused => self.focused(true, window, cx),
1086 EditorEvent::Blurred => self.blurred(window, cx),
1087 EditorEvent::SelectionsChanged { local: true } => {
1088 self.local_selections_changed(window, cx);
1089 }
1090 EditorEvent::InputIgnored { text } => {
1091 self.input_ignored(text.clone(), window, cx);
1092 Vim::globals(cx).observe_insertion(text, None)
1093 }
1094 EditorEvent::InputHandled {
1095 text,
1096 utf16_range_to_replace: range_to_replace,
1097 } => Vim::globals(cx).observe_insertion(text, range_to_replace.clone()),
1098 EditorEvent::TransactionBegun { transaction_id } => {
1099 self.transaction_begun(*transaction_id, window, cx)
1100 }
1101 EditorEvent::TransactionUndone { transaction_id } => {
1102 self.transaction_undone(transaction_id, window, cx)
1103 }
1104 EditorEvent::Edited { .. } => self.push_to_change_list(window, cx),
1105 EditorEvent::FocusedIn => self.sync_vim_settings(window, cx),
1106 EditorEvent::CursorShapeChanged => self.cursor_shape_changed(window, cx),
1107 EditorEvent::PushedToNavHistory {
1108 anchor,
1109 is_deactivate,
1110 } => {
1111 self.update_editor(cx, |vim, editor, cx| {
1112 let mark = if *is_deactivate {
1113 "\"".to_string()
1114 } else {
1115 "'".to_string()
1116 };
1117 vim.set_mark(mark, vec![*anchor], editor.buffer(), window, cx);
1118 });
1119 }
1120 _ => {}
1121 }
1122 }
1123
1124 fn push_operator(&mut self, operator: Operator, window: &mut Window, cx: &mut Context<Self>) {
1125 if operator.starts_dot_recording() {
1126 self.start_recording(cx);
1127 }
1128 // Since these operations can only be entered with pre-operators,
1129 // we need to clear the previous operators when pushing,
1130 // so that the current stack is the most correct
1131 if matches!(
1132 operator,
1133 Operator::AddSurrounds { .. }
1134 | Operator::ChangeSurrounds { .. }
1135 | Operator::DeleteSurrounds
1136 | Operator::Exchange
1137 ) {
1138 self.operator_stack.clear();
1139 };
1140 self.operator_stack.push(operator);
1141 self.sync_vim_settings(window, cx);
1142 }
1143
1144 pub fn switch_mode(
1145 &mut self,
1146 mode: Mode,
1147 leave_selections: bool,
1148 window: &mut Window,
1149 cx: &mut Context<Self>,
1150 ) {
1151 if self.temp_mode && mode == Mode::Normal {
1152 self.temp_mode = false;
1153 self.switch_mode(Mode::Normal, leave_selections, window, cx);
1154 self.switch_mode(Mode::Insert, false, window, cx);
1155 return;
1156 } else if self.temp_mode
1157 && !matches!(mode, Mode::Visual | Mode::VisualLine | Mode::VisualBlock)
1158 {
1159 self.temp_mode = false;
1160 }
1161
1162 let last_mode = self.mode;
1163 let prior_mode = self.last_mode;
1164 let prior_tx = self.current_tx;
1165 self.last_mode = last_mode;
1166 self.mode = mode;
1167 self.operator_stack.clear();
1168 self.selected_register.take();
1169 self.cancel_running_command(window, cx);
1170 if mode == Mode::Normal || mode != last_mode {
1171 self.current_tx.take();
1172 self.current_anchor.take();
1173 self.update_editor(cx, |_, editor, _| {
1174 editor.clear_selection_drag_state();
1175 });
1176 }
1177 Vim::take_forced_motion(cx);
1178 if mode != Mode::Insert && mode != Mode::Replace {
1179 Vim::take_count(cx);
1180 }
1181
1182 // Sync editor settings like clip mode
1183 self.sync_vim_settings(window, cx);
1184
1185 if VimSettings::get_global(cx).toggle_relative_line_numbers
1186 && self.mode != self.last_mode
1187 && (self.mode == Mode::Insert || self.last_mode == Mode::Insert)
1188 {
1189 self.update_editor(cx, |vim, editor, cx| {
1190 let is_relative = vim.mode != Mode::Insert;
1191 editor.set_relative_line_number(Some(is_relative), cx)
1192 });
1193 }
1194 if HelixModeSetting::get_global(cx).0 {
1195 if self.mode == Mode::Normal {
1196 self.mode = Mode::HelixNormal
1197 } else if self.mode == Mode::Visual {
1198 self.mode = Mode::HelixSelect
1199 }
1200 }
1201
1202 if leave_selections {
1203 return;
1204 }
1205
1206 if !mode.is_visual() && last_mode.is_visual() {
1207 self.create_visual_marks(last_mode, window, cx);
1208 }
1209
1210 // Adjust selections
1211 self.update_editor(cx, |vim, editor, cx| {
1212 if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
1213 {
1214 vim.visual_block_motion(true, editor, window, cx, &mut |_, point, goal| {
1215 Some((point, goal))
1216 })
1217 }
1218 if (last_mode == Mode::Insert || last_mode == Mode::Replace)
1219 && let Some(prior_tx) = prior_tx
1220 {
1221 editor.group_until_transaction(prior_tx, cx)
1222 }
1223
1224 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1225 // we cheat with visual block mode and use multiple cursors.
1226 // the cost of this cheat is we need to convert back to a single
1227 // cursor whenever vim would.
1228 if last_mode == Mode::VisualBlock
1229 && (mode != Mode::VisualBlock && mode != Mode::Insert)
1230 {
1231 let tail = s.oldest_anchor().tail();
1232 let head = s.newest_anchor().head();
1233 s.select_anchor_ranges(vec![tail..head]);
1234 } else if last_mode == Mode::Insert
1235 && prior_mode == Mode::VisualBlock
1236 && mode != Mode::VisualBlock
1237 {
1238 let pos = s.first_anchor().head();
1239 s.select_anchor_ranges(vec![pos..pos])
1240 }
1241
1242 let mut should_extend_pending = false;
1243 if !last_mode.is_visual()
1244 && mode.is_visual()
1245 && let Some(pending) = s.pending_anchor()
1246 {
1247 let snapshot = s.display_snapshot();
1248 let is_empty = pending
1249 .start
1250 .cmp(&pending.end, &snapshot.buffer_snapshot())
1251 .is_eq();
1252 should_extend_pending = pending.reversed
1253 && !is_empty
1254 && vim.extended_pending_selection_id != Some(pending.id);
1255 };
1256
1257 if should_extend_pending {
1258 let snapshot = s.display_snapshot();
1259 s.change_with(&snapshot, |map| {
1260 if let Some(pending) = map.pending_anchor_mut() {
1261 let end = pending.end.to_point(&snapshot.buffer_snapshot());
1262 let end = end.to_display_point(&snapshot);
1263 let new_end = movement::right(&snapshot, end);
1264 pending.end = snapshot
1265 .buffer_snapshot()
1266 .anchor_before(new_end.to_point(&snapshot));
1267 }
1268 });
1269 vim.extended_pending_selection_id = s.pending_anchor().map(|p| p.id)
1270 }
1271
1272 s.move_with(&mut |map, selection| {
1273 if last_mode.is_visual() && !mode.is_visual() {
1274 let mut point = selection.head();
1275 if !selection.reversed && !selection.is_empty() {
1276 point = movement::left(map, selection.head());
1277 } else if selection.is_empty() {
1278 point = map.clip_point(point, Bias::Left);
1279 }
1280 selection.collapse_to(point, selection.goal)
1281 } else if !last_mode.is_visual() && mode.is_visual() {
1282 if selection.is_empty() {
1283 selection.end = movement::right(map, selection.start);
1284 }
1285 }
1286 });
1287 })
1288 });
1289 }
1290
1291 pub fn take_count(cx: &mut App) -> Option<usize> {
1292 let global_state = cx.global_mut::<VimGlobals>();
1293 if global_state.dot_replaying {
1294 return global_state.recorded_count;
1295 }
1296
1297 let count = if global_state.post_count.is_none() && global_state.pre_count.is_none() {
1298 return None;
1299 } else {
1300 Some(
1301 global_state.post_count.take().unwrap_or(1)
1302 * global_state.pre_count.take().unwrap_or(1),
1303 )
1304 };
1305
1306 if global_state.dot_recording {
1307 global_state.recording_count = count;
1308 }
1309 count
1310 }
1311
1312 pub fn take_forced_motion(cx: &mut App) -> bool {
1313 let global_state = cx.global_mut::<VimGlobals>();
1314 let forced_motion = global_state.forced_motion;
1315 global_state.forced_motion = false;
1316 forced_motion
1317 }
1318
1319 pub fn cursor_shape(&self, cx: &App) -> CursorShape {
1320 let cursor_shape = VimSettings::get_global(cx).cursor_shape;
1321 match self.mode {
1322 Mode::Normal => {
1323 if let Some(operator) = self.operator_stack.last() {
1324 match operator {
1325 // Navigation operators -> Block cursor
1326 Operator::FindForward { .. }
1327 | Operator::FindBackward { .. }
1328 | Operator::Mark
1329 | Operator::Jump { .. }
1330 | Operator::Register
1331 | Operator::RecordRegister
1332 | Operator::ReplayRegister => CursorShape::Block,
1333
1334 // All other operators -> Underline cursor
1335 _ => CursorShape::Underline,
1336 }
1337 } else {
1338 cursor_shape.normal
1339 }
1340 }
1341 Mode::HelixNormal => cursor_shape.normal,
1342 Mode::Replace => cursor_shape.replace,
1343 Mode::Visual | Mode::VisualLine | Mode::VisualBlock | Mode::HelixSelect => {
1344 cursor_shape.visual
1345 }
1346 Mode::Insert => match cursor_shape.insert {
1347 InsertModeCursorShape::Explicit(shape) => shape,
1348 InsertModeCursorShape::Inherit => {
1349 let editor_settings = EditorSettings::get_global(cx);
1350 editor_settings.cursor_shape.unwrap_or_default()
1351 }
1352 },
1353 }
1354 }
1355
1356 fn expects_character_input(&self) -> bool {
1357 if let Some(operator) = self.operator_stack.last() {
1358 if operator.is_waiting(self.mode) {
1359 return true;
1360 }
1361 }
1362 self.editor_input_enabled()
1363 }
1364
1365 pub fn editor_input_enabled(&self) -> bool {
1366 match self.mode {
1367 Mode::Insert => {
1368 if let Some(operator) = self.operator_stack.last() {
1369 !operator.is_waiting(self.mode)
1370 } else {
1371 true
1372 }
1373 }
1374 Mode::Normal
1375 | Mode::HelixNormal
1376 | Mode::Replace
1377 | Mode::Visual
1378 | Mode::VisualLine
1379 | Mode::VisualBlock
1380 | Mode::HelixSelect => false,
1381 }
1382 }
1383
1384 pub fn should_autoindent(&self) -> bool {
1385 !(self.mode == Mode::Insert && self.last_mode == Mode::VisualBlock)
1386 }
1387
1388 pub fn clip_at_line_ends(&self) -> bool {
1389 match self.mode {
1390 Mode::Insert
1391 | Mode::Visual
1392 | Mode::VisualLine
1393 | Mode::VisualBlock
1394 | Mode::Replace
1395 | Mode::HelixNormal
1396 | Mode::HelixSelect => false,
1397 Mode::Normal => true,
1398 }
1399 }
1400
1401 pub fn extend_key_context(&self, context: &mut KeyContext, cx: &App) {
1402 let mut mode = match self.mode {
1403 Mode::Normal => "normal",
1404 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => "visual",
1405 Mode::Insert => "insert",
1406 Mode::Replace => "replace",
1407 Mode::HelixNormal => "helix_normal",
1408 Mode::HelixSelect => "helix_select",
1409 }
1410 .to_string();
1411
1412 let mut operator_id = "none";
1413
1414 let active_operator = self.active_operator();
1415 if active_operator.is_none() && cx.global::<VimGlobals>().pre_count.is_some()
1416 || active_operator.is_some() && cx.global::<VimGlobals>().post_count.is_some()
1417 {
1418 context.add("VimCount");
1419 }
1420
1421 if let Some(active_operator) = active_operator {
1422 if active_operator.is_waiting(self.mode) {
1423 if matches!(active_operator, Operator::Literal { .. }) {
1424 mode = "literal".to_string();
1425 } else {
1426 mode = "waiting".to_string();
1427 }
1428 } else {
1429 operator_id = active_operator.id();
1430 mode = "operator".to_string();
1431 }
1432 }
1433
1434 if mode == "normal"
1435 || mode == "visual"
1436 || mode == "operator"
1437 || mode == "helix_normal"
1438 || mode == "helix_select"
1439 {
1440 context.add("VimControl");
1441 }
1442 context.set("vim_mode", mode);
1443 context.set("vim_operator", operator_id);
1444 }
1445
1446 fn focused(&mut self, preserve_selection: bool, window: &mut Window, cx: &mut Context<Self>) {
1447 // If editor gains focus while search bar is still open (not dismissed),
1448 // the user has explicitly navigated away - clear prior_selections so we
1449 // don't restore to the old position if they later dismiss the search.
1450 if !self.search.prior_selections.is_empty() {
1451 if let Some(pane) = self.pane(window, cx) {
1452 let search_still_open = pane
1453 .read(cx)
1454 .toolbar()
1455 .read(cx)
1456 .item_of_type::<BufferSearchBar>()
1457 .is_some_and(|bar| !bar.read(cx).is_dismissed());
1458 if search_still_open {
1459 self.search.prior_selections.clear();
1460 }
1461 }
1462 }
1463
1464 let Some(editor) = self.editor() else {
1465 return;
1466 };
1467 let newest_selection_empty = editor.update(cx, |editor, cx| {
1468 editor
1469 .selections
1470 .newest::<MultiBufferOffset>(&editor.display_snapshot(cx))
1471 .is_empty()
1472 });
1473 let editor = editor.read(cx);
1474 let editor_mode = editor.mode();
1475
1476 if editor_mode.is_full()
1477 && !newest_selection_empty
1478 && self.mode == Mode::Normal
1479 // When following someone, don't switch vim mode.
1480 && editor.leader_id().is_none()
1481 {
1482 if preserve_selection {
1483 self.switch_mode(Mode::Visual, true, window, cx);
1484 } else {
1485 self.update_editor(cx, |_, editor, cx| {
1486 editor.set_clip_at_line_ends(false, cx);
1487 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1488 s.move_with(&mut |_, selection| {
1489 selection.collapse_to(selection.start, selection.goal)
1490 })
1491 });
1492 });
1493 }
1494 }
1495
1496 cx.emit(VimEvent::Focused);
1497 self.sync_vim_settings(window, cx);
1498
1499 if VimSettings::get_global(cx).toggle_relative_line_numbers {
1500 if let Some(old_vim) = Vim::globals(cx).focused_vim() {
1501 if old_vim.entity_id() != cx.entity().entity_id() {
1502 old_vim.update(cx, |vim, cx| {
1503 vim.update_editor(cx, |_, editor, cx| {
1504 editor.set_relative_line_number(None, cx)
1505 });
1506 });
1507
1508 self.update_editor(cx, |vim, editor, cx| {
1509 let is_relative = vim.mode != Mode::Insert;
1510 editor.set_relative_line_number(Some(is_relative), cx)
1511 });
1512 }
1513 } else {
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 }
1520 Vim::globals(cx).focused_vim = Some(cx.entity().downgrade());
1521 }
1522
1523 fn blurred(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1524 self.stop_recording_immediately(NormalBefore.boxed_clone(), cx);
1525 self.store_visual_marks(window, cx);
1526 self.clear_operator(window, cx);
1527 self.update_editor(cx, |vim, editor, cx| {
1528 if vim.cursor_shape(cx) == CursorShape::Block {
1529 editor.set_cursor_shape(CursorShape::Hollow, cx);
1530 }
1531 });
1532 }
1533
1534 fn cursor_shape_changed(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1535 self.update_editor(cx, |vim, editor, cx| {
1536 editor.set_cursor_shape(vim.cursor_shape(cx), cx);
1537 });
1538 }
1539
1540 fn update_editor<S>(
1541 &mut self,
1542 cx: &mut Context<Self>,
1543 update: impl FnOnce(&mut Self, &mut Editor, &mut Context<Editor>) -> S,
1544 ) -> Option<S> {
1545 let editor = self.editor.upgrade()?;
1546 Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
1547 }
1548
1549 fn editor_selections(&mut self, _: &mut Window, cx: &mut Context<Self>) -> Vec<Range<Anchor>> {
1550 self.update_editor(cx, |_, editor, _| {
1551 editor
1552 .selections
1553 .disjoint_anchors_arc()
1554 .iter()
1555 .map(|selection| selection.tail()..selection.head())
1556 .collect()
1557 })
1558 .unwrap_or_default()
1559 }
1560
1561 fn editor_cursor_word(
1562 &mut self,
1563 window: &mut Window,
1564 cx: &mut Context<Self>,
1565 ) -> Option<String> {
1566 self.update_editor(cx, |_, editor, cx| {
1567 let snapshot = &editor.snapshot(window, cx);
1568 let selection = editor
1569 .selections
1570 .newest::<MultiBufferOffset>(&snapshot.display_snapshot);
1571
1572 let snapshot = snapshot.buffer_snapshot();
1573 let (range, kind) =
1574 snapshot.surrounding_word(selection.start, Some(CharScopeContext::Completion));
1575 if kind == Some(CharKind::Word) {
1576 let text: String = snapshot.text_for_range(range).collect();
1577 if !text.trim().is_empty() {
1578 return Some(text);
1579 }
1580 }
1581
1582 None
1583 })
1584 .unwrap_or_default()
1585 }
1586
1587 /// When doing an action that modifies the buffer, we start recording so that `.`
1588 /// will replay the action.
1589 pub fn start_recording(&mut self, cx: &mut Context<Self>) {
1590 Vim::update_globals(cx, |globals, cx| {
1591 if !globals.dot_replaying {
1592 globals.dot_recording = true;
1593 globals.recording_actions = Default::default();
1594 globals.recording_count = None;
1595 globals.recording_register_for_dot = self.selected_register;
1596
1597 let selections = self.editor().map(|editor| {
1598 editor.update(cx, |editor, cx| {
1599 let snapshot = editor.display_snapshot(cx);
1600
1601 (
1602 editor.selections.oldest::<Point>(&snapshot),
1603 editor.selections.newest::<Point>(&snapshot),
1604 )
1605 })
1606 });
1607
1608 if let Some((oldest, newest)) = selections {
1609 globals.recorded_selection = match self.mode {
1610 Mode::Visual if newest.end.row == newest.start.row => {
1611 RecordedSelection::SingleLine {
1612 cols: newest.end.column - newest.start.column,
1613 }
1614 }
1615 Mode::Visual => RecordedSelection::Visual {
1616 rows: newest.end.row - newest.start.row,
1617 cols: newest.end.column,
1618 },
1619 Mode::VisualLine => RecordedSelection::VisualLine {
1620 rows: newest.end.row - newest.start.row,
1621 },
1622 Mode::VisualBlock => RecordedSelection::VisualBlock {
1623 rows: newest.end.row.abs_diff(oldest.start.row),
1624 cols: newest.end.column.abs_diff(oldest.start.column),
1625 },
1626 _ => RecordedSelection::None,
1627 }
1628 } else {
1629 globals.recorded_selection = RecordedSelection::None;
1630 }
1631 }
1632 })
1633 }
1634
1635 pub fn stop_replaying(&mut self, cx: &mut Context<Self>) {
1636 let globals = Vim::globals(cx);
1637 globals.dot_replaying = false;
1638 if let Some(replayer) = globals.replayer.take() {
1639 replayer.stop();
1640 }
1641 }
1642
1643 /// When finishing an action that modifies the buffer, stop recording.
1644 /// as you usually call this within a keystroke handler we also ensure that
1645 /// the current action is recorded.
1646 pub fn stop_recording(&mut self, cx: &mut Context<Self>) {
1647 let globals = Vim::globals(cx);
1648 if globals.dot_recording {
1649 globals.stop_recording_after_next_action = true;
1650 }
1651 self.exit_temporary_mode = self.temp_mode;
1652 }
1653
1654 /// Stops recording actions immediately rather than waiting until after the
1655 /// next action to stop recording.
1656 ///
1657 /// This doesn't include the current action.
1658 pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>, cx: &mut Context<Self>) {
1659 let globals = Vim::globals(cx);
1660 if globals.dot_recording {
1661 globals
1662 .recording_actions
1663 .push(ReplayableAction::Action(action.boxed_clone()));
1664 globals.recorded_actions = mem::take(&mut globals.recording_actions);
1665 globals.recorded_count = globals.recording_count.take();
1666 globals.dot_recording = false;
1667 globals.stop_recording_after_next_action = false;
1668 }
1669 self.exit_temporary_mode = self.temp_mode;
1670 }
1671
1672 /// Explicitly record one action (equivalents to start_recording and stop_recording)
1673 pub fn record_current_action(&mut self, cx: &mut Context<Self>) {
1674 self.start_recording(cx);
1675 self.stop_recording(cx);
1676 }
1677
1678 fn push_count_digit(&mut self, number: usize, window: &mut Window, cx: &mut Context<Self>) {
1679 if self.active_operator().is_some() {
1680 let post_count = Vim::globals(cx).post_count.unwrap_or(0);
1681
1682 Vim::globals(cx).post_count = Some(
1683 post_count
1684 .checked_mul(10)
1685 .and_then(|post_count| post_count.checked_add(number))
1686 .filter(|post_count| *post_count < isize::MAX as usize)
1687 .unwrap_or(post_count),
1688 )
1689 } else {
1690 let pre_count = Vim::globals(cx).pre_count.unwrap_or(0);
1691
1692 Vim::globals(cx).pre_count = Some(
1693 pre_count
1694 .checked_mul(10)
1695 .and_then(|pre_count| pre_count.checked_add(number))
1696 .filter(|pre_count| *pre_count < isize::MAX as usize)
1697 .unwrap_or(pre_count),
1698 )
1699 }
1700 // update the keymap so that 0 works
1701 self.sync_vim_settings(window, cx)
1702 }
1703
1704 fn select_register(&mut self, register: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
1705 if register.chars().count() == 1 {
1706 self.selected_register
1707 .replace(register.chars().next().unwrap());
1708 }
1709 self.operator_stack.clear();
1710 self.sync_vim_settings(window, cx);
1711 }
1712
1713 fn maybe_pop_operator(&mut self) -> Option<Operator> {
1714 self.operator_stack.pop()
1715 }
1716
1717 fn pop_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Operator {
1718 let popped_operator = self.operator_stack.pop()
1719 .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
1720 self.sync_vim_settings(window, cx);
1721 popped_operator
1722 }
1723
1724 fn clear_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1725 Vim::take_count(cx);
1726 Vim::take_forced_motion(cx);
1727 self.selected_register.take();
1728 self.operator_stack.clear();
1729 self.sync_vim_settings(window, cx);
1730 }
1731
1732 fn active_operator(&self) -> Option<Operator> {
1733 self.operator_stack.last().cloned()
1734 }
1735
1736 fn transaction_begun(
1737 &mut self,
1738 transaction_id: TransactionId,
1739 _window: &mut Window,
1740 _: &mut Context<Self>,
1741 ) {
1742 let mode = if (self.mode == Mode::Insert
1743 || self.mode == Mode::Replace
1744 || self.mode == Mode::Normal)
1745 && self.current_tx.is_none()
1746 {
1747 self.current_tx = Some(transaction_id);
1748 self.last_mode
1749 } else {
1750 self.mode
1751 };
1752 if mode == Mode::VisualLine || mode == Mode::VisualBlock {
1753 self.undo_modes.insert(transaction_id, mode);
1754 }
1755 }
1756
1757 fn transaction_undone(
1758 &mut self,
1759 transaction_id: &TransactionId,
1760 window: &mut Window,
1761 cx: &mut Context<Self>,
1762 ) {
1763 match self.mode {
1764 Mode::VisualLine | Mode::VisualBlock | Mode::Visual | Mode::HelixSelect => {
1765 self.update_editor(cx, |vim, editor, cx| {
1766 let original_mode = vim.undo_modes.get(transaction_id);
1767 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1768 match original_mode {
1769 Some(Mode::VisualLine) => {
1770 s.move_with(&mut |map, selection| {
1771 selection.collapse_to(
1772 map.prev_line_boundary(selection.start.to_point(map)).1,
1773 SelectionGoal::None,
1774 )
1775 });
1776 }
1777 Some(Mode::VisualBlock) => {
1778 let mut first = s.first_anchor();
1779 first.collapse_to(first.start, first.goal);
1780 s.select_anchors(vec![first]);
1781 }
1782 _ => {
1783 s.move_with(&mut |map, selection| {
1784 selection.collapse_to(
1785 map.clip_at_line_end(selection.start),
1786 selection.goal,
1787 );
1788 });
1789 }
1790 }
1791 });
1792 });
1793 self.switch_mode(Mode::Normal, true, window, cx)
1794 }
1795 Mode::Normal => {
1796 self.update_editor(cx, |_, editor, cx| {
1797 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1798 s.move_with(&mut |map, selection| {
1799 selection
1800 .collapse_to(map.clip_at_line_end(selection.end), selection.goal)
1801 })
1802 })
1803 });
1804 }
1805 Mode::Insert | Mode::Replace | Mode::HelixNormal => {}
1806 }
1807 }
1808
1809 fn local_selections_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1810 let Some(editor) = self.editor() else { return };
1811
1812 if editor.read(cx).leader_id().is_some() {
1813 return;
1814 }
1815
1816 let newest = editor.read(cx).selections.newest_anchor().clone();
1817 let is_multicursor = editor.read(cx).selections.count() > 1;
1818 if self.mode == Mode::Insert && self.current_tx.is_some() {
1819 if let Some(current_anchor) = &self.current_anchor {
1820 if current_anchor != &newest
1821 && let Some(tx_id) = self.current_tx.take()
1822 {
1823 self.update_editor(cx, |_, editor, cx| {
1824 editor.group_until_transaction(tx_id, cx)
1825 });
1826 }
1827 } else {
1828 self.current_anchor = Some(newest);
1829 }
1830 } else if self.mode == Mode::Normal && newest.start != newest.end {
1831 if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
1832 self.switch_mode(Mode::VisualBlock, false, window, cx);
1833 } else {
1834 self.switch_mode(Mode::Visual, false, window, cx)
1835 }
1836 } else if newest.start == newest.end
1837 && !is_multicursor
1838 && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&self.mode)
1839 {
1840 self.switch_mode(Mode::Normal, false, window, cx);
1841 }
1842 }
1843
1844 fn input_ignored(&mut self, text: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
1845 if text.is_empty() {
1846 return;
1847 }
1848
1849 match self.active_operator() {
1850 Some(Operator::FindForward { before, multiline }) => {
1851 let find = Motion::FindForward {
1852 before,
1853 char: text.chars().next().unwrap(),
1854 mode: if multiline {
1855 FindRange::MultiLine
1856 } else {
1857 FindRange::SingleLine
1858 },
1859 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1860 };
1861 Vim::globals(cx).last_find = Some(find.clone());
1862 self.motion(find, window, cx)
1863 }
1864 Some(Operator::FindBackward { after, multiline }) => {
1865 let find = Motion::FindBackward {
1866 after,
1867 char: text.chars().next().unwrap(),
1868 mode: if multiline {
1869 FindRange::MultiLine
1870 } else {
1871 FindRange::SingleLine
1872 },
1873 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1874 };
1875 Vim::globals(cx).last_find = Some(find.clone());
1876 self.motion(find, window, cx)
1877 }
1878 Some(Operator::Sneak { first_char }) => {
1879 if let Some(first_char) = first_char {
1880 if let Some(second_char) = text.chars().next() {
1881 let sneak = Motion::Sneak {
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::Sneak { first_char }, window, cx);
1893 }
1894 }
1895 Some(Operator::SneakBackward { first_char }) => {
1896 if let Some(first_char) = first_char {
1897 if let Some(second_char) = text.chars().next() {
1898 let sneak = Motion::SneakBackward {
1899 first_char,
1900 second_char,
1901 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1902 };
1903 Vim::globals(cx).last_find = Some(sneak.clone());
1904 self.motion(sneak, window, cx)
1905 }
1906 } else {
1907 let first_char = text.chars().next();
1908 self.pop_operator(window, cx);
1909 self.push_operator(Operator::SneakBackward { first_char }, window, cx);
1910 }
1911 }
1912 Some(Operator::Replace) => match self.mode {
1913 Mode::Normal => self.normal_replace(text, window, cx),
1914 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1915 self.visual_replace(text, window, cx)
1916 }
1917 Mode::HelixNormal => self.helix_replace(&text, window, cx),
1918 _ => self.clear_operator(window, cx),
1919 },
1920 Some(Operator::Digraph { first_char }) => {
1921 if let Some(first_char) = first_char {
1922 if let Some(second_char) = text.chars().next() {
1923 self.insert_digraph(first_char, second_char, window, cx);
1924 }
1925 } else {
1926 let first_char = text.chars().next();
1927 self.pop_operator(window, cx);
1928 self.push_operator(Operator::Digraph { first_char }, window, cx);
1929 }
1930 }
1931 Some(Operator::Literal { prefix }) => {
1932 self.handle_literal_input(prefix.unwrap_or_default(), &text, window, cx)
1933 }
1934 Some(Operator::AddSurrounds { target }) => match self.mode {
1935 Mode::Normal => {
1936 if let Some(target) = target {
1937 self.add_surrounds(text, target, window, cx);
1938 self.clear_operator(window, cx);
1939 }
1940 }
1941 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1942 self.add_surrounds(text, SurroundsType::Selection, window, cx);
1943 self.clear_operator(window, cx);
1944 }
1945 _ => self.clear_operator(window, cx),
1946 },
1947 Some(Operator::ChangeSurrounds { target, opening }) => match self.mode {
1948 Mode::Normal => {
1949 if let Some(target) = target {
1950 self.change_surrounds(text, target, opening, window, cx);
1951 self.clear_operator(window, cx);
1952 }
1953 }
1954 _ => self.clear_operator(window, cx),
1955 },
1956 Some(Operator::DeleteSurrounds) => match self.mode {
1957 Mode::Normal => {
1958 self.delete_surrounds(text, window, cx);
1959 self.clear_operator(window, cx);
1960 }
1961 _ => self.clear_operator(window, cx),
1962 },
1963 Some(Operator::HelixSurroundAdd) => match self.mode {
1964 Mode::HelixNormal | Mode::HelixSelect => {
1965 self.update_editor(cx, |_, editor, cx| {
1966 editor.change_selections(Default::default(), window, cx, |s| {
1967 s.move_with(&mut |map, selection| {
1968 if selection.is_empty() {
1969 selection.end = movement::right(map, selection.start);
1970 }
1971 });
1972 });
1973 });
1974 self.helix_surround_add(&text, window, cx);
1975 self.switch_mode(Mode::HelixNormal, false, window, cx);
1976 self.clear_operator(window, cx);
1977 }
1978 _ => self.clear_operator(window, cx),
1979 },
1980 Some(Operator::HelixSurroundReplace {
1981 replaced_char: Some(old),
1982 }) => match self.mode {
1983 Mode::HelixNormal | Mode::HelixSelect => {
1984 if let Some(new_char) = text.chars().next() {
1985 self.helix_surround_replace(old, new_char, window, cx);
1986 }
1987 self.clear_operator(window, cx);
1988 }
1989 _ => self.clear_operator(window, cx),
1990 },
1991 Some(Operator::HelixSurroundReplace {
1992 replaced_char: None,
1993 }) => match self.mode {
1994 Mode::HelixNormal | Mode::HelixSelect => {
1995 if let Some(ch) = text.chars().next() {
1996 self.pop_operator(window, cx);
1997 self.push_operator(
1998 Operator::HelixSurroundReplace {
1999 replaced_char: Some(ch),
2000 },
2001 window,
2002 cx,
2003 );
2004 }
2005 }
2006 _ => self.clear_operator(window, cx),
2007 },
2008 Some(Operator::HelixSurroundDelete) => match self.mode {
2009 Mode::HelixNormal | Mode::HelixSelect => {
2010 if let Some(ch) = text.chars().next() {
2011 self.helix_surround_delete(ch, window, cx);
2012 }
2013 self.clear_operator(window, cx);
2014 }
2015 _ => self.clear_operator(window, cx),
2016 },
2017 Some(Operator::Mark) => self.create_mark(text, window, cx),
2018 Some(Operator::RecordRegister) => {
2019 self.record_register(text.chars().next().unwrap(), window, cx)
2020 }
2021 Some(Operator::ReplayRegister) => {
2022 self.replay_register(text.chars().next().unwrap(), window, cx)
2023 }
2024 Some(Operator::Register) => match self.mode {
2025 Mode::Insert => {
2026 self.update_editor(cx, |_, editor, cx| {
2027 if let Some(register) = Vim::update_globals(cx, |globals, cx| {
2028 globals.read_register(text.chars().next(), Some(editor), cx)
2029 }) {
2030 editor.do_paste(
2031 ®ister.text.to_string(),
2032 register.clipboard_selections,
2033 false,
2034 window,
2035 cx,
2036 )
2037 }
2038 });
2039 self.clear_operator(window, cx);
2040 }
2041 _ => {
2042 self.select_register(text, window, cx);
2043 }
2044 },
2045 Some(Operator::Jump { line }) => self.jump(text, line, true, window, cx),
2046 _ => {
2047 if self.mode == Mode::Replace {
2048 self.multi_replace(text, window, cx)
2049 }
2050
2051 if self.mode == Mode::Normal {
2052 self.update_editor(cx, |_, editor, cx| {
2053 editor.accept_edit_prediction(
2054 &editor::actions::AcceptEditPrediction {},
2055 window,
2056 cx,
2057 );
2058 });
2059 }
2060 }
2061 }
2062 }
2063
2064 fn sync_vim_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2065 let state = self.state_for_editor_settings(cx);
2066 self.update_editor(cx, |_, editor, cx| {
2067 Vim::sync_vim_settings_to_editor(&state, editor, window, cx);
2068 });
2069 cx.notify()
2070 }
2071
2072 fn state_for_editor_settings(&self, cx: &App) -> VimEditorSettingsState {
2073 VimEditorSettingsState {
2074 cursor_shape: self.cursor_shape(cx),
2075 clip_at_line_ends: self.clip_at_line_ends(),
2076 collapse_matches: !HelixModeSetting::get_global(cx).0,
2077 input_enabled: self.editor_input_enabled(),
2078 expects_character_input: self.expects_character_input(),
2079 autoindent: self.should_autoindent(),
2080 cursor_offset_on_selection: self.mode.is_visual() || self.mode.is_helix(),
2081 line_mode: matches!(self.mode, Mode::VisualLine),
2082 hide_edit_predictions: !matches!(self.mode, Mode::Insert | Mode::Replace),
2083 }
2084 }
2085
2086 fn sync_vim_settings_to_editor(
2087 state: &VimEditorSettingsState,
2088 editor: &mut Editor,
2089 window: &mut Window,
2090 cx: &mut Context<Editor>,
2091 ) {
2092 editor.set_cursor_shape(state.cursor_shape, cx);
2093 editor.set_clip_at_line_ends(state.clip_at_line_ends, cx);
2094 editor.set_collapse_matches(state.collapse_matches);
2095 editor.set_input_enabled(state.input_enabled);
2096 editor.set_expects_character_input(state.expects_character_input);
2097 editor.set_autoindent(state.autoindent);
2098 editor.set_cursor_offset_on_selection(state.cursor_offset_on_selection);
2099 editor.selections.set_line_mode(state.line_mode);
2100 editor.set_edit_predictions_hidden_for_vim_mode(state.hide_edit_predictions, window, cx);
2101 }
2102
2103 fn set_status_label(&mut self, label: impl Into<SharedString>, cx: &mut Context<Editor>) {
2104 self.status_label = Some(label.into());
2105 cx.notify();
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}