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 },
682 window,
683 cx,
684 )
685 },
686 );
687
688 Vim::action(editor, cx, |vim, action: &PushJump, window, cx| {
689 vim.push_operator(Operator::Jump { line: action.line }, window, cx)
690 });
691
692 Vim::action(editor, cx, |vim, action: &PushDigraph, window, cx| {
693 vim.push_operator(
694 Operator::Digraph {
695 first_char: action.first_char,
696 },
697 window,
698 cx,
699 )
700 });
701
702 Vim::action(editor, cx, |vim, action: &PushLiteral, window, cx| {
703 vim.push_operator(
704 Operator::Literal {
705 prefix: action.prefix.clone(),
706 },
707 window,
708 cx,
709 )
710 });
711
712 Vim::action(editor, cx, |vim, _: &PushChange, window, cx| {
713 vim.push_operator(Operator::Change, window, cx)
714 });
715
716 Vim::action(editor, cx, |vim, _: &PushDelete, window, cx| {
717 vim.push_operator(Operator::Delete, window, cx)
718 });
719
720 Vim::action(editor, cx, |vim, _: &PushYank, window, cx| {
721 vim.push_operator(Operator::Yank, window, cx)
722 });
723
724 Vim::action(editor, cx, |vim, _: &PushReplace, window, cx| {
725 vim.push_operator(Operator::Replace, window, cx)
726 });
727
728 Vim::action(editor, cx, |vim, _: &PushDeleteSurrounds, window, cx| {
729 vim.push_operator(Operator::DeleteSurrounds, window, cx)
730 });
731
732 Vim::action(editor, cx, |vim, _: &PushMark, window, cx| {
733 vim.push_operator(Operator::Mark, window, cx)
734 });
735
736 Vim::action(editor, cx, |vim, _: &PushIndent, window, cx| {
737 vim.push_operator(Operator::Indent, window, cx)
738 });
739
740 Vim::action(editor, cx, |vim, _: &PushOutdent, window, cx| {
741 vim.push_operator(Operator::Outdent, window, cx)
742 });
743
744 Vim::action(editor, cx, |vim, _: &PushAutoIndent, window, cx| {
745 vim.push_operator(Operator::AutoIndent, window, cx)
746 });
747
748 Vim::action(editor, cx, |vim, _: &PushRewrap, window, cx| {
749 vim.push_operator(Operator::Rewrap, window, cx)
750 });
751
752 Vim::action(editor, cx, |vim, _: &PushShellCommand, window, cx| {
753 vim.push_operator(Operator::ShellCommand, window, cx)
754 });
755
756 Vim::action(editor, cx, |vim, _: &PushLowercase, window, cx| {
757 vim.push_operator(Operator::Lowercase, window, cx)
758 });
759
760 Vim::action(editor, cx, |vim, _: &PushUppercase, window, cx| {
761 vim.push_operator(Operator::Uppercase, window, cx)
762 });
763
764 Vim::action(editor, cx, |vim, _: &PushOppositeCase, window, cx| {
765 vim.push_operator(Operator::OppositeCase, window, cx)
766 });
767
768 Vim::action(editor, cx, |vim, _: &PushRot13, window, cx| {
769 vim.push_operator(Operator::Rot13, window, cx)
770 });
771
772 Vim::action(editor, cx, |vim, _: &PushRot47, window, cx| {
773 vim.push_operator(Operator::Rot47, window, cx)
774 });
775
776 Vim::action(editor, cx, |vim, _: &PushRegister, window, cx| {
777 vim.push_operator(Operator::Register, window, cx)
778 });
779
780 Vim::action(editor, cx, |vim, _: &PushRecordRegister, window, cx| {
781 vim.push_operator(Operator::RecordRegister, window, cx)
782 });
783
784 Vim::action(editor, cx, |vim, _: &PushReplayRegister, window, cx| {
785 vim.push_operator(Operator::ReplayRegister, window, cx)
786 });
787
788 Vim::action(
789 editor,
790 cx,
791 |vim, _: &PushReplaceWithRegister, window, cx| {
792 vim.push_operator(Operator::ReplaceWithRegister, window, cx)
793 },
794 );
795
796 Vim::action(editor, cx, |vim, _: &Exchange, window, cx| {
797 if vim.mode.is_visual() {
798 vim.exchange_visual(window, cx)
799 } else {
800 vim.push_operator(Operator::Exchange, window, cx)
801 }
802 });
803
804 Vim::action(editor, cx, |vim, _: &ClearExchange, window, cx| {
805 vim.clear_exchange(window, cx)
806 });
807
808 Vim::action(editor, cx, |vim, _: &PushToggleComments, window, cx| {
809 vim.push_operator(Operator::ToggleComments, window, cx)
810 });
811
812 Vim::action(editor, cx, |vim, _: &ClearOperators, window, cx| {
813 vim.clear_operator(window, cx)
814 });
815 Vim::action(editor, cx, |vim, n: &Number, window, cx| {
816 vim.push_count_digit(n.0, window, cx);
817 });
818 Vim::action(editor, cx, |vim, _: &Tab, window, cx| {
819 vim.input_ignored(" ".into(), window, cx)
820 });
821 Vim::action(
822 editor,
823 cx,
824 |vim, action: &editor::actions::AcceptEditPrediction, window, cx| {
825 vim.update_editor(cx, |_, editor, cx| {
826 editor.accept_edit_prediction(action, window, cx);
827 });
828 // In non-insertion modes, predictions will be hidden and instead a jump will be
829 // displayed (and performed by `accept_edit_prediction`). This switches to
830 // insert mode so that the prediction is displayed after the jump.
831 match vim.mode {
832 Mode::Replace => {}
833 _ => vim.switch_mode(Mode::Insert, true, window, cx),
834 };
835 },
836 );
837 Vim::action(editor, cx, |vim, _: &Enter, window, cx| {
838 vim.input_ignored("\n".into(), window, cx)
839 });
840 Vim::action(editor, cx, |vim, _: &PushHelixMatch, window, cx| {
841 vim.push_operator(Operator::HelixMatch, window, cx)
842 });
843 Vim::action(editor, cx, |vim, action: &PushHelixNext, window, cx| {
844 vim.push_operator(
845 Operator::HelixNext {
846 around: action.around,
847 },
848 window,
849 cx,
850 );
851 });
852 Vim::action(editor, cx, |vim, action: &PushHelixPrevious, window, cx| {
853 vim.push_operator(
854 Operator::HelixPrevious {
855 around: action.around,
856 },
857 window,
858 cx,
859 );
860 });
861
862 normal::register(editor, cx);
863 insert::register(editor, cx);
864 helix::register(editor, cx);
865 motion::register(editor, cx);
866 command::register(editor, cx);
867 replace::register(editor, cx);
868 indent::register(editor, cx);
869 rewrap::register(editor, cx);
870 object::register(editor, cx);
871 visual::register(editor, cx);
872 change_list::register(editor, cx);
873 digraph::register(editor, cx);
874
875 cx.defer_in(window, |vim, window, cx| {
876 vim.focused(false, window, cx);
877 })
878 })
879 }
880
881 fn deactivate(editor: &mut Editor, cx: &mut Context<Editor>) {
882 editor.set_cursor_shape(CursorShape::Bar, cx);
883 editor.set_clip_at_line_ends(false, cx);
884 editor.set_collapse_matches(false);
885 editor.set_input_enabled(true);
886 editor.set_autoindent(true);
887 editor.selections.set_line_mode(false);
888 editor.unregister_addon::<VimAddon>();
889 editor.set_relative_line_number(None, cx);
890 if let Some(vim) = Vim::globals(cx).focused_vim()
891 && vim.entity_id() == cx.entity().entity_id()
892 {
893 Vim::globals(cx).focused_vim = None;
894 }
895 }
896
897 /// Register an action on the editor.
898 pub fn action<A: Action>(
899 editor: &mut Editor,
900 cx: &mut Context<Vim>,
901 f: impl Fn(&mut Vim, &A, &mut Window, &mut Context<Vim>) + 'static,
902 ) {
903 let subscription = editor.register_action(cx.listener(f));
904 cx.on_release(|_, _| drop(subscription)).detach();
905 }
906
907 pub fn editor(&self) -> Option<Entity<Editor>> {
908 self.editor.upgrade()
909 }
910
911 pub fn workspace(&self, window: &mut Window) -> Option<Entity<Workspace>> {
912 window.root::<Workspace>().flatten()
913 }
914
915 pub fn pane(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Entity<Pane>> {
916 self.workspace(window)
917 .map(|workspace| workspace.read(cx).focused_pane(window, cx))
918 }
919
920 pub fn enabled(cx: &mut App) -> bool {
921 VimModeSetting::get_global(cx).0 || HelixModeSetting::get_global(cx).0
922 }
923
924 /// Called whenever an keystroke is typed so vim can observe all actions
925 /// and keystrokes accordingly.
926 fn observe_keystrokes(
927 &mut self,
928 keystroke_event: &KeystrokeEvent,
929 window: &mut Window,
930 cx: &mut Context<Self>,
931 ) {
932 if self.exit_temporary_mode {
933 self.exit_temporary_mode = false;
934 // Don't switch to insert mode if the action is temporary_normal.
935 if let Some(action) = keystroke_event.action.as_ref()
936 && action.as_any().downcast_ref::<TemporaryNormal>().is_some()
937 {
938 return;
939 }
940 self.switch_mode(Mode::Insert, false, window, cx)
941 }
942 if let Some(action) = keystroke_event.action.as_ref() {
943 // Keystroke is handled by the vim system, so continue forward
944 if action.name().starts_with("vim::") {
945 self.update_editor(cx, |_, editor, cx| {
946 editor.hide_mouse_cursor(HideMouseCursorOrigin::MovementAction, cx)
947 });
948 return;
949 }
950 } else if window.has_pending_keystrokes() || keystroke_event.keystroke.is_ime_in_progress()
951 {
952 return;
953 }
954
955 if let Some(operator) = self.active_operator() {
956 match operator {
957 Operator::Literal { prefix } => {
958 self.handle_literal_keystroke(
959 keystroke_event,
960 prefix.unwrap_or_default(),
961 window,
962 cx,
963 );
964 }
965 _ if !operator.is_waiting(self.mode) => {
966 self.clear_operator(window, cx);
967 self.stop_recording_immediately(Box::new(ClearOperators), cx)
968 }
969 _ => {}
970 }
971 }
972 }
973
974 fn handle_editor_event(
975 &mut self,
976 event: &EditorEvent,
977 window: &mut Window,
978 cx: &mut Context<Self>,
979 ) {
980 match event {
981 EditorEvent::Focused => self.focused(true, window, cx),
982 EditorEvent::Blurred => self.blurred(window, cx),
983 EditorEvent::SelectionsChanged { local: true } => {
984 self.local_selections_changed(window, cx);
985 }
986 EditorEvent::InputIgnored { text } => {
987 self.input_ignored(text.clone(), window, cx);
988 Vim::globals(cx).observe_insertion(text, None)
989 }
990 EditorEvent::InputHandled {
991 text,
992 utf16_range_to_replace: range_to_replace,
993 } => Vim::globals(cx).observe_insertion(text, range_to_replace.clone()),
994 EditorEvent::TransactionBegun { transaction_id } => {
995 self.transaction_begun(*transaction_id, window, cx)
996 }
997 EditorEvent::TransactionUndone { transaction_id } => {
998 self.transaction_undone(transaction_id, window, cx)
999 }
1000 EditorEvent::Edited { .. } => self.push_to_change_list(window, cx),
1001 EditorEvent::FocusedIn => self.sync_vim_settings(window, cx),
1002 EditorEvent::CursorShapeChanged => self.cursor_shape_changed(window, cx),
1003 EditorEvent::PushedToNavHistory {
1004 anchor,
1005 is_deactivate,
1006 } => {
1007 self.update_editor(cx, |vim, editor, cx| {
1008 let mark = if *is_deactivate {
1009 "\"".to_string()
1010 } else {
1011 "'".to_string()
1012 };
1013 vim.set_mark(mark, vec![*anchor], editor.buffer(), window, cx);
1014 });
1015 }
1016 _ => {}
1017 }
1018 }
1019
1020 fn push_operator(&mut self, operator: Operator, window: &mut Window, cx: &mut Context<Self>) {
1021 if operator.starts_dot_recording() {
1022 self.start_recording(cx);
1023 }
1024 // Since these operations can only be entered with pre-operators,
1025 // we need to clear the previous operators when pushing,
1026 // so that the current stack is the most correct
1027 if matches!(
1028 operator,
1029 Operator::AddSurrounds { .. }
1030 | Operator::ChangeSurrounds { .. }
1031 | Operator::DeleteSurrounds
1032 | Operator::Exchange
1033 ) {
1034 self.operator_stack.clear();
1035 };
1036 self.operator_stack.push(operator);
1037 self.sync_vim_settings(window, cx);
1038 }
1039
1040 pub fn switch_mode(
1041 &mut self,
1042 mode: Mode,
1043 leave_selections: bool,
1044 window: &mut Window,
1045 cx: &mut Context<Self>,
1046 ) {
1047 if self.temp_mode && mode == Mode::Normal {
1048 self.temp_mode = false;
1049 self.switch_mode(Mode::Normal, leave_selections, window, cx);
1050 self.switch_mode(Mode::Insert, false, window, cx);
1051 return;
1052 } else if self.temp_mode
1053 && !matches!(mode, Mode::Visual | Mode::VisualLine | Mode::VisualBlock)
1054 {
1055 self.temp_mode = false;
1056 }
1057
1058 let last_mode = self.mode;
1059 let prior_mode = self.last_mode;
1060 let prior_tx = self.current_tx;
1061 self.status_label.take();
1062 self.last_mode = last_mode;
1063 self.mode = mode;
1064 self.operator_stack.clear();
1065 self.selected_register.take();
1066 self.cancel_running_command(window, cx);
1067 if mode == Mode::Normal || mode != last_mode {
1068 self.current_tx.take();
1069 self.current_anchor.take();
1070 self.update_editor(cx, |_, editor, _| {
1071 editor.clear_selection_drag_state();
1072 });
1073 }
1074 Vim::take_forced_motion(cx);
1075 if mode != Mode::Insert && mode != Mode::Replace {
1076 Vim::take_count(cx);
1077 }
1078
1079 // Sync editor settings like clip mode
1080 self.sync_vim_settings(window, cx);
1081
1082 if VimSettings::get_global(cx).toggle_relative_line_numbers
1083 && self.mode != self.last_mode
1084 && (self.mode == Mode::Insert || self.last_mode == Mode::Insert)
1085 {
1086 self.update_editor(cx, |vim, editor, cx| {
1087 let is_relative = vim.mode != Mode::Insert;
1088 editor.set_relative_line_number(Some(is_relative), cx)
1089 });
1090 }
1091 if HelixModeSetting::get_global(cx).0 {
1092 if self.mode == Mode::Normal {
1093 self.mode = Mode::HelixNormal
1094 } else if self.mode == Mode::Visual {
1095 self.mode = Mode::HelixSelect
1096 }
1097 }
1098
1099 if leave_selections {
1100 return;
1101 }
1102
1103 if !mode.is_visual() && last_mode.is_visual() {
1104 self.create_visual_marks(last_mode, window, cx);
1105 }
1106
1107 // Adjust selections
1108 self.update_editor(cx, |vim, editor, cx| {
1109 if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
1110 {
1111 vim.visual_block_motion(true, editor, window, cx, |_, point, goal| {
1112 Some((point, goal))
1113 })
1114 }
1115 if (last_mode == Mode::Insert || last_mode == Mode::Replace)
1116 && let Some(prior_tx) = prior_tx
1117 {
1118 editor.group_until_transaction(prior_tx, cx)
1119 }
1120
1121 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1122 // we cheat with visual block mode and use multiple cursors.
1123 // the cost of this cheat is we need to convert back to a single
1124 // cursor whenever vim would.
1125 if last_mode == Mode::VisualBlock
1126 && (mode != Mode::VisualBlock && mode != Mode::Insert)
1127 {
1128 let tail = s.oldest_anchor().tail();
1129 let head = s.newest_anchor().head();
1130 s.select_anchor_ranges(vec![tail..head]);
1131 } else if last_mode == Mode::Insert
1132 && prior_mode == Mode::VisualBlock
1133 && mode != Mode::VisualBlock
1134 {
1135 let pos = s.first_anchor().head();
1136 s.select_anchor_ranges(vec![pos..pos])
1137 }
1138
1139 let snapshot = s.display_map();
1140 if let Some(pending) = s.pending_anchor_mut()
1141 && pending.reversed
1142 && mode.is_visual()
1143 && !last_mode.is_visual()
1144 {
1145 let mut end = pending.end.to_point(&snapshot.buffer_snapshot());
1146 end = snapshot
1147 .buffer_snapshot()
1148 .clip_point(end + Point::new(0, 1), Bias::Right);
1149 pending.end = snapshot.buffer_snapshot().anchor_before(end);
1150 }
1151
1152 s.move_with(|map, selection| {
1153 if last_mode.is_visual() && !mode.is_visual() {
1154 let mut point = selection.head();
1155 if !selection.reversed && !selection.is_empty() {
1156 point = movement::left(map, selection.head());
1157 } else if selection.is_empty() {
1158 point = map.clip_point(point, Bias::Left);
1159 }
1160 selection.collapse_to(point, selection.goal)
1161 } else if !last_mode.is_visual() && mode.is_visual() && selection.is_empty() {
1162 selection.end = movement::right(map, selection.start);
1163 }
1164 });
1165 })
1166 });
1167 }
1168
1169 pub fn take_count(cx: &mut App) -> Option<usize> {
1170 let global_state = cx.global_mut::<VimGlobals>();
1171 if global_state.dot_replaying {
1172 return global_state.recorded_count;
1173 }
1174
1175 let count = if global_state.post_count.is_none() && global_state.pre_count.is_none() {
1176 return None;
1177 } else {
1178 Some(
1179 global_state.post_count.take().unwrap_or(1)
1180 * global_state.pre_count.take().unwrap_or(1),
1181 )
1182 };
1183
1184 if global_state.dot_recording {
1185 global_state.recorded_count = count;
1186 }
1187 count
1188 }
1189
1190 pub fn take_forced_motion(cx: &mut App) -> bool {
1191 let global_state = cx.global_mut::<VimGlobals>();
1192 let forced_motion = global_state.forced_motion;
1193 global_state.forced_motion = false;
1194 forced_motion
1195 }
1196
1197 pub fn cursor_shape(&self, cx: &mut App) -> CursorShape {
1198 let cursor_shape = VimSettings::get_global(cx).cursor_shape;
1199 match self.mode {
1200 Mode::Normal => {
1201 if let Some(operator) = self.operator_stack.last() {
1202 match operator {
1203 // Navigation operators -> Block cursor
1204 Operator::FindForward { .. }
1205 | Operator::FindBackward { .. }
1206 | Operator::Mark
1207 | Operator::Jump { .. }
1208 | Operator::Register
1209 | Operator::RecordRegister
1210 | Operator::ReplayRegister => CursorShape::Block,
1211
1212 // All other operators -> Underline cursor
1213 _ => CursorShape::Underline,
1214 }
1215 } else {
1216 cursor_shape.normal.unwrap_or(CursorShape::Block)
1217 }
1218 }
1219 Mode::HelixNormal => cursor_shape.normal.unwrap_or(CursorShape::Block),
1220 Mode::Replace => cursor_shape.replace.unwrap_or(CursorShape::Underline),
1221 Mode::Visual | Mode::VisualLine | Mode::VisualBlock | Mode::HelixSelect => {
1222 cursor_shape.visual.unwrap_or(CursorShape::Block)
1223 }
1224 Mode::Insert => cursor_shape.insert.unwrap_or({
1225 let editor_settings = EditorSettings::get_global(cx);
1226 editor_settings.cursor_shape.unwrap_or_default()
1227 }),
1228 }
1229 }
1230
1231 pub fn editor_input_enabled(&self) -> bool {
1232 match self.mode {
1233 Mode::Insert => {
1234 if let Some(operator) = self.operator_stack.last() {
1235 !operator.is_waiting(self.mode)
1236 } else {
1237 true
1238 }
1239 }
1240 Mode::Normal
1241 | Mode::HelixNormal
1242 | Mode::Replace
1243 | Mode::Visual
1244 | Mode::VisualLine
1245 | Mode::VisualBlock
1246 | Mode::HelixSelect => false,
1247 }
1248 }
1249
1250 pub fn should_autoindent(&self) -> bool {
1251 !(self.mode == Mode::Insert && self.last_mode == Mode::VisualBlock)
1252 }
1253
1254 pub fn clip_at_line_ends(&self) -> bool {
1255 match self.mode {
1256 Mode::Insert
1257 | Mode::Visual
1258 | Mode::VisualLine
1259 | Mode::VisualBlock
1260 | Mode::Replace
1261 | Mode::HelixNormal
1262 | Mode::HelixSelect => false,
1263 Mode::Normal => true,
1264 }
1265 }
1266
1267 pub fn extend_key_context(&self, context: &mut KeyContext, cx: &App) {
1268 let mut mode = match self.mode {
1269 Mode::Normal => "normal",
1270 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => "visual",
1271 Mode::Insert => "insert",
1272 Mode::Replace => "replace",
1273 Mode::HelixNormal => "helix_normal",
1274 Mode::HelixSelect => "helix_select",
1275 }
1276 .to_string();
1277
1278 let mut operator_id = "none";
1279
1280 let active_operator = self.active_operator();
1281 if active_operator.is_none() && cx.global::<VimGlobals>().pre_count.is_some()
1282 || active_operator.is_some() && cx.global::<VimGlobals>().post_count.is_some()
1283 {
1284 context.add("VimCount");
1285 }
1286
1287 if let Some(active_operator) = active_operator {
1288 if active_operator.is_waiting(self.mode) {
1289 if matches!(active_operator, Operator::Literal { .. }) {
1290 mode = "literal".to_string();
1291 } else {
1292 mode = "waiting".to_string();
1293 }
1294 } else {
1295 operator_id = active_operator.id();
1296 mode = "operator".to_string();
1297 }
1298 }
1299
1300 if mode == "normal"
1301 || mode == "visual"
1302 || mode == "operator"
1303 || mode == "helix_normal"
1304 || mode == "helix_select"
1305 {
1306 context.add("VimControl");
1307 }
1308 context.set("vim_mode", mode);
1309 context.set("vim_operator", operator_id);
1310 }
1311
1312 fn focused(&mut self, preserve_selection: bool, window: &mut Window, cx: &mut Context<Self>) {
1313 let Some(editor) = self.editor() else {
1314 return;
1315 };
1316 let newest_selection_empty = editor.update(cx, |editor, cx| {
1317 editor.selections.newest::<usize>(cx).is_empty()
1318 });
1319 let editor = editor.read(cx);
1320 let editor_mode = editor.mode();
1321
1322 if editor_mode.is_full()
1323 && !newest_selection_empty
1324 && self.mode == Mode::Normal
1325 // When following someone, don't switch vim mode.
1326 && editor.leader_id().is_none()
1327 {
1328 if preserve_selection {
1329 self.switch_mode(Mode::Visual, true, window, cx);
1330 } else {
1331 self.update_editor(cx, |_, editor, cx| {
1332 editor.set_clip_at_line_ends(false, cx);
1333 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1334 s.move_with(|_, selection| {
1335 selection.collapse_to(selection.start, selection.goal)
1336 })
1337 });
1338 });
1339 }
1340 }
1341
1342 cx.emit(VimEvent::Focused);
1343 self.sync_vim_settings(window, cx);
1344
1345 if VimSettings::get_global(cx).toggle_relative_line_numbers {
1346 if let Some(old_vim) = Vim::globals(cx).focused_vim() {
1347 if old_vim.entity_id() != cx.entity().entity_id() {
1348 old_vim.update(cx, |vim, cx| {
1349 vim.update_editor(cx, |_, editor, cx| {
1350 editor.set_relative_line_number(None, cx)
1351 });
1352 });
1353
1354 self.update_editor(cx, |vim, editor, cx| {
1355 let is_relative = vim.mode != Mode::Insert;
1356 editor.set_relative_line_number(Some(is_relative), cx)
1357 });
1358 }
1359 } else {
1360 self.update_editor(cx, |vim, editor, cx| {
1361 let is_relative = vim.mode != Mode::Insert;
1362 editor.set_relative_line_number(Some(is_relative), cx)
1363 });
1364 }
1365 }
1366 Vim::globals(cx).focused_vim = Some(cx.entity().downgrade());
1367 }
1368
1369 fn blurred(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1370 self.stop_recording_immediately(NormalBefore.boxed_clone(), cx);
1371 self.store_visual_marks(window, cx);
1372 self.clear_operator(window, cx);
1373 self.update_editor(cx, |vim, editor, cx| {
1374 if vim.cursor_shape(cx) == CursorShape::Block {
1375 editor.set_cursor_shape(CursorShape::Hollow, cx);
1376 }
1377 });
1378 }
1379
1380 fn cursor_shape_changed(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1381 self.update_editor(cx, |vim, editor, cx| {
1382 editor.set_cursor_shape(vim.cursor_shape(cx), cx);
1383 });
1384 }
1385
1386 fn update_editor<S>(
1387 &mut self,
1388 cx: &mut Context<Self>,
1389 update: impl FnOnce(&mut Self, &mut Editor, &mut Context<Editor>) -> S,
1390 ) -> Option<S> {
1391 let editor = self.editor.upgrade()?;
1392 Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
1393 }
1394
1395 fn editor_selections(&mut self, _: &mut Window, cx: &mut Context<Self>) -> Vec<Range<Anchor>> {
1396 self.update_editor(cx, |_, editor, _| {
1397 editor
1398 .selections
1399 .disjoint_anchors_arc()
1400 .iter()
1401 .map(|selection| selection.tail()..selection.head())
1402 .collect()
1403 })
1404 .unwrap_or_default()
1405 }
1406
1407 fn editor_cursor_word(
1408 &mut self,
1409 window: &mut Window,
1410 cx: &mut Context<Self>,
1411 ) -> Option<String> {
1412 self.update_editor(cx, |_, editor, cx| {
1413 let selection = editor.selections.newest::<usize>(cx);
1414
1415 let snapshot = editor.snapshot(window, cx);
1416 let snapshot = snapshot.buffer_snapshot();
1417 let (range, kind) =
1418 snapshot.surrounding_word(selection.start, Some(CharScopeContext::Completion));
1419 if kind == Some(CharKind::Word) {
1420 let text: String = snapshot.text_for_range(range).collect();
1421 if !text.trim().is_empty() {
1422 return Some(text);
1423 }
1424 }
1425
1426 None
1427 })
1428 .unwrap_or_default()
1429 }
1430
1431 /// When doing an action that modifies the buffer, we start recording so that `.`
1432 /// will replay the action.
1433 pub fn start_recording(&mut self, cx: &mut Context<Self>) {
1434 Vim::update_globals(cx, |globals, cx| {
1435 if !globals.dot_replaying {
1436 globals.dot_recording = true;
1437 globals.recording_actions = Default::default();
1438 globals.recorded_count = None;
1439
1440 let selections = self.editor().map(|editor| {
1441 editor.update(cx, |editor, cx| {
1442 (
1443 editor.selections.oldest::<Point>(cx),
1444 editor.selections.newest::<Point>(cx),
1445 )
1446 })
1447 });
1448
1449 if let Some((oldest, newest)) = selections {
1450 globals.recorded_selection = match self.mode {
1451 Mode::Visual if newest.end.row == newest.start.row => {
1452 RecordedSelection::SingleLine {
1453 cols: newest.end.column - newest.start.column,
1454 }
1455 }
1456 Mode::Visual => RecordedSelection::Visual {
1457 rows: newest.end.row - newest.start.row,
1458 cols: newest.end.column,
1459 },
1460 Mode::VisualLine => RecordedSelection::VisualLine {
1461 rows: newest.end.row - newest.start.row,
1462 },
1463 Mode::VisualBlock => RecordedSelection::VisualBlock {
1464 rows: newest.end.row.abs_diff(oldest.start.row),
1465 cols: newest.end.column.abs_diff(oldest.start.column),
1466 },
1467 _ => RecordedSelection::None,
1468 }
1469 } else {
1470 globals.recorded_selection = RecordedSelection::None;
1471 }
1472 }
1473 })
1474 }
1475
1476 pub fn stop_replaying(&mut self, cx: &mut Context<Self>) {
1477 let globals = Vim::globals(cx);
1478 globals.dot_replaying = false;
1479 if let Some(replayer) = globals.replayer.take() {
1480 replayer.stop();
1481 }
1482 }
1483
1484 /// When finishing an action that modifies the buffer, stop recording.
1485 /// as you usually call this within a keystroke handler we also ensure that
1486 /// the current action is recorded.
1487 pub fn stop_recording(&mut self, cx: &mut Context<Self>) {
1488 let globals = Vim::globals(cx);
1489 if globals.dot_recording {
1490 globals.stop_recording_after_next_action = true;
1491 }
1492 self.exit_temporary_mode = self.temp_mode;
1493 }
1494
1495 /// Stops recording actions immediately rather than waiting until after the
1496 /// next action to stop recording.
1497 ///
1498 /// This doesn't include the current action.
1499 pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>, cx: &mut Context<Self>) {
1500 let globals = Vim::globals(cx);
1501 if globals.dot_recording {
1502 globals
1503 .recording_actions
1504 .push(ReplayableAction::Action(action.boxed_clone()));
1505 globals.recorded_actions = mem::take(&mut globals.recording_actions);
1506 globals.dot_recording = false;
1507 globals.stop_recording_after_next_action = false;
1508 }
1509 self.exit_temporary_mode = self.temp_mode;
1510 }
1511
1512 /// Explicitly record one action (equivalents to start_recording and stop_recording)
1513 pub fn record_current_action(&mut self, cx: &mut Context<Self>) {
1514 self.start_recording(cx);
1515 self.stop_recording(cx);
1516 }
1517
1518 fn push_count_digit(&mut self, number: usize, window: &mut Window, cx: &mut Context<Self>) {
1519 if self.active_operator().is_some() {
1520 let post_count = Vim::globals(cx).post_count.unwrap_or(0);
1521
1522 Vim::globals(cx).post_count = Some(
1523 post_count
1524 .checked_mul(10)
1525 .and_then(|post_count| post_count.checked_add(number))
1526 .unwrap_or(post_count),
1527 )
1528 } else {
1529 let pre_count = Vim::globals(cx).pre_count.unwrap_or(0);
1530
1531 Vim::globals(cx).pre_count = Some(
1532 pre_count
1533 .checked_mul(10)
1534 .and_then(|pre_count| pre_count.checked_add(number))
1535 .unwrap_or(pre_count),
1536 )
1537 }
1538 // update the keymap so that 0 works
1539 self.sync_vim_settings(window, cx)
1540 }
1541
1542 fn select_register(&mut self, register: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
1543 if register.chars().count() == 1 {
1544 self.selected_register
1545 .replace(register.chars().next().unwrap());
1546 }
1547 self.operator_stack.clear();
1548 self.sync_vim_settings(window, cx);
1549 }
1550
1551 fn maybe_pop_operator(&mut self) -> Option<Operator> {
1552 self.operator_stack.pop()
1553 }
1554
1555 fn pop_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Operator {
1556 let popped_operator = self.operator_stack.pop()
1557 .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
1558 self.sync_vim_settings(window, cx);
1559 popped_operator
1560 }
1561
1562 fn clear_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1563 Vim::take_count(cx);
1564 Vim::take_forced_motion(cx);
1565 self.selected_register.take();
1566 self.operator_stack.clear();
1567 self.sync_vim_settings(window, cx);
1568 }
1569
1570 fn active_operator(&self) -> Option<Operator> {
1571 self.operator_stack.last().cloned()
1572 }
1573
1574 fn transaction_begun(
1575 &mut self,
1576 transaction_id: TransactionId,
1577 _window: &mut Window,
1578 _: &mut Context<Self>,
1579 ) {
1580 let mode = if (self.mode == Mode::Insert
1581 || self.mode == Mode::Replace
1582 || self.mode == Mode::Normal)
1583 && self.current_tx.is_none()
1584 {
1585 self.current_tx = Some(transaction_id);
1586 self.last_mode
1587 } else {
1588 self.mode
1589 };
1590 if mode == Mode::VisualLine || mode == Mode::VisualBlock {
1591 self.undo_modes.insert(transaction_id, mode);
1592 }
1593 }
1594
1595 fn transaction_undone(
1596 &mut self,
1597 transaction_id: &TransactionId,
1598 window: &mut Window,
1599 cx: &mut Context<Self>,
1600 ) {
1601 match self.mode {
1602 Mode::VisualLine | Mode::VisualBlock | Mode::Visual | Mode::HelixSelect => {
1603 self.update_editor(cx, |vim, editor, cx| {
1604 let original_mode = vim.undo_modes.get(transaction_id);
1605 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1606 match original_mode {
1607 Some(Mode::VisualLine) => {
1608 s.move_with(|map, selection| {
1609 selection.collapse_to(
1610 map.prev_line_boundary(selection.start.to_point(map)).1,
1611 SelectionGoal::None,
1612 )
1613 });
1614 }
1615 Some(Mode::VisualBlock) => {
1616 let mut first = s.first_anchor();
1617 first.collapse_to(first.start, first.goal);
1618 s.select_anchors(vec![first]);
1619 }
1620 _ => {
1621 s.move_with(|map, selection| {
1622 selection.collapse_to(
1623 map.clip_at_line_end(selection.start),
1624 selection.goal,
1625 );
1626 });
1627 }
1628 }
1629 });
1630 });
1631 self.switch_mode(Mode::Normal, true, window, cx)
1632 }
1633 Mode::Normal => {
1634 self.update_editor(cx, |_, editor, cx| {
1635 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1636 s.move_with(|map, selection| {
1637 selection
1638 .collapse_to(map.clip_at_line_end(selection.end), selection.goal)
1639 })
1640 })
1641 });
1642 }
1643 Mode::Insert | Mode::Replace | Mode::HelixNormal => {}
1644 }
1645 }
1646
1647 fn local_selections_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1648 let Some(editor) = self.editor() else { return };
1649
1650 if editor.read(cx).leader_id().is_some() {
1651 return;
1652 }
1653
1654 let newest = editor.read(cx).selections.newest_anchor().clone();
1655 let is_multicursor = editor.read(cx).selections.count() > 1;
1656 if self.mode == Mode::Insert && self.current_tx.is_some() {
1657 if self.current_anchor.is_none() {
1658 self.current_anchor = Some(newest);
1659 } else if self.current_anchor.as_ref().unwrap() != &newest
1660 && let Some(tx_id) = self.current_tx.take()
1661 {
1662 self.update_editor(cx, |_, editor, cx| {
1663 editor.group_until_transaction(tx_id, cx)
1664 });
1665 }
1666 } else if self.mode == Mode::Normal && newest.start != newest.end {
1667 if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
1668 self.switch_mode(Mode::VisualBlock, false, window, cx);
1669 } else {
1670 self.switch_mode(Mode::Visual, false, window, cx)
1671 }
1672 } else if newest.start == newest.end
1673 && !is_multicursor
1674 && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&self.mode)
1675 {
1676 self.switch_mode(Mode::Normal, false, window, cx);
1677 }
1678 }
1679
1680 fn input_ignored(&mut self, text: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
1681 if text.is_empty() {
1682 return;
1683 }
1684
1685 match self.active_operator() {
1686 Some(Operator::FindForward { before, multiline }) => {
1687 let find = Motion::FindForward {
1688 before,
1689 char: text.chars().next().unwrap(),
1690 mode: if multiline {
1691 FindRange::MultiLine
1692 } else {
1693 FindRange::SingleLine
1694 },
1695 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1696 };
1697 Vim::globals(cx).last_find = Some(find.clone());
1698 self.motion(find, window, cx)
1699 }
1700 Some(Operator::FindBackward { after, multiline }) => {
1701 let find = Motion::FindBackward {
1702 after,
1703 char: text.chars().next().unwrap(),
1704 mode: if multiline {
1705 FindRange::MultiLine
1706 } else {
1707 FindRange::SingleLine
1708 },
1709 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1710 };
1711 Vim::globals(cx).last_find = Some(find.clone());
1712 self.motion(find, window, cx)
1713 }
1714 Some(Operator::Sneak { first_char }) => {
1715 if let Some(first_char) = first_char {
1716 if let Some(second_char) = text.chars().next() {
1717 let sneak = Motion::Sneak {
1718 first_char,
1719 second_char,
1720 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1721 };
1722 Vim::globals(cx).last_find = Some(sneak.clone());
1723 self.motion(sneak, window, cx)
1724 }
1725 } else {
1726 let first_char = text.chars().next();
1727 self.pop_operator(window, cx);
1728 self.push_operator(Operator::Sneak { first_char }, window, cx);
1729 }
1730 }
1731 Some(Operator::SneakBackward { first_char }) => {
1732 if let Some(first_char) = first_char {
1733 if let Some(second_char) = text.chars().next() {
1734 let sneak = Motion::SneakBackward {
1735 first_char,
1736 second_char,
1737 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1738 };
1739 Vim::globals(cx).last_find = Some(sneak.clone());
1740 self.motion(sneak, window, cx)
1741 }
1742 } else {
1743 let first_char = text.chars().next();
1744 self.pop_operator(window, cx);
1745 self.push_operator(Operator::SneakBackward { first_char }, window, cx);
1746 }
1747 }
1748 Some(Operator::Replace) => match self.mode {
1749 Mode::Normal => self.normal_replace(text, window, cx),
1750 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1751 self.visual_replace(text, window, cx)
1752 }
1753 Mode::HelixNormal => self.helix_replace(&text, window, cx),
1754 _ => self.clear_operator(window, cx),
1755 },
1756 Some(Operator::Digraph { first_char }) => {
1757 if let Some(first_char) = first_char {
1758 if let Some(second_char) = text.chars().next() {
1759 self.insert_digraph(first_char, second_char, window, cx);
1760 }
1761 } else {
1762 let first_char = text.chars().next();
1763 self.pop_operator(window, cx);
1764 self.push_operator(Operator::Digraph { first_char }, window, cx);
1765 }
1766 }
1767 Some(Operator::Literal { prefix }) => {
1768 self.handle_literal_input(prefix.unwrap_or_default(), &text, window, cx)
1769 }
1770 Some(Operator::AddSurrounds { target }) => match self.mode {
1771 Mode::Normal => {
1772 if let Some(target) = target {
1773 self.add_surrounds(text, target, window, cx);
1774 self.clear_operator(window, cx);
1775 }
1776 }
1777 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1778 self.add_surrounds(text, SurroundsType::Selection, window, cx);
1779 self.clear_operator(window, cx);
1780 }
1781 _ => self.clear_operator(window, cx),
1782 },
1783 Some(Operator::ChangeSurrounds { target }) => match self.mode {
1784 Mode::Normal => {
1785 if let Some(target) = target {
1786 self.change_surrounds(text, target, window, cx);
1787 self.clear_operator(window, cx);
1788 }
1789 }
1790 _ => self.clear_operator(window, cx),
1791 },
1792 Some(Operator::DeleteSurrounds) => match self.mode {
1793 Mode::Normal => {
1794 self.delete_surrounds(text, window, cx);
1795 self.clear_operator(window, cx);
1796 }
1797 _ => self.clear_operator(window, cx),
1798 },
1799 Some(Operator::Mark) => self.create_mark(text, window, cx),
1800 Some(Operator::RecordRegister) => {
1801 self.record_register(text.chars().next().unwrap(), window, cx)
1802 }
1803 Some(Operator::ReplayRegister) => {
1804 self.replay_register(text.chars().next().unwrap(), window, cx)
1805 }
1806 Some(Operator::Register) => match self.mode {
1807 Mode::Insert => {
1808 self.update_editor(cx, |_, editor, cx| {
1809 if let Some(register) = Vim::update_globals(cx, |globals, cx| {
1810 globals.read_register(text.chars().next(), Some(editor), cx)
1811 }) {
1812 editor.do_paste(
1813 ®ister.text.to_string(),
1814 register.clipboard_selections,
1815 false,
1816 window,
1817 cx,
1818 )
1819 }
1820 });
1821 self.clear_operator(window, cx);
1822 }
1823 _ => {
1824 self.select_register(text, window, cx);
1825 }
1826 },
1827 Some(Operator::Jump { line }) => self.jump(text, line, true, window, cx),
1828 _ => {
1829 if self.mode == Mode::Replace {
1830 self.multi_replace(text, window, cx)
1831 }
1832
1833 if self.mode == Mode::Normal {
1834 self.update_editor(cx, |_, editor, cx| {
1835 editor.accept_edit_prediction(
1836 &editor::actions::AcceptEditPrediction {},
1837 window,
1838 cx,
1839 );
1840 });
1841 }
1842 }
1843 }
1844 }
1845
1846 fn sync_vim_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1847 self.update_editor(cx, |vim, editor, cx| {
1848 editor.set_cursor_shape(vim.cursor_shape(cx), cx);
1849 editor.set_clip_at_line_ends(vim.clip_at_line_ends(), cx);
1850 editor.set_collapse_matches(true);
1851 editor.set_input_enabled(vim.editor_input_enabled());
1852 editor.set_autoindent(vim.should_autoindent());
1853 editor
1854 .selections
1855 .set_line_mode(matches!(vim.mode, Mode::VisualLine));
1856
1857 let hide_edit_predictions = !matches!(vim.mode, Mode::Insert | Mode::Replace);
1858 editor.set_edit_predictions_hidden_for_vim_mode(hide_edit_predictions, window, cx);
1859 });
1860 cx.notify()
1861 }
1862}
1863
1864struct VimSettings {
1865 pub default_mode: Mode,
1866 pub toggle_relative_line_numbers: bool,
1867 pub use_system_clipboard: settings::UseSystemClipboard,
1868 pub use_smartcase_find: bool,
1869 pub custom_digraphs: HashMap<String, Arc<str>>,
1870 pub highlight_on_yank_duration: u64,
1871 pub cursor_shape: CursorShapeSettings,
1872}
1873
1874/// The settings for cursor shape.
1875#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1876pub struct CursorShapeSettings {
1877 /// Cursor shape for the normal mode.
1878 ///
1879 /// Default: block
1880 pub normal: Option<CursorShape>,
1881 /// Cursor shape for the replace mode.
1882 ///
1883 /// Default: underline
1884 pub replace: Option<CursorShape>,
1885 /// Cursor shape for the visual mode.
1886 ///
1887 /// Default: block
1888 pub visual: Option<CursorShape>,
1889 /// Cursor shape for the insert mode.
1890 ///
1891 /// The default value follows the primary cursor_shape.
1892 pub insert: Option<CursorShape>,
1893}
1894
1895impl From<settings::CursorShapeSettings> for CursorShapeSettings {
1896 fn from(settings: settings::CursorShapeSettings) -> Self {
1897 Self {
1898 normal: settings.normal.map(Into::into),
1899 replace: settings.replace.map(Into::into),
1900 visual: settings.visual.map(Into::into),
1901 insert: settings.insert.map(Into::into),
1902 }
1903 }
1904}
1905
1906impl From<settings::ModeContent> for Mode {
1907 fn from(mode: ModeContent) -> Self {
1908 match mode {
1909 ModeContent::Normal => Self::Normal,
1910 ModeContent::Insert => Self::Insert,
1911 }
1912 }
1913}
1914
1915impl Settings for VimSettings {
1916 fn from_settings(content: &settings::SettingsContent) -> Self {
1917 let vim = content.vim.clone().unwrap();
1918 Self {
1919 default_mode: vim.default_mode.unwrap().into(),
1920 toggle_relative_line_numbers: vim.toggle_relative_line_numbers.unwrap(),
1921 use_system_clipboard: vim.use_system_clipboard.unwrap(),
1922 use_smartcase_find: vim.use_smartcase_find.unwrap(),
1923 custom_digraphs: vim.custom_digraphs.unwrap(),
1924 highlight_on_yank_duration: vim.highlight_on_yank_duration.unwrap(),
1925 cursor_shape: vim.cursor_shape.unwrap().into(),
1926 }
1927 }
1928}