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