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 movement::{self, FindRange},
26 Anchor, Bias, Editor, EditorEvent, EditorMode, ToPoint,
27};
28use gpui::{
29 actions, impl_actions, Action, AppContext, Axis, Entity, EventEmitter, KeyContext,
30 KeystrokeEvent, Render, Subscription, View, ViewContext, WeakView,
31};
32use insert::{NormalBefore, TemporaryNormal};
33use language::{CursorShape, Point, Selection, SelectionGoal, TransactionId};
34pub use mode_indicator::ModeIndicator;
35use motion::Motion;
36use normal::search::SearchSubmit;
37use schemars::JsonSchema;
38use serde::Deserialize;
39use serde_derive::Serialize;
40use settings::{update_settings_file, Settings, SettingsSources, SettingsStore};
41use state::{Mode, Operator, RecordedSelection, SearchState, VimGlobals};
42use std::{mem, ops::Range, sync::Arc};
43use surrounds::SurroundsType;
44use theme::ThemeSettings;
45use ui::{px, IntoElement, VisualContext};
46use vim_mode_setting::VimModeSetting;
47use workspace::{self, Pane, ResizeIntent, Workspace};
48
49use crate::state::ReplayableAction;
50
51/// Used to resize the current pane
52#[derive(Clone, Deserialize, PartialEq)]
53pub struct ResizePane(pub ResizeIntent);
54
55/// An Action to Switch between modes
56#[derive(Clone, Deserialize, PartialEq)]
57pub struct SwitchMode(pub Mode);
58
59/// PushOperator is used to put vim into a "minor" mode,
60/// where it's waiting for a specific next set of keystrokes.
61/// For example 'd' needs a motion to complete.
62#[derive(Clone, Deserialize, PartialEq)]
63pub struct PushOperator(pub Operator);
64
65/// Number is used to manage vim's count. Pushing a digit
66/// multiplis the current value by 10 and adds the digit.
67#[derive(Clone, Deserialize, PartialEq)]
68struct Number(usize);
69
70#[derive(Clone, Deserialize, PartialEq)]
71struct SelectRegister(String);
72
73actions!(
74 vim,
75 [
76 ClearOperators,
77 Tab,
78 Enter,
79 Object,
80 InnerObject,
81 FindForward,
82 FindBackward,
83 OpenDefaultKeymap,
84 MaximizePane,
85 ResetPaneSizes,
86 ]
87);
88
89// in the workspace namespace so it's not filtered out when vim is disabled.
90actions!(workspace, [ToggleVimMode]);
91
92impl_actions!(
93 vim,
94 [ResizePane, SwitchMode, PushOperator, Number, SelectRegister]
95);
96
97/// Initializes the `vim` crate.
98pub fn init(cx: &mut AppContext) {
99 vim_mode_setting::init(cx);
100 VimSettings::register(cx);
101 VimGlobals::register(cx);
102
103 cx.observe_new_views(|editor: &mut Editor, cx| Vim::register(editor, cx))
104 .detach();
105
106 cx.observe_new_views(|workspace: &mut Workspace, _| {
107 workspace.register_action(|workspace, _: &ToggleVimMode, cx| {
108 let fs = workspace.app_state().fs.clone();
109 let currently_enabled = Vim::enabled(cx);
110 update_settings_file::<VimModeSetting>(fs, cx, move |setting, _| {
111 *setting = Some(!currently_enabled)
112 })
113 });
114
115 workspace.register_action(|_, _: &OpenDefaultKeymap, cx| {
116 cx.emit(workspace::Event::OpenBundledFile {
117 text: settings::vim_keymap(),
118 title: "Default Vim Bindings",
119 language: "JSON",
120 });
121 });
122
123 workspace.register_action(|workspace, _: &ResetPaneSizes, cx| {
124 workspace.reset_pane_sizes(cx);
125 });
126
127 workspace.register_action(|workspace, _: &MaximizePane, cx| {
128 let pane = workspace.active_pane();
129 let Some(size) = workspace.bounding_box_for_pane(&pane) else {
130 return;
131 };
132
133 let theme = ThemeSettings::get_global(cx);
134 let height = theme.buffer_font_size(cx) * theme.buffer_line_height.value();
135
136 let desired_size = if let Some(count) = Vim::take_count(cx) {
137 height * count
138 } else {
139 px(10000.)
140 };
141 workspace.resize_pane(Axis::Vertical, desired_size - size.size.height, cx)
142 });
143
144 workspace.register_action(|workspace, action: &ResizePane, cx| {
145 let count = Vim::take_count(cx).unwrap_or(1) as f32;
146 let theme = ThemeSettings::get_global(cx);
147 let Ok(font_id) = cx.text_system().font_id(&theme.buffer_font) else {
148 return;
149 };
150 let Ok(width) = cx
151 .text_system()
152 .advance(font_id, theme.buffer_font_size(cx), 'm')
153 else {
154 return;
155 };
156 let height = theme.buffer_font_size(cx) * theme.buffer_line_height.value();
157
158 let (axis, amount) = match action.0 {
159 ResizeIntent::Lengthen => (Axis::Vertical, height),
160 ResizeIntent::Shorten => (Axis::Vertical, height * -1.),
161 ResizeIntent::Widen => (Axis::Horizontal, width.width),
162 ResizeIntent::Narrow => (Axis::Horizontal, width.width * -1.),
163 };
164
165 workspace.resize_pane(axis, amount * count, cx);
166 });
167
168 workspace.register_action(|workspace, _: &SearchSubmit, cx| {
169 let vim = workspace
170 .focused_pane(cx)
171 .read(cx)
172 .active_item()
173 .and_then(|item| item.act_as::<Editor>(cx))
174 .and_then(|editor| editor.read(cx).addon::<VimAddon>().cloned());
175 let Some(vim) = vim else { return };
176 vim.view
177 .update(cx, |_, cx| cx.defer(|vim, cx| vim.search_submit(cx)))
178 });
179 })
180 .detach();
181}
182
183#[derive(Clone)]
184pub(crate) struct VimAddon {
185 pub(crate) view: View<Vim>,
186}
187
188impl editor::Addon for VimAddon {
189 fn extend_key_context(&self, key_context: &mut KeyContext, cx: &AppContext) {
190 self.view.read(cx).extend_key_context(key_context, cx)
191 }
192
193 fn to_any(&self) -> &dyn std::any::Any {
194 self
195 }
196}
197
198/// The state pertaining to Vim mode.
199pub(crate) struct Vim {
200 pub(crate) mode: Mode,
201 pub last_mode: Mode,
202 pub temp_mode: bool,
203 pub exit_temporary_mode: bool,
204
205 operator_stack: Vec<Operator>,
206 pub(crate) replacements: Vec<(Range<editor::Anchor>, String)>,
207
208 pub(crate) marks: HashMap<String, Vec<Anchor>>,
209 pub(crate) stored_visual_mode: Option<(Mode, Vec<bool>)>,
210 pub(crate) change_list: Vec<Vec<Anchor>>,
211 pub(crate) change_list_position: Option<usize>,
212
213 pub(crate) current_tx: Option<TransactionId>,
214 pub(crate) current_anchor: Option<Selection<Anchor>>,
215 pub(crate) undo_modes: HashMap<TransactionId, Mode>,
216
217 selected_register: Option<char>,
218 pub search: SearchState,
219
220 editor: WeakView<Editor>,
221
222 _subscriptions: Vec<Subscription>,
223}
224
225// Hack: Vim intercepts events dispatched to a window and updates the view in response.
226// This means it needs a VisualContext. The easiest way to satisfy that constraint is
227// to make Vim a "View" that is just never actually rendered.
228impl Render for Vim {
229 fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
230 gpui::Empty
231 }
232}
233
234enum VimEvent {
235 Focused,
236}
237impl EventEmitter<VimEvent> for Vim {}
238
239impl Vim {
240 /// The namespace for Vim actions.
241 const NAMESPACE: &'static str = "vim";
242
243 pub fn new(cx: &mut ViewContext<Editor>) -> View<Self> {
244 let editor = cx.view().clone();
245
246 cx.new_view(|cx| Vim {
247 mode: Mode::Normal,
248 last_mode: Mode::Normal,
249 temp_mode: false,
250 exit_temporary_mode: false,
251 operator_stack: Vec::new(),
252 replacements: Vec::new(),
253
254 marks: HashMap::default(),
255 stored_visual_mode: None,
256 change_list: Vec::new(),
257 change_list_position: None,
258 current_tx: None,
259 current_anchor: None,
260 undo_modes: HashMap::default(),
261
262 selected_register: None,
263 search: SearchState::default(),
264
265 editor: editor.downgrade(),
266 _subscriptions: vec![
267 cx.observe_keystrokes(Self::observe_keystrokes),
268 cx.subscribe(&editor, |this, _, event, cx| {
269 this.handle_editor_event(event, cx)
270 }),
271 ],
272 })
273 }
274
275 fn register(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
276 if !editor.use_modal_editing() {
277 return;
278 }
279
280 let mut was_enabled = Vim::enabled(cx);
281 let mut was_toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;
282 cx.observe_global::<SettingsStore>(move |editor, cx| {
283 let enabled = Vim::enabled(cx);
284 let toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;
285 if enabled && was_enabled && (toggle != was_toggle) {
286 if toggle {
287 let is_relative = editor
288 .addon::<VimAddon>()
289 .map(|vim| vim.view.read(cx).mode != Mode::Insert);
290 editor.set_relative_line_number(is_relative, cx)
291 } else {
292 editor.set_relative_line_number(None, cx)
293 }
294 }
295 was_toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;
296 if was_enabled == enabled {
297 return;
298 }
299 was_enabled = enabled;
300 if enabled {
301 Self::activate(editor, cx)
302 } else {
303 Self::deactivate(editor, cx)
304 }
305 })
306 .detach();
307 if was_enabled {
308 Self::activate(editor, cx)
309 }
310 }
311
312 fn activate(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
313 let vim = Vim::new(cx);
314
315 editor.register_addon(VimAddon { view: vim.clone() });
316
317 vim.update(cx, |_, cx| {
318 Vim::action(editor, cx, |vim, action: &SwitchMode, cx| {
319 vim.switch_mode(action.0, false, cx)
320 });
321
322 Vim::action(editor, cx, |vim, action: &PushOperator, cx| {
323 vim.push_operator(action.0.clone(), cx)
324 });
325
326 Vim::action(editor, cx, |vim, _: &ClearOperators, cx| {
327 vim.clear_operator(cx)
328 });
329 Vim::action(editor, cx, |vim, n: &Number, cx| {
330 vim.push_count_digit(n.0, cx);
331 });
332 Vim::action(editor, cx, |vim, _: &Tab, cx| {
333 vim.input_ignored(" ".into(), cx)
334 });
335 Vim::action(editor, cx, |vim, _: &Enter, cx| {
336 vim.input_ignored("\n".into(), cx)
337 });
338
339 normal::register(editor, cx);
340 insert::register(editor, cx);
341 helix::register(editor, cx);
342 motion::register(editor, cx);
343 command::register(editor, cx);
344 replace::register(editor, cx);
345 indent::register(editor, cx);
346 rewrap::register(editor, cx);
347 object::register(editor, cx);
348 visual::register(editor, cx);
349 change_list::register(editor, cx);
350 digraph::register(editor, cx);
351
352 cx.defer(|vim, cx| {
353 vim.focused(false, cx);
354 })
355 })
356 }
357
358 fn deactivate(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
359 editor.set_cursor_shape(CursorShape::Bar, cx);
360 editor.set_clip_at_line_ends(false, cx);
361 editor.set_collapse_matches(false);
362 editor.set_input_enabled(true);
363 editor.set_autoindent(true);
364 editor.selections.line_mode = false;
365 editor.unregister_addon::<VimAddon>();
366 editor.set_relative_line_number(None, cx);
367 if let Some(vim) = Vim::globals(cx).focused_vim() {
368 if vim.entity_id() == cx.view().entity_id() {
369 Vim::globals(cx).focused_vim = None;
370 }
371 }
372 }
373
374 /// Register an action on the editor.
375 pub fn action<A: Action>(
376 editor: &mut Editor,
377 cx: &mut ViewContext<Vim>,
378 f: impl Fn(&mut Vim, &A, &mut ViewContext<Vim>) + 'static,
379 ) {
380 let subscription = editor.register_action(cx.listener(f));
381 cx.on_release(|_, _, _| drop(subscription)).detach();
382 }
383
384 pub fn editor(&self) -> Option<View<Editor>> {
385 self.editor.upgrade()
386 }
387
388 pub fn workspace(&self, cx: &mut ViewContext<Self>) -> Option<View<Workspace>> {
389 cx.window_handle()
390 .downcast::<Workspace>()
391 .and_then(|handle| handle.root(cx).ok())
392 }
393
394 pub fn pane(&self, cx: &mut ViewContext<Self>) -> Option<View<Pane>> {
395 self.workspace(cx)
396 .map(|workspace| workspace.read(cx).focused_pane(cx))
397 }
398
399 pub fn enabled(cx: &mut AppContext) -> bool {
400 VimModeSetting::get_global(cx).0
401 }
402
403 /// Called whenever an keystroke is typed so vim can observe all actions
404 /// and keystrokes accordingly.
405 fn observe_keystrokes(&mut self, keystroke_event: &KeystrokeEvent, cx: &mut ViewContext<Self>) {
406 if self.exit_temporary_mode {
407 self.exit_temporary_mode = false;
408 // Don't switch to insert mode if the action is temporary_normal.
409 if let Some(action) = keystroke_event.action.as_ref() {
410 if action.as_any().downcast_ref::<TemporaryNormal>().is_some() {
411 return;
412 }
413 }
414 self.switch_mode(Mode::Insert, false, cx)
415 }
416 if let Some(action) = keystroke_event.action.as_ref() {
417 // Keystroke is handled by the vim system, so continue forward
418 if action.name().starts_with("vim::") {
419 return;
420 }
421 } else if cx.has_pending_keystrokes() || keystroke_event.keystroke.is_ime_in_progress() {
422 return;
423 }
424
425 if let Some(operator) = self.active_operator() {
426 match operator {
427 Operator::Literal { prefix } => {
428 self.handle_literal_keystroke(keystroke_event, prefix.unwrap_or_default(), cx);
429 }
430 _ if !operator.is_waiting(self.mode) => {
431 self.clear_operator(cx);
432 self.stop_recording_immediately(Box::new(ClearOperators), cx)
433 }
434 _ => {}
435 }
436 }
437 }
438
439 fn handle_editor_event(&mut self, event: &EditorEvent, cx: &mut ViewContext<Self>) {
440 match event {
441 EditorEvent::Focused => self.focused(true, cx),
442 EditorEvent::Blurred => self.blurred(cx),
443 EditorEvent::SelectionsChanged { local: true } => {
444 self.local_selections_changed(cx);
445 }
446 EditorEvent::InputIgnored { text } => {
447 self.input_ignored(text.clone(), cx);
448 Vim::globals(cx).observe_insertion(text, None)
449 }
450 EditorEvent::InputHandled {
451 text,
452 utf16_range_to_replace: range_to_replace,
453 } => Vim::globals(cx).observe_insertion(text, range_to_replace.clone()),
454 EditorEvent::TransactionBegun { transaction_id } => {
455 self.transaction_begun(*transaction_id, cx)
456 }
457 EditorEvent::TransactionUndone { transaction_id } => {
458 self.transaction_undone(transaction_id, cx)
459 }
460 EditorEvent::Edited { .. } => self.push_to_change_list(cx),
461 EditorEvent::FocusedIn => self.sync_vim_settings(cx),
462 EditorEvent::CursorShapeChanged => self.cursor_shape_changed(cx),
463 _ => {}
464 }
465 }
466
467 fn push_operator(&mut self, operator: Operator, cx: &mut ViewContext<Self>) {
468 if matches!(
469 operator,
470 Operator::Change
471 | Operator::Delete
472 | Operator::Replace
473 | Operator::Indent
474 | Operator::Outdent
475 | Operator::AutoIndent
476 | Operator::Lowercase
477 | Operator::Uppercase
478 | Operator::OppositeCase
479 | Operator::ToggleComments
480 ) {
481 self.start_recording(cx)
482 };
483 // Since these operations can only be entered with pre-operators,
484 // we need to clear the previous operators when pushing,
485 // so that the current stack is the most correct
486 if matches!(
487 operator,
488 Operator::AddSurrounds { .. }
489 | Operator::ChangeSurrounds { .. }
490 | Operator::DeleteSurrounds
491 ) {
492 self.operator_stack.clear();
493 if let Operator::AddSurrounds { target: None } = operator {
494 self.start_recording(cx);
495 }
496 };
497 self.operator_stack.push(operator);
498 self.sync_vim_settings(cx);
499 }
500
501 pub fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut ViewContext<Self>) {
502 if self.temp_mode && mode == Mode::Normal {
503 self.temp_mode = false;
504 self.switch_mode(Mode::Normal, leave_selections, cx);
505 self.switch_mode(Mode::Insert, false, cx);
506 return;
507 } else if self.temp_mode
508 && !matches!(mode, Mode::Visual | Mode::VisualLine | Mode::VisualBlock)
509 {
510 self.temp_mode = false;
511 }
512
513 let last_mode = self.mode;
514 let prior_mode = self.last_mode;
515 let prior_tx = self.current_tx;
516 self.last_mode = last_mode;
517 self.mode = mode;
518 self.operator_stack.clear();
519 self.selected_register.take();
520 if mode == Mode::Normal || mode != last_mode {
521 self.current_tx.take();
522 self.current_anchor.take();
523 }
524 if mode != Mode::Insert && mode != Mode::Replace {
525 Vim::take_count(cx);
526 }
527
528 // Sync editor settings like clip mode
529 self.sync_vim_settings(cx);
530
531 if VimSettings::get_global(cx).toggle_relative_line_numbers
532 && self.mode != self.last_mode
533 && (self.mode == Mode::Insert || self.last_mode == Mode::Insert)
534 {
535 self.update_editor(cx, |vim, editor, cx| {
536 let is_relative = vim.mode != Mode::Insert;
537 editor.set_relative_line_number(Some(is_relative), cx)
538 });
539 }
540
541 if leave_selections {
542 return;
543 }
544
545 if !mode.is_visual() && last_mode.is_visual() {
546 self.create_visual_marks(last_mode, cx);
547 }
548
549 // Adjust selections
550 self.update_editor(cx, |vim, editor, cx| {
551 if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
552 {
553 vim.visual_block_motion(true, editor, cx, |_, point, goal| Some((point, goal)))
554 }
555 if last_mode == Mode::Insert || last_mode == Mode::Replace {
556 if let Some(prior_tx) = prior_tx {
557 editor.group_until_transaction(prior_tx, cx)
558 }
559 }
560
561 editor.change_selections(None, cx, |s| {
562 // we cheat with visual block mode and use multiple cursors.
563 // the cost of this cheat is we need to convert back to a single
564 // cursor whenever vim would.
565 if last_mode == Mode::VisualBlock
566 && (mode != Mode::VisualBlock && mode != Mode::Insert)
567 {
568 let tail = s.oldest_anchor().tail();
569 let head = s.newest_anchor().head();
570 s.select_anchor_ranges(vec![tail..head]);
571 } else if last_mode == Mode::Insert
572 && prior_mode == Mode::VisualBlock
573 && mode != Mode::VisualBlock
574 {
575 let pos = s.first_anchor().head();
576 s.select_anchor_ranges(vec![pos..pos])
577 }
578
579 let snapshot = s.display_map();
580 if let Some(pending) = s.pending.as_mut() {
581 if pending.selection.reversed && mode.is_visual() && !last_mode.is_visual() {
582 let mut end = pending.selection.end.to_point(&snapshot.buffer_snapshot);
583 end = snapshot
584 .buffer_snapshot
585 .clip_point(end + Point::new(0, 1), Bias::Right);
586 pending.selection.end = snapshot.buffer_snapshot.anchor_before(end);
587 }
588 }
589
590 s.move_with(|map, selection| {
591 if last_mode.is_visual() && !mode.is_visual() {
592 let mut point = selection.head();
593 if !selection.reversed && !selection.is_empty() {
594 point = movement::left(map, selection.head());
595 }
596 selection.collapse_to(point, selection.goal)
597 } else if !last_mode.is_visual() && mode.is_visual() && selection.is_empty() {
598 selection.end = movement::right(map, selection.start);
599 }
600 });
601 })
602 });
603 }
604
605 pub fn take_count(cx: &mut AppContext) -> Option<usize> {
606 let global_state = cx.global_mut::<VimGlobals>();
607 if global_state.dot_replaying {
608 return global_state.recorded_count;
609 }
610
611 let count = if global_state.post_count.is_none() && global_state.pre_count.is_none() {
612 return None;
613 } else {
614 Some(
615 global_state.post_count.take().unwrap_or(1)
616 * global_state.pre_count.take().unwrap_or(1),
617 )
618 };
619
620 if global_state.dot_recording {
621 global_state.recorded_count = count;
622 }
623 count
624 }
625
626 pub fn cursor_shape(&self) -> CursorShape {
627 match self.mode {
628 Mode::Normal => {
629 if let Some(operator) = self.operator_stack.last() {
630 match operator {
631 // Navigation operators -> Block cursor
632 Operator::FindForward { .. }
633 | Operator::FindBackward { .. }
634 | Operator::Mark
635 | Operator::Jump { .. }
636 | Operator::Register
637 | Operator::RecordRegister
638 | Operator::ReplayRegister => CursorShape::Block,
639
640 // All other operators -> Underline cursor
641 _ => CursorShape::Underline,
642 }
643 } else {
644 // No operator active -> Block cursor
645 CursorShape::Block
646 }
647 }
648 Mode::Replace => CursorShape::Underline,
649 Mode::HelixNormal | Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
650 CursorShape::Block
651 }
652 Mode::Insert => CursorShape::Bar,
653 }
654 }
655
656 pub fn editor_input_enabled(&self) -> bool {
657 match self.mode {
658 Mode::Insert => {
659 if let Some(operator) = self.operator_stack.last() {
660 !operator.is_waiting(self.mode)
661 } else {
662 true
663 }
664 }
665 Mode::Normal
666 | Mode::HelixNormal
667 | Mode::Replace
668 | Mode::Visual
669 | Mode::VisualLine
670 | Mode::VisualBlock => false,
671 }
672 }
673
674 pub fn should_autoindent(&self) -> bool {
675 !(self.mode == Mode::Insert && self.last_mode == Mode::VisualBlock)
676 }
677
678 pub fn clip_at_line_ends(&self) -> bool {
679 match self.mode {
680 Mode::Insert
681 | Mode::Visual
682 | Mode::VisualLine
683 | Mode::VisualBlock
684 | Mode::Replace
685 | Mode::HelixNormal => false,
686 Mode::Normal => true,
687 }
688 }
689
690 pub fn extend_key_context(&self, context: &mut KeyContext, cx: &AppContext) {
691 let mut mode = match self.mode {
692 Mode::Normal => "normal",
693 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => "visual",
694 Mode::Insert => "insert",
695 Mode::Replace => "replace",
696 Mode::HelixNormal => "helix_normal",
697 }
698 .to_string();
699
700 let mut operator_id = "none";
701
702 let active_operator = self.active_operator();
703 if active_operator.is_none() && cx.global::<VimGlobals>().pre_count.is_some()
704 || active_operator.is_some() && cx.global::<VimGlobals>().post_count.is_some()
705 {
706 context.add("VimCount");
707 }
708
709 if let Some(active_operator) = active_operator {
710 if active_operator.is_waiting(self.mode) {
711 if matches!(active_operator, Operator::Literal { .. }) {
712 mode = "literal".to_string();
713 } else {
714 mode = "waiting".to_string();
715 }
716 } else {
717 operator_id = active_operator.id();
718 mode = "operator".to_string();
719 }
720 }
721
722 if mode == "normal" || mode == "visual" || mode == "operator" {
723 context.add("VimControl");
724 }
725 context.set("vim_mode", mode);
726 context.set("vim_operator", operator_id);
727 }
728
729 fn focused(&mut self, preserve_selection: bool, cx: &mut ViewContext<Self>) {
730 let Some(editor) = self.editor() else {
731 return;
732 };
733 let newest_selection_empty = editor.update(cx, |editor, cx| {
734 editor.selections.newest::<usize>(cx).is_empty()
735 });
736 let editor = editor.read(cx);
737 let editor_mode = editor.mode();
738
739 if editor_mode == EditorMode::Full
740 && !newest_selection_empty
741 && self.mode == Mode::Normal
742 // When following someone, don't switch vim mode.
743 && editor.leader_peer_id().is_none()
744 {
745 if preserve_selection {
746 self.switch_mode(Mode::Visual, true, cx);
747 } else {
748 self.update_editor(cx, |_, editor, cx| {
749 editor.set_clip_at_line_ends(false, cx);
750 editor.change_selections(None, cx, |s| {
751 s.move_with(|_, selection| {
752 selection.collapse_to(selection.start, selection.goal)
753 })
754 });
755 });
756 }
757 }
758
759 cx.emit(VimEvent::Focused);
760 self.sync_vim_settings(cx);
761
762 if VimSettings::get_global(cx).toggle_relative_line_numbers {
763 if let Some(old_vim) = Vim::globals(cx).focused_vim() {
764 if old_vim.entity_id() != cx.view().entity_id() {
765 old_vim.update(cx, |vim, cx| {
766 vim.update_editor(cx, |_, editor, cx| {
767 editor.set_relative_line_number(None, cx)
768 });
769 });
770
771 self.update_editor(cx, |vim, editor, cx| {
772 let is_relative = vim.mode != Mode::Insert;
773 editor.set_relative_line_number(Some(is_relative), cx)
774 });
775 }
776 } else {
777 self.update_editor(cx, |vim, editor, cx| {
778 let is_relative = vim.mode != Mode::Insert;
779 editor.set_relative_line_number(Some(is_relative), cx)
780 });
781 }
782 }
783 Vim::globals(cx).focused_vim = Some(cx.view().downgrade());
784 }
785
786 fn blurred(&mut self, cx: &mut ViewContext<Self>) {
787 self.stop_recording_immediately(NormalBefore.boxed_clone(), cx);
788 self.store_visual_marks(cx);
789 self.clear_operator(cx);
790 self.update_editor(cx, |_, editor, cx| {
791 editor.set_cursor_shape(language::CursorShape::Hollow, cx);
792 });
793 }
794
795 fn cursor_shape_changed(&mut self, cx: &mut ViewContext<Self>) {
796 self.update_editor(cx, |vim, editor, cx| {
797 editor.set_cursor_shape(vim.cursor_shape(), cx);
798 });
799 }
800
801 fn update_editor<S>(
802 &mut self,
803 cx: &mut ViewContext<Self>,
804 update: impl FnOnce(&mut Self, &mut Editor, &mut ViewContext<Editor>) -> S,
805 ) -> Option<S> {
806 let editor = self.editor.upgrade()?;
807 Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
808 }
809
810 fn editor_selections(&mut self, cx: &mut ViewContext<Self>) -> Vec<Range<Anchor>> {
811 self.update_editor(cx, |_, editor, _| {
812 editor
813 .selections
814 .disjoint_anchors()
815 .iter()
816 .map(|selection| selection.tail()..selection.head())
817 .collect()
818 })
819 .unwrap_or_default()
820 }
821
822 /// When doing an action that modifies the buffer, we start recording so that `.`
823 /// will replay the action.
824 pub fn start_recording(&mut self, cx: &mut ViewContext<Self>) {
825 Vim::update_globals(cx, |globals, cx| {
826 if !globals.dot_replaying {
827 globals.dot_recording = true;
828 globals.recording_actions = Default::default();
829 globals.recorded_count = None;
830
831 let selections = self.editor().map(|editor| {
832 editor.update(cx, |editor, cx| {
833 (
834 editor.selections.oldest::<Point>(cx),
835 editor.selections.newest::<Point>(cx),
836 )
837 })
838 });
839
840 if let Some((oldest, newest)) = selections {
841 globals.recorded_selection = match self.mode {
842 Mode::Visual if newest.end.row == newest.start.row => {
843 RecordedSelection::SingleLine {
844 cols: newest.end.column - newest.start.column,
845 }
846 }
847 Mode::Visual => RecordedSelection::Visual {
848 rows: newest.end.row - newest.start.row,
849 cols: newest.end.column,
850 },
851 Mode::VisualLine => RecordedSelection::VisualLine {
852 rows: newest.end.row - newest.start.row,
853 },
854 Mode::VisualBlock => RecordedSelection::VisualBlock {
855 rows: newest.end.row.abs_diff(oldest.start.row),
856 cols: newest.end.column.abs_diff(oldest.start.column),
857 },
858 _ => RecordedSelection::None,
859 }
860 } else {
861 globals.recorded_selection = RecordedSelection::None;
862 }
863 }
864 })
865 }
866
867 pub fn stop_replaying(&mut self, cx: &mut ViewContext<Self>) {
868 let globals = Vim::globals(cx);
869 globals.dot_replaying = false;
870 if let Some(replayer) = globals.replayer.take() {
871 replayer.stop();
872 }
873 }
874
875 /// When finishing an action that modifies the buffer, stop recording.
876 /// as you usually call this within a keystroke handler we also ensure that
877 /// the current action is recorded.
878 pub fn stop_recording(&mut self, cx: &mut ViewContext<Self>) {
879 let globals = Vim::globals(cx);
880 if globals.dot_recording {
881 globals.stop_recording_after_next_action = true;
882 }
883 self.exit_temporary_mode = self.temp_mode;
884 }
885
886 /// Stops recording actions immediately rather than waiting until after the
887 /// next action to stop recording.
888 ///
889 /// This doesn't include the current action.
890 pub fn stop_recording_immediately(
891 &mut self,
892 action: Box<dyn Action>,
893 cx: &mut ViewContext<Self>,
894 ) {
895 let globals = Vim::globals(cx);
896 if globals.dot_recording {
897 globals
898 .recording_actions
899 .push(ReplayableAction::Action(action.boxed_clone()));
900 globals.recorded_actions = mem::take(&mut globals.recording_actions);
901 globals.dot_recording = false;
902 globals.stop_recording_after_next_action = false;
903 }
904 self.exit_temporary_mode = self.temp_mode;
905 }
906
907 /// Explicitly record one action (equivalents to start_recording and stop_recording)
908 pub fn record_current_action(&mut self, cx: &mut ViewContext<Self>) {
909 self.start_recording(cx);
910 self.stop_recording(cx);
911 }
912
913 fn push_count_digit(&mut self, number: usize, cx: &mut ViewContext<Self>) {
914 if self.active_operator().is_some() {
915 let post_count = Vim::globals(cx).post_count.unwrap_or(0);
916
917 Vim::globals(cx).post_count = Some(
918 post_count
919 .checked_mul(10)
920 .and_then(|post_count| post_count.checked_add(number))
921 .unwrap_or(post_count),
922 )
923 } else {
924 let pre_count = Vim::globals(cx).pre_count.unwrap_or(0);
925
926 Vim::globals(cx).pre_count = Some(
927 pre_count
928 .checked_mul(10)
929 .and_then(|pre_count| pre_count.checked_add(number))
930 .unwrap_or(pre_count),
931 )
932 }
933 // update the keymap so that 0 works
934 self.sync_vim_settings(cx)
935 }
936
937 fn select_register(&mut self, register: Arc<str>, cx: &mut ViewContext<Self>) {
938 if register.chars().count() == 1 {
939 self.selected_register
940 .replace(register.chars().next().unwrap());
941 }
942 self.operator_stack.clear();
943 self.sync_vim_settings(cx);
944 }
945
946 fn maybe_pop_operator(&mut self) -> Option<Operator> {
947 self.operator_stack.pop()
948 }
949
950 fn pop_operator(&mut self, cx: &mut ViewContext<Self>) -> Operator {
951 let popped_operator = self.operator_stack.pop()
952 .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
953 self.sync_vim_settings(cx);
954 popped_operator
955 }
956
957 fn clear_operator(&mut self, cx: &mut ViewContext<Self>) {
958 Vim::take_count(cx);
959 self.selected_register.take();
960 self.operator_stack.clear();
961 self.sync_vim_settings(cx);
962 }
963
964 fn active_operator(&self) -> Option<Operator> {
965 self.operator_stack.last().cloned()
966 }
967
968 fn transaction_begun(&mut self, transaction_id: TransactionId, _: &mut ViewContext<Self>) {
969 let mode = if (self.mode == Mode::Insert
970 || self.mode == Mode::Replace
971 || self.mode == Mode::Normal)
972 && self.current_tx.is_none()
973 {
974 self.current_tx = Some(transaction_id);
975 self.last_mode
976 } else {
977 self.mode
978 };
979 if mode == Mode::VisualLine || mode == Mode::VisualBlock {
980 self.undo_modes.insert(transaction_id, mode);
981 }
982 }
983
984 fn transaction_undone(&mut self, transaction_id: &TransactionId, cx: &mut ViewContext<Self>) {
985 match self.mode {
986 Mode::VisualLine | Mode::VisualBlock | Mode::Visual => {
987 self.update_editor(cx, |vim, editor, cx| {
988 let original_mode = vim.undo_modes.get(transaction_id);
989 editor.change_selections(None, cx, |s| match original_mode {
990 Some(Mode::VisualLine) => {
991 s.move_with(|map, selection| {
992 selection.collapse_to(
993 map.prev_line_boundary(selection.start.to_point(map)).1,
994 SelectionGoal::None,
995 )
996 });
997 }
998 Some(Mode::VisualBlock) => {
999 let mut first = s.first_anchor();
1000 first.collapse_to(first.start, first.goal);
1001 s.select_anchors(vec![first]);
1002 }
1003 _ => {
1004 s.move_with(|map, selection| {
1005 selection.collapse_to(
1006 map.clip_at_line_end(selection.start),
1007 selection.goal,
1008 );
1009 });
1010 }
1011 });
1012 });
1013 self.switch_mode(Mode::Normal, true, cx)
1014 }
1015 Mode::Normal => {
1016 self.update_editor(cx, |_, editor, cx| {
1017 editor.change_selections(None, cx, |s| {
1018 s.move_with(|map, selection| {
1019 selection
1020 .collapse_to(map.clip_at_line_end(selection.end), selection.goal)
1021 })
1022 })
1023 });
1024 }
1025 Mode::Insert | Mode::Replace | Mode::HelixNormal => {}
1026 }
1027 }
1028
1029 fn local_selections_changed(&mut self, cx: &mut ViewContext<Self>) {
1030 let Some(editor) = self.editor() else { return };
1031
1032 if editor.read(cx).leader_peer_id().is_some() {
1033 return;
1034 }
1035
1036 let newest = editor.read(cx).selections.newest_anchor().clone();
1037 let is_multicursor = editor.read(cx).selections.count() > 1;
1038 if self.mode == Mode::Insert && self.current_tx.is_some() {
1039 if self.current_anchor.is_none() {
1040 self.current_anchor = Some(newest);
1041 } else if self.current_anchor.as_ref().unwrap() != &newest {
1042 if let Some(tx_id) = self.current_tx.take() {
1043 self.update_editor(cx, |_, editor, cx| {
1044 editor.group_until_transaction(tx_id, cx)
1045 });
1046 }
1047 }
1048 } else if self.mode == Mode::Normal && newest.start != newest.end {
1049 if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
1050 self.switch_mode(Mode::VisualBlock, false, cx);
1051 } else {
1052 self.switch_mode(Mode::Visual, false, cx)
1053 }
1054 } else if newest.start == newest.end
1055 && !is_multicursor
1056 && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&self.mode)
1057 {
1058 self.switch_mode(Mode::Normal, true, cx);
1059 }
1060 }
1061
1062 fn input_ignored(&mut self, text: Arc<str>, cx: &mut ViewContext<Self>) {
1063 if text.is_empty() {
1064 return;
1065 }
1066
1067 match self.active_operator() {
1068 Some(Operator::FindForward { before }) => {
1069 let find = Motion::FindForward {
1070 before,
1071 char: text.chars().next().unwrap(),
1072 mode: if VimSettings::get_global(cx).use_multiline_find {
1073 FindRange::MultiLine
1074 } else {
1075 FindRange::SingleLine
1076 },
1077 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1078 };
1079 Vim::globals(cx).last_find = Some(find.clone());
1080 self.motion(find, cx)
1081 }
1082 Some(Operator::FindBackward { after }) => {
1083 let find = Motion::FindBackward {
1084 after,
1085 char: text.chars().next().unwrap(),
1086 mode: if VimSettings::get_global(cx).use_multiline_find {
1087 FindRange::MultiLine
1088 } else {
1089 FindRange::SingleLine
1090 },
1091 smartcase: VimSettings::get_global(cx).use_smartcase_find,
1092 };
1093 Vim::globals(cx).last_find = Some(find.clone());
1094 self.motion(find, cx)
1095 }
1096 Some(Operator::Replace) => match self.mode {
1097 Mode::Normal => self.normal_replace(text, cx),
1098 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1099 self.visual_replace(text, cx)
1100 }
1101 _ => self.clear_operator(cx),
1102 },
1103 Some(Operator::Digraph { first_char }) => {
1104 if let Some(first_char) = first_char {
1105 if let Some(second_char) = text.chars().next() {
1106 self.insert_digraph(first_char, second_char, cx);
1107 }
1108 } else {
1109 let first_char = text.chars().next();
1110 self.pop_operator(cx);
1111 self.push_operator(Operator::Digraph { first_char }, cx);
1112 }
1113 }
1114 Some(Operator::Literal { prefix }) => {
1115 self.handle_literal_input(prefix.unwrap_or_default(), &text, cx)
1116 }
1117 Some(Operator::AddSurrounds { target }) => match self.mode {
1118 Mode::Normal => {
1119 if let Some(target) = target {
1120 self.add_surrounds(text, target, cx);
1121 self.clear_operator(cx);
1122 }
1123 }
1124 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
1125 self.add_surrounds(text, SurroundsType::Selection, cx);
1126 self.clear_operator(cx);
1127 }
1128 _ => self.clear_operator(cx),
1129 },
1130 Some(Operator::ChangeSurrounds { target }) => match self.mode {
1131 Mode::Normal => {
1132 if let Some(target) = target {
1133 self.change_surrounds(text, target, cx);
1134 self.clear_operator(cx);
1135 }
1136 }
1137 _ => self.clear_operator(cx),
1138 },
1139 Some(Operator::DeleteSurrounds) => match self.mode {
1140 Mode::Normal => {
1141 self.delete_surrounds(text, cx);
1142 self.clear_operator(cx);
1143 }
1144 _ => self.clear_operator(cx),
1145 },
1146 Some(Operator::Mark) => self.create_mark(text, false, cx),
1147 Some(Operator::RecordRegister) => {
1148 self.record_register(text.chars().next().unwrap(), cx)
1149 }
1150 Some(Operator::ReplayRegister) => {
1151 self.replay_register(text.chars().next().unwrap(), cx)
1152 }
1153 Some(Operator::Register) => match self.mode {
1154 Mode::Insert => {
1155 self.update_editor(cx, |_, editor, cx| {
1156 if let Some(register) = Vim::update_globals(cx, |globals, cx| {
1157 globals.read_register(text.chars().next(), Some(editor), cx)
1158 }) {
1159 editor.do_paste(
1160 ®ister.text.to_string(),
1161 register.clipboard_selections.clone(),
1162 false,
1163 cx,
1164 )
1165 }
1166 });
1167 self.clear_operator(cx);
1168 }
1169 _ => {
1170 self.select_register(text, cx);
1171 }
1172 },
1173 Some(Operator::Jump { line }) => self.jump(text, line, cx),
1174 _ => {
1175 if self.mode == Mode::Replace {
1176 self.multi_replace(text, cx)
1177 }
1178
1179 if self.mode == Mode::Normal {
1180 self.update_editor(cx, |_, editor, cx| {
1181 editor.accept_inline_completion(
1182 &editor::actions::AcceptInlineCompletion {},
1183 cx,
1184 );
1185 });
1186 }
1187 }
1188 }
1189 }
1190
1191 fn sync_vim_settings(&mut self, cx: &mut ViewContext<Self>) {
1192 self.update_editor(cx, |vim, editor, cx| {
1193 editor.set_cursor_shape(vim.cursor_shape(), cx);
1194 editor.set_clip_at_line_ends(vim.clip_at_line_ends(), cx);
1195 editor.set_collapse_matches(true);
1196 editor.set_input_enabled(vim.editor_input_enabled());
1197 editor.set_autoindent(vim.should_autoindent());
1198 editor.selections.line_mode = matches!(vim.mode, Mode::VisualLine);
1199
1200 let enable_inline_completions = match vim.mode {
1201 Mode::Insert | Mode::Replace => true,
1202 Mode::Normal => editor
1203 .inline_completion_provider()
1204 .map_or(false, |provider| provider.show_completions_in_normal_mode()),
1205 _ => false,
1206 };
1207 editor.set_inline_completions_enabled(enable_inline_completions, cx);
1208 });
1209 cx.notify()
1210 }
1211}
1212
1213/// Controls when to use system clipboard.
1214#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
1215#[serde(rename_all = "snake_case")]
1216pub enum UseSystemClipboard {
1217 /// Don't use system clipboard.
1218 Never,
1219 /// Use system clipboard.
1220 Always,
1221 /// Use system clipboard for yank operations.
1222 OnYank,
1223}
1224
1225#[derive(Deserialize)]
1226struct VimSettings {
1227 pub toggle_relative_line_numbers: bool,
1228 pub use_system_clipboard: UseSystemClipboard,
1229 pub use_multiline_find: bool,
1230 pub use_smartcase_find: bool,
1231 pub custom_digraphs: HashMap<String, Arc<str>>,
1232 pub highlight_on_yank_duration: u64,
1233}
1234
1235#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
1236struct VimSettingsContent {
1237 pub toggle_relative_line_numbers: Option<bool>,
1238 pub use_system_clipboard: Option<UseSystemClipboard>,
1239 pub use_multiline_find: Option<bool>,
1240 pub use_smartcase_find: Option<bool>,
1241 pub custom_digraphs: Option<HashMap<String, Arc<str>>>,
1242 pub highlight_on_yank_duration: Option<u64>,
1243}
1244
1245impl Settings for VimSettings {
1246 const KEY: Option<&'static str> = Some("vim");
1247
1248 type FileContent = VimSettingsContent;
1249
1250 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1251 sources.json_merge()
1252 }
1253}