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