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