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