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