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