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