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