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