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, SettingsUi, 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 && vim.entity_id() == cx.entity().entity_id()
793 {
794 Vim::globals(cx).focused_vim = None;
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 && action.as_any().downcast_ref::<TemporaryNormal>().is_some()
838 {
839 return;
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 && let Some(prior_tx) = prior_tx
1011 {
1012 editor.group_until_transaction(prior_tx, cx)
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 && pending.selection.reversed
1036 && mode.is_visual()
1037 && !last_mode.is_visual()
1038 {
1039 let mut end = pending.selection.end.to_point(&snapshot.buffer_snapshot);
1040 end = snapshot
1041 .buffer_snapshot
1042 .clip_point(end + Point::new(0, 1), Bias::Right);
1043 pending.selection.end = snapshot.buffer_snapshot.anchor_before(end);
1044 }
1045
1046 s.move_with(|map, selection| {
1047 if last_mode.is_visual() && !mode.is_visual() {
1048 let mut point = selection.head();
1049 if !selection.reversed && !selection.is_empty() {
1050 point = movement::left(map, selection.head());
1051 }
1052 selection.collapse_to(point, selection.goal)
1053 } else if !last_mode.is_visual() && mode.is_visual() && selection.is_empty() {
1054 selection.end = movement::right(map, selection.start);
1055 }
1056 });
1057 })
1058 });
1059 }
1060
1061 pub fn take_count(cx: &mut App) -> Option<usize> {
1062 let global_state = cx.global_mut::<VimGlobals>();
1063 if global_state.dot_replaying {
1064 return global_state.recorded_count;
1065 }
1066
1067 let count = if global_state.post_count.is_none() && global_state.pre_count.is_none() {
1068 return None;
1069 } else {
1070 Some(
1071 global_state.post_count.take().unwrap_or(1)
1072 * global_state.pre_count.take().unwrap_or(1),
1073 )
1074 };
1075
1076 if global_state.dot_recording {
1077 global_state.recorded_count = count;
1078 }
1079 count
1080 }
1081
1082 pub fn take_forced_motion(cx: &mut App) -> bool {
1083 let global_state = cx.global_mut::<VimGlobals>();
1084 let forced_motion = global_state.forced_motion;
1085 global_state.forced_motion = false;
1086 forced_motion
1087 }
1088
1089 pub fn cursor_shape(&self, cx: &mut App) -> CursorShape {
1090 let cursor_shape = VimSettings::get_global(cx).cursor_shape;
1091 match self.mode {
1092 Mode::Normal => {
1093 if let Some(operator) = self.operator_stack.last() {
1094 match operator {
1095 // Navigation operators -> Block cursor
1096 Operator::FindForward { .. }
1097 | Operator::FindBackward { .. }
1098 | Operator::Mark
1099 | Operator::Jump { .. }
1100 | Operator::Register
1101 | Operator::RecordRegister
1102 | Operator::ReplayRegister => CursorShape::Block,
1103
1104 // All other operators -> Underline cursor
1105 _ => CursorShape::Underline,
1106 }
1107 } else {
1108 cursor_shape.normal.unwrap_or(CursorShape::Block)
1109 }
1110 }
1111 Mode::HelixNormal => cursor_shape.normal.unwrap_or(CursorShape::Block),
1112 Mode::Replace => cursor_shape.replace.unwrap_or(CursorShape::Underline),
1113 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1114 cursor_shape.visual.unwrap_or(CursorShape::Block)
1115 }
1116 Mode::Insert => cursor_shape.insert.unwrap_or({
1117 let editor_settings = EditorSettings::get_global(cx);
1118 editor_settings.cursor_shape.unwrap_or_default()
1119 }),
1120 }
1121 }
1122
1123 pub fn editor_input_enabled(&self) -> bool {
1124 match self.mode {
1125 Mode::Insert => {
1126 if let Some(operator) = self.operator_stack.last() {
1127 !operator.is_waiting(self.mode)
1128 } else {
1129 true
1130 }
1131 }
1132 Mode::Normal
1133 | Mode::HelixNormal
1134 | Mode::Replace
1135 | Mode::Visual
1136 | Mode::VisualLine
1137 | Mode::VisualBlock => false,
1138 }
1139 }
1140
1141 pub fn should_autoindent(&self) -> bool {
1142 !(self.mode == Mode::Insert && self.last_mode == Mode::VisualBlock)
1143 }
1144
1145 pub fn clip_at_line_ends(&self) -> bool {
1146 match self.mode {
1147 Mode::Insert
1148 | Mode::Visual
1149 | Mode::VisualLine
1150 | Mode::VisualBlock
1151 | Mode::Replace
1152 | Mode::HelixNormal => false,
1153 Mode::Normal => true,
1154 }
1155 }
1156
1157 pub fn extend_key_context(&self, context: &mut KeyContext, cx: &App) {
1158 let mut mode = match self.mode {
1159 Mode::Normal => "normal",
1160 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => "visual",
1161 Mode::Insert => "insert",
1162 Mode::Replace => "replace",
1163 Mode::HelixNormal => "helix_normal",
1164 }
1165 .to_string();
1166
1167 let mut operator_id = "none";
1168
1169 let active_operator = self.active_operator();
1170 if active_operator.is_none() && cx.global::<VimGlobals>().pre_count.is_some()
1171 || active_operator.is_some() && cx.global::<VimGlobals>().post_count.is_some()
1172 {
1173 context.add("VimCount");
1174 }
1175
1176 if let Some(active_operator) = active_operator {
1177 if active_operator.is_waiting(self.mode) {
1178 if matches!(active_operator, Operator::Literal { .. }) {
1179 mode = "literal".to_string();
1180 } else {
1181 mode = "waiting".to_string();
1182 }
1183 } else {
1184 operator_id = active_operator.id();
1185 mode = "operator".to_string();
1186 }
1187 }
1188
1189 if mode == "normal" || mode == "visual" || mode == "operator" || mode == "helix_normal" {
1190 context.add("VimControl");
1191 }
1192 context.set("vim_mode", mode);
1193 context.set("vim_operator", operator_id);
1194 }
1195
1196 fn focused(&mut self, preserve_selection: bool, window: &mut Window, cx: &mut Context<Self>) {
1197 let Some(editor) = self.editor() else {
1198 return;
1199 };
1200 let newest_selection_empty = editor.update(cx, |editor, cx| {
1201 editor.selections.newest::<usize>(cx).is_empty()
1202 });
1203 let editor = editor.read(cx);
1204 let editor_mode = editor.mode();
1205
1206 if editor_mode.is_full()
1207 && !newest_selection_empty
1208 && self.mode == Mode::Normal
1209 // When following someone, don't switch vim mode.
1210 && editor.leader_id().is_none()
1211 {
1212 if preserve_selection {
1213 self.switch_mode(Mode::Visual, true, window, cx);
1214 } else {
1215 self.update_editor(cx, |_, editor, cx| {
1216 editor.set_clip_at_line_ends(false, cx);
1217 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1218 s.move_with(|_, selection| {
1219 selection.collapse_to(selection.start, selection.goal)
1220 })
1221 });
1222 });
1223 }
1224 }
1225
1226 cx.emit(VimEvent::Focused);
1227 self.sync_vim_settings(window, cx);
1228
1229 if VimSettings::get_global(cx).toggle_relative_line_numbers {
1230 if let Some(old_vim) = Vim::globals(cx).focused_vim() {
1231 if old_vim.entity_id() != cx.entity().entity_id() {
1232 old_vim.update(cx, |vim, cx| {
1233 vim.update_editor(cx, |_, editor, cx| {
1234 editor.set_relative_line_number(None, cx)
1235 });
1236 });
1237
1238 self.update_editor(cx, |vim, editor, cx| {
1239 let is_relative = vim.mode != Mode::Insert;
1240 editor.set_relative_line_number(Some(is_relative), cx)
1241 });
1242 }
1243 } else {
1244 self.update_editor(cx, |vim, editor, cx| {
1245 let is_relative = vim.mode != Mode::Insert;
1246 editor.set_relative_line_number(Some(is_relative), cx)
1247 });
1248 }
1249 }
1250 Vim::globals(cx).focused_vim = Some(cx.entity().downgrade());
1251 }
1252
1253 fn blurred(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1254 self.stop_recording_immediately(NormalBefore.boxed_clone(), cx);
1255 self.store_visual_marks(window, cx);
1256 self.clear_operator(window, cx);
1257 self.update_editor(cx, |vim, editor, cx| {
1258 if vim.cursor_shape(cx) == CursorShape::Block {
1259 editor.set_cursor_shape(CursorShape::Hollow, cx);
1260 }
1261 });
1262 }
1263
1264 fn cursor_shape_changed(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1265 self.update_editor(cx, |vim, editor, cx| {
1266 editor.set_cursor_shape(vim.cursor_shape(cx), cx);
1267 });
1268 }
1269
1270 fn update_editor<S>(
1271 &mut self,
1272 cx: &mut Context<Self>,
1273 update: impl FnOnce(&mut Self, &mut Editor, &mut Context<Editor>) -> S,
1274 ) -> Option<S> {
1275 let editor = self.editor.upgrade()?;
1276 Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
1277 }
1278
1279 fn editor_selections(&mut self, _: &mut Window, cx: &mut Context<Self>) -> Vec<Range<Anchor>> {
1280 self.update_editor(cx, |_, editor, _| {
1281 editor
1282 .selections
1283 .disjoint_anchors()
1284 .iter()
1285 .map(|selection| selection.tail()..selection.head())
1286 .collect()
1287 })
1288 .unwrap_or_default()
1289 }
1290
1291 fn editor_cursor_word(
1292 &mut self,
1293 window: &mut Window,
1294 cx: &mut Context<Self>,
1295 ) -> Option<String> {
1296 self.update_editor(cx, |_, editor, cx| {
1297 let selection = editor.selections.newest::<usize>(cx);
1298
1299 let snapshot = &editor.snapshot(window, cx).buffer_snapshot;
1300 let (range, kind) = snapshot.surrounding_word(selection.start, true);
1301 if kind == Some(CharKind::Word) {
1302 let text: String = snapshot.text_for_range(range).collect();
1303 if !text.trim().is_empty() {
1304 return Some(text);
1305 }
1306 }
1307
1308 None
1309 })
1310 .unwrap_or_default()
1311 }
1312
1313 /// When doing an action that modifies the buffer, we start recording so that `.`
1314 /// will replay the action.
1315 pub fn start_recording(&mut self, cx: &mut Context<Self>) {
1316 Vim::update_globals(cx, |globals, cx| {
1317 if !globals.dot_replaying {
1318 globals.dot_recording = true;
1319 globals.recording_actions = Default::default();
1320 globals.recorded_count = None;
1321
1322 let selections = self.editor().map(|editor| {
1323 editor.update(cx, |editor, cx| {
1324 (
1325 editor.selections.oldest::<Point>(cx),
1326 editor.selections.newest::<Point>(cx),
1327 )
1328 })
1329 });
1330
1331 if let Some((oldest, newest)) = selections {
1332 globals.recorded_selection = match self.mode {
1333 Mode::Visual if newest.end.row == newest.start.row => {
1334 RecordedSelection::SingleLine {
1335 cols: newest.end.column - newest.start.column,
1336 }
1337 }
1338 Mode::Visual => RecordedSelection::Visual {
1339 rows: newest.end.row - newest.start.row,
1340 cols: newest.end.column,
1341 },
1342 Mode::VisualLine => RecordedSelection::VisualLine {
1343 rows: newest.end.row - newest.start.row,
1344 },
1345 Mode::VisualBlock => RecordedSelection::VisualBlock {
1346 rows: newest.end.row.abs_diff(oldest.start.row),
1347 cols: newest.end.column.abs_diff(oldest.start.column),
1348 },
1349 _ => RecordedSelection::None,
1350 }
1351 } else {
1352 globals.recorded_selection = RecordedSelection::None;
1353 }
1354 }
1355 })
1356 }
1357
1358 pub fn stop_replaying(&mut self, cx: &mut Context<Self>) {
1359 let globals = Vim::globals(cx);
1360 globals.dot_replaying = false;
1361 if let Some(replayer) = globals.replayer.take() {
1362 replayer.stop();
1363 }
1364 }
1365
1366 /// When finishing an action that modifies the buffer, stop recording.
1367 /// as you usually call this within a keystroke handler we also ensure that
1368 /// the current action is recorded.
1369 pub fn stop_recording(&mut self, cx: &mut Context<Self>) {
1370 let globals = Vim::globals(cx);
1371 if globals.dot_recording {
1372 globals.stop_recording_after_next_action = true;
1373 }
1374 self.exit_temporary_mode = self.temp_mode;
1375 }
1376
1377 /// Stops recording actions immediately rather than waiting until after the
1378 /// next action to stop recording.
1379 ///
1380 /// This doesn't include the current action.
1381 pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>, cx: &mut Context<Self>) {
1382 let globals = Vim::globals(cx);
1383 if globals.dot_recording {
1384 globals
1385 .recording_actions
1386 .push(ReplayableAction::Action(action.boxed_clone()));
1387 globals.recorded_actions = mem::take(&mut globals.recording_actions);
1388 globals.dot_recording = false;
1389 globals.stop_recording_after_next_action = false;
1390 }
1391 self.exit_temporary_mode = self.temp_mode;
1392 }
1393
1394 /// Explicitly record one action (equivalents to start_recording and stop_recording)
1395 pub fn record_current_action(&mut self, cx: &mut Context<Self>) {
1396 self.start_recording(cx);
1397 self.stop_recording(cx);
1398 }
1399
1400 fn push_count_digit(&mut self, number: usize, window: &mut Window, cx: &mut Context<Self>) {
1401 if self.active_operator().is_some() {
1402 let post_count = Vim::globals(cx).post_count.unwrap_or(0);
1403
1404 Vim::globals(cx).post_count = Some(
1405 post_count
1406 .checked_mul(10)
1407 .and_then(|post_count| post_count.checked_add(number))
1408 .unwrap_or(post_count),
1409 )
1410 } else {
1411 let pre_count = Vim::globals(cx).pre_count.unwrap_or(0);
1412
1413 Vim::globals(cx).pre_count = Some(
1414 pre_count
1415 .checked_mul(10)
1416 .and_then(|pre_count| pre_count.checked_add(number))
1417 .unwrap_or(pre_count),
1418 )
1419 }
1420 // update the keymap so that 0 works
1421 self.sync_vim_settings(window, cx)
1422 }
1423
1424 fn select_register(&mut self, register: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
1425 if register.chars().count() == 1 {
1426 self.selected_register
1427 .replace(register.chars().next().unwrap());
1428 }
1429 self.operator_stack.clear();
1430 self.sync_vim_settings(window, cx);
1431 }
1432
1433 fn maybe_pop_operator(&mut self) -> Option<Operator> {
1434 self.operator_stack.pop()
1435 }
1436
1437 fn pop_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Operator {
1438 let popped_operator = self.operator_stack.pop()
1439 .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
1440 self.sync_vim_settings(window, cx);
1441 popped_operator
1442 }
1443
1444 fn clear_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1445 Vim::take_count(cx);
1446 Vim::take_forced_motion(cx);
1447 self.selected_register.take();
1448 self.operator_stack.clear();
1449 self.sync_vim_settings(window, cx);
1450 }
1451
1452 fn active_operator(&self) -> Option<Operator> {
1453 self.operator_stack.last().cloned()
1454 }
1455
1456 fn transaction_begun(
1457 &mut self,
1458 transaction_id: TransactionId,
1459 _window: &mut Window,
1460 _: &mut Context<Self>,
1461 ) {
1462 let mode = if (self.mode == Mode::Insert
1463 || self.mode == Mode::Replace
1464 || self.mode == Mode::Normal)
1465 && self.current_tx.is_none()
1466 {
1467 self.current_tx = Some(transaction_id);
1468 self.last_mode
1469 } else {
1470 self.mode
1471 };
1472 if mode == Mode::VisualLine || mode == Mode::VisualBlock {
1473 self.undo_modes.insert(transaction_id, mode);
1474 }
1475 }
1476
1477 fn transaction_undone(
1478 &mut self,
1479 transaction_id: &TransactionId,
1480 window: &mut Window,
1481 cx: &mut Context<Self>,
1482 ) {
1483 match self.mode {
1484 Mode::VisualLine | Mode::VisualBlock | Mode::Visual => {
1485 self.update_editor(cx, |vim, editor, cx| {
1486 let original_mode = vim.undo_modes.get(transaction_id);
1487 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1488 match original_mode {
1489 Some(Mode::VisualLine) => {
1490 s.move_with(|map, selection| {
1491 selection.collapse_to(
1492 map.prev_line_boundary(selection.start.to_point(map)).1,
1493 SelectionGoal::None,
1494 )
1495 });
1496 }
1497 Some(Mode::VisualBlock) => {
1498 let mut first = s.first_anchor();
1499 first.collapse_to(first.start, first.goal);
1500 s.select_anchors(vec![first]);
1501 }
1502 _ => {
1503 s.move_with(|map, selection| {
1504 selection.collapse_to(
1505 map.clip_at_line_end(selection.start),
1506 selection.goal,
1507 );
1508 });
1509 }
1510 }
1511 });
1512 });
1513 self.switch_mode(Mode::Normal, true, window, cx)
1514 }
1515 Mode::Normal => {
1516 self.update_editor(cx, |_, editor, cx| {
1517 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1518 s.move_with(|map, selection| {
1519 selection
1520 .collapse_to(map.clip_at_line_end(selection.end), selection.goal)
1521 })
1522 })
1523 });
1524 }
1525 Mode::Insert | Mode::Replace | Mode::HelixNormal => {}
1526 }
1527 }
1528
1529 fn local_selections_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1530 let Some(editor) = self.editor() else { return };
1531
1532 if editor.read(cx).leader_id().is_some() {
1533 return;
1534 }
1535
1536 let newest = editor.read(cx).selections.newest_anchor().clone();
1537 let is_multicursor = editor.read(cx).selections.count() > 1;
1538 if self.mode == Mode::Insert && self.current_tx.is_some() {
1539 if self.current_anchor.is_none() {
1540 self.current_anchor = Some(newest);
1541 } else if self.current_anchor.as_ref().unwrap() != &newest
1542 && let Some(tx_id) = self.current_tx.take()
1543 {
1544 self.update_editor(cx, |_, editor, cx| {
1545 editor.group_until_transaction(tx_id, cx)
1546 });
1547 }
1548 } else if self.mode == Mode::Normal && newest.start != newest.end {
1549 if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
1550 self.switch_mode(Mode::VisualBlock, false, window, cx);
1551 } else {
1552 self.switch_mode(Mode::Visual, false, window, cx)
1553 }
1554 } else if newest.start == newest.end
1555 && !is_multicursor
1556 && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&self.mode)
1557 {
1558 self.switch_mode(Mode::Normal, true, window, cx);
1559 }
1560 }
1561
1562 fn input_ignored(&mut self, text: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
1563 if text.is_empty() {
1564 return;
1565 }
1566
1567 match self.active_operator() {
1568 Some(Operator::FindForward { before, multiline }) => {
1569 let find = Motion::FindForward {
1570 before,
1571 char: text.chars().next().unwrap(),
1572 mode: if multiline {
1573 FindRange::MultiLine
1574 } else {
1575 FindRange::SingleLine
1576 },
1577 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1578 };
1579 Vim::globals(cx).last_find = Some(find.clone());
1580 self.motion(find, window, cx)
1581 }
1582 Some(Operator::FindBackward { after, multiline }) => {
1583 let find = Motion::FindBackward {
1584 after,
1585 char: text.chars().next().unwrap(),
1586 mode: if multiline {
1587 FindRange::MultiLine
1588 } else {
1589 FindRange::SingleLine
1590 },
1591 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1592 };
1593 Vim::globals(cx).last_find = Some(find.clone());
1594 self.motion(find, window, cx)
1595 }
1596 Some(Operator::Sneak { first_char }) => {
1597 if let Some(first_char) = first_char {
1598 if let Some(second_char) = text.chars().next() {
1599 let sneak = Motion::Sneak {
1600 first_char,
1601 second_char,
1602 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1603 };
1604 Vim::globals(cx).last_find = Some(sneak.clone());
1605 self.motion(sneak, window, cx)
1606 }
1607 } else {
1608 let first_char = text.chars().next();
1609 self.pop_operator(window, cx);
1610 self.push_operator(Operator::Sneak { first_char }, window, cx);
1611 }
1612 }
1613 Some(Operator::SneakBackward { first_char }) => {
1614 if let Some(first_char) = first_char {
1615 if let Some(second_char) = text.chars().next() {
1616 let sneak = Motion::SneakBackward {
1617 first_char,
1618 second_char,
1619 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1620 };
1621 Vim::globals(cx).last_find = Some(sneak.clone());
1622 self.motion(sneak, window, cx)
1623 }
1624 } else {
1625 let first_char = text.chars().next();
1626 self.pop_operator(window, cx);
1627 self.push_operator(Operator::SneakBackward { first_char }, window, cx);
1628 }
1629 }
1630 Some(Operator::Replace) => match self.mode {
1631 Mode::Normal => self.normal_replace(text, window, cx),
1632 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1633 self.visual_replace(text, window, cx)
1634 }
1635 Mode::HelixNormal => self.helix_replace(&text, window, cx),
1636 _ => self.clear_operator(window, cx),
1637 },
1638 Some(Operator::Digraph { first_char }) => {
1639 if let Some(first_char) = first_char {
1640 if let Some(second_char) = text.chars().next() {
1641 self.insert_digraph(first_char, second_char, window, cx);
1642 }
1643 } else {
1644 let first_char = text.chars().next();
1645 self.pop_operator(window, cx);
1646 self.push_operator(Operator::Digraph { first_char }, window, cx);
1647 }
1648 }
1649 Some(Operator::Literal { prefix }) => {
1650 self.handle_literal_input(prefix.unwrap_or_default(), &text, window, cx)
1651 }
1652 Some(Operator::AddSurrounds { target }) => match self.mode {
1653 Mode::Normal => {
1654 if let Some(target) = target {
1655 self.add_surrounds(text, target, window, cx);
1656 self.clear_operator(window, cx);
1657 }
1658 }
1659 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1660 self.add_surrounds(text, SurroundsType::Selection, window, cx);
1661 self.clear_operator(window, cx);
1662 }
1663 _ => self.clear_operator(window, cx),
1664 },
1665 Some(Operator::ChangeSurrounds { target }) => match self.mode {
1666 Mode::Normal => {
1667 if let Some(target) = target {
1668 self.change_surrounds(text, target, window, cx);
1669 self.clear_operator(window, cx);
1670 }
1671 }
1672 _ => self.clear_operator(window, cx),
1673 },
1674 Some(Operator::DeleteSurrounds) => match self.mode {
1675 Mode::Normal => {
1676 self.delete_surrounds(text, window, cx);
1677 self.clear_operator(window, cx);
1678 }
1679 _ => self.clear_operator(window, cx),
1680 },
1681 Some(Operator::Mark) => self.create_mark(text, window, cx),
1682 Some(Operator::RecordRegister) => {
1683 self.record_register(text.chars().next().unwrap(), window, cx)
1684 }
1685 Some(Operator::ReplayRegister) => {
1686 self.replay_register(text.chars().next().unwrap(), window, cx)
1687 }
1688 Some(Operator::Register) => match self.mode {
1689 Mode::Insert => {
1690 self.update_editor(cx, |_, editor, cx| {
1691 if let Some(register) = Vim::update_globals(cx, |globals, cx| {
1692 globals.read_register(text.chars().next(), Some(editor), cx)
1693 }) {
1694 editor.do_paste(
1695 ®ister.text.to_string(),
1696 register.clipboard_selections,
1697 false,
1698 window,
1699 cx,
1700 )
1701 }
1702 });
1703 self.clear_operator(window, cx);
1704 }
1705 _ => {
1706 self.select_register(text, window, cx);
1707 }
1708 },
1709 Some(Operator::Jump { line }) => self.jump(text, line, true, window, cx),
1710 _ => {
1711 if self.mode == Mode::Replace {
1712 self.multi_replace(text, window, cx)
1713 }
1714
1715 if self.mode == Mode::Normal {
1716 self.update_editor(cx, |_, editor, cx| {
1717 editor.accept_edit_prediction(
1718 &editor::actions::AcceptEditPrediction {},
1719 window,
1720 cx,
1721 );
1722 });
1723 }
1724 }
1725 }
1726 }
1727
1728 fn sync_vim_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1729 self.update_editor(cx, |vim, editor, cx| {
1730 editor.set_cursor_shape(vim.cursor_shape(cx), cx);
1731 editor.set_clip_at_line_ends(vim.clip_at_line_ends(), cx);
1732 editor.set_collapse_matches(true);
1733 editor.set_input_enabled(vim.editor_input_enabled());
1734 editor.set_autoindent(vim.should_autoindent());
1735 editor.selections.line_mode = matches!(vim.mode, Mode::VisualLine);
1736
1737 let hide_edit_predictions = !matches!(vim.mode, Mode::Insert | Mode::Replace);
1738 editor.set_edit_predictions_hidden_for_vim_mode(hide_edit_predictions, window, cx);
1739 });
1740 cx.notify()
1741 }
1742}
1743
1744/// Controls when to use system clipboard.
1745#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
1746#[serde(rename_all = "snake_case")]
1747pub enum UseSystemClipboard {
1748 /// Don't use system clipboard.
1749 Never,
1750 /// Use system clipboard.
1751 Always,
1752 /// Use system clipboard for yank operations.
1753 OnYank,
1754}
1755
1756/// The settings for cursor shape.
1757#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
1758struct CursorShapeSettings {
1759 /// Cursor shape for the normal mode.
1760 ///
1761 /// Default: block
1762 pub normal: Option<CursorShape>,
1763 /// Cursor shape for the replace mode.
1764 ///
1765 /// Default: underline
1766 pub replace: Option<CursorShape>,
1767 /// Cursor shape for the visual mode.
1768 ///
1769 /// Default: block
1770 pub visual: Option<CursorShape>,
1771 /// Cursor shape for the insert mode.
1772 ///
1773 /// The default value follows the primary cursor_shape.
1774 pub insert: Option<CursorShape>,
1775}
1776
1777#[derive(Deserialize)]
1778struct VimSettings {
1779 pub default_mode: Mode,
1780 pub toggle_relative_line_numbers: bool,
1781 pub use_system_clipboard: UseSystemClipboard,
1782 pub use_smartcase_find: bool,
1783 pub custom_digraphs: HashMap<String, Arc<str>>,
1784 pub highlight_on_yank_duration: u64,
1785 pub cursor_shape: CursorShapeSettings,
1786}
1787
1788#[derive(Clone, Default, Serialize, Deserialize, JsonSchema, SettingsUi)]
1789struct VimSettingsContent {
1790 pub default_mode: Option<ModeContent>,
1791 pub toggle_relative_line_numbers: Option<bool>,
1792 pub use_system_clipboard: Option<UseSystemClipboard>,
1793 pub use_smartcase_find: Option<bool>,
1794 pub custom_digraphs: Option<HashMap<String, Arc<str>>>,
1795 pub highlight_on_yank_duration: Option<u64>,
1796 pub cursor_shape: Option<CursorShapeSettings>,
1797}
1798
1799#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
1800#[serde(rename_all = "snake_case")]
1801pub enum ModeContent {
1802 #[default]
1803 Normal,
1804 Insert,
1805 Replace,
1806 Visual,
1807 VisualLine,
1808 VisualBlock,
1809 HelixNormal,
1810}
1811
1812impl From<ModeContent> for Mode {
1813 fn from(mode: ModeContent) -> Self {
1814 match mode {
1815 ModeContent::Normal => Self::Normal,
1816 ModeContent::Insert => Self::Insert,
1817 ModeContent::Replace => Self::Replace,
1818 ModeContent::Visual => Self::Visual,
1819 ModeContent::VisualLine => Self::VisualLine,
1820 ModeContent::VisualBlock => Self::VisualBlock,
1821 ModeContent::HelixNormal => Self::HelixNormal,
1822 }
1823 }
1824}
1825
1826impl Settings for VimSettings {
1827 const KEY: Option<&'static str> = Some("vim");
1828
1829 type FileContent = VimSettingsContent;
1830
1831 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
1832 let settings: VimSettingsContent = sources.json_merge()?;
1833
1834 Ok(Self {
1835 default_mode: settings
1836 .default_mode
1837 .ok_or_else(Self::missing_default)?
1838 .into(),
1839 toggle_relative_line_numbers: settings
1840 .toggle_relative_line_numbers
1841 .ok_or_else(Self::missing_default)?,
1842 use_system_clipboard: settings
1843 .use_system_clipboard
1844 .ok_or_else(Self::missing_default)?,
1845 use_smartcase_find: settings
1846 .use_smartcase_find
1847 .ok_or_else(Self::missing_default)?,
1848 custom_digraphs: settings.custom_digraphs.ok_or_else(Self::missing_default)?,
1849 highlight_on_yank_duration: settings
1850 .highlight_on_yank_duration
1851 .ok_or_else(Self::missing_default)?,
1852 cursor_shape: settings.cursor_shape.ok_or_else(Self::missing_default)?,
1853 })
1854 }
1855
1856 fn import_from_vscode(_vscode: &settings::VsCodeSettings, _current: &mut Self::FileContent) {
1857 // TODO: translate vim extension settings
1858 }
1859}