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