1//! Vim support for Zed.
2
3#[cfg(test)]
4mod test;
5
6mod change_list;
7mod command;
8mod editor_events;
9mod insert;
10mod mode_indicator;
11mod motion;
12mod normal;
13mod object;
14mod replace;
15mod state;
16mod surrounds;
17mod visual;
18
19use anyhow::Result;
20use change_list::push_to_change_list;
21use collections::HashMap;
22use command_palette_hooks::{CommandPaletteFilter, CommandPaletteInterceptor};
23use editor::{
24 movement::{self, FindRange},
25 Anchor, Bias, Editor, EditorEvent, EditorMode, ToPoint,
26};
27use gpui::{
28 actions, impl_actions, Action, AppContext, EntityId, FocusableView, Global, KeystrokeEvent,
29 Subscription, UpdateGlobal, View, ViewContext, WeakView, WindowContext,
30};
31use language::{CursorShape, Point, SelectionGoal, TransactionId};
32pub use mode_indicator::ModeIndicator;
33use motion::Motion;
34use normal::{
35 mark::{create_mark, create_mark_after, create_mark_before},
36 normal_replace,
37};
38use replace::multi_replace;
39use schemars::JsonSchema;
40use serde::Deserialize;
41use serde_derive::Serialize;
42use settings::{update_settings_file, Settings, SettingsSources, SettingsStore};
43use state::{EditorState, Mode, Operator, RecordedSelection, Register, WorkspaceState};
44use std::{ops::Range, sync::Arc};
45use surrounds::{add_surrounds, change_surrounds, delete_surrounds};
46use ui::BorrowAppContext;
47use visual::{visual_block_motion, visual_replace};
48use workspace::{self, Workspace};
49
50use crate::state::ReplayableAction;
51
52/// Whether or not to enable Vim mode (work in progress).
53///
54/// Default: false
55pub struct VimModeSetting(pub bool);
56
57/// An Action to Switch between modes
58#[derive(Clone, Deserialize, PartialEq)]
59pub struct SwitchMode(pub Mode);
60
61/// PushOperator is used to put vim into a "minor" mode,
62/// where it's waiting for a specific next set of keystrokes.
63/// For example 'd' needs a motion to complete.
64#[derive(Clone, Deserialize, PartialEq)]
65pub struct PushOperator(pub Operator);
66
67/// Number is used to manage vim's count. Pushing a digit
68/// multiplis the current value by 10 and adds the digit.
69#[derive(Clone, Deserialize, PartialEq)]
70struct Number(usize);
71
72#[derive(Clone, Deserialize, PartialEq)]
73struct SelectRegister(String);
74
75actions!(
76 vim,
77 [
78 Tab,
79 Enter,
80 Object,
81 InnerObject,
82 FindForward,
83 FindBackward,
84 OpenDefaultKeymap
85 ]
86);
87
88// in the workspace namespace so it's not filtered out when vim is disabled.
89actions!(workspace, [ToggleVimMode]);
90
91impl_actions!(vim, [SwitchMode, PushOperator, Number, SelectRegister]);
92
93/// Initializes the `vim` crate.
94pub fn init(cx: &mut AppContext) {
95 cx.set_global(Vim::default());
96 VimModeSetting::register(cx);
97 VimSettings::register(cx);
98
99 cx.observe_keystrokes(observe_keystrokes).detach();
100 editor_events::init(cx);
101
102 cx.observe_new_views(|workspace: &mut Workspace, cx| register(workspace, cx))
103 .detach();
104
105 // Any time settings change, update vim mode to match. The Vim struct
106 // will be initialized as disabled by default, so we filter its commands
107 // out when starting up.
108 CommandPaletteFilter::update_global(cx, |filter, _| {
109 filter.hide_namespace(Vim::NAMESPACE);
110 });
111 Vim::update_global(cx, |vim, cx| {
112 vim.set_enabled(VimModeSetting::get_global(cx).0, cx)
113 });
114 cx.observe_global::<SettingsStore>(|cx| {
115 Vim::update_global(cx, |vim, cx| {
116 vim.set_enabled(VimModeSetting::get_global(cx).0, cx)
117 });
118 })
119 .detach();
120}
121
122fn register(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
123 workspace.register_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {
124 Vim::update(cx, |vim, cx| vim.switch_mode(mode, false, cx))
125 });
126 workspace.register_action(
127 |_: &mut Workspace, PushOperator(operator): &PushOperator, cx| {
128 Vim::update(cx, |vim, cx| vim.push_operator(operator.clone(), cx))
129 },
130 );
131 workspace.register_action(|_: &mut Workspace, n: &Number, cx: _| {
132 Vim::update(cx, |vim, cx| vim.push_count_digit(n.0, cx));
133 });
134 workspace.register_action(|_: &mut Workspace, _: &Tab, cx| {
135 Vim::active_editor_input_ignored(" ".into(), cx)
136 });
137
138 workspace.register_action(|_: &mut Workspace, _: &Enter, cx| {
139 Vim::active_editor_input_ignored("\n".into(), cx)
140 });
141
142 workspace.register_action(|workspace: &mut Workspace, _: &ToggleVimMode, cx| {
143 let fs = workspace.app_state().fs.clone();
144 let currently_enabled = VimModeSetting::get_global(cx).0;
145 update_settings_file::<VimModeSetting>(fs, cx, move |setting| {
146 *setting = Some(!currently_enabled)
147 })
148 });
149
150 workspace.register_action(|_: &mut Workspace, _: &OpenDefaultKeymap, cx| {
151 cx.emit(workspace::Event::OpenBundledFile {
152 text: settings::vim_keymap(),
153 title: "Default Vim Bindings",
154 language: "JSON",
155 });
156 });
157
158 normal::register(workspace, cx);
159 insert::register(workspace, cx);
160 motion::register(workspace, cx);
161 command::register(workspace, cx);
162 replace::register(workspace, cx);
163 object::register(workspace, cx);
164 visual::register(workspace, cx);
165 change_list::register(workspace, cx);
166}
167
168/// Called whenever an keystroke is typed so vim can observe all actions
169/// and keystrokes accordingly.
170fn observe_keystrokes(keystroke_event: &KeystrokeEvent, cx: &mut WindowContext) {
171 if let Some(action) = keystroke_event
172 .action
173 .as_ref()
174 .map(|action| action.boxed_clone())
175 {
176 Vim::update(cx, |vim, _| {
177 if vim.workspace_state.recording {
178 vim.workspace_state
179 .recorded_actions
180 .push(ReplayableAction::Action(action.boxed_clone()));
181
182 if vim.workspace_state.stop_recording_after_next_action {
183 vim.workspace_state.recording = false;
184 vim.workspace_state.stop_recording_after_next_action = false;
185 }
186 }
187 });
188
189 // Keystroke is handled by the vim system, so continue forward
190 if action.name().starts_with("vim::") {
191 return;
192 }
193 } else if cx.has_pending_keystrokes() {
194 return;
195 }
196
197 Vim::update(cx, |vim, cx| match vim.active_operator() {
198 Some(
199 Operator::FindForward { .. }
200 | Operator::FindBackward { .. }
201 | Operator::Replace
202 | Operator::AddSurrounds { .. }
203 | Operator::ChangeSurrounds { .. }
204 | Operator::DeleteSurrounds
205 | Operator::Mark
206 | Operator::Jump { .. }
207 | Operator::Register,
208 ) => {}
209 Some(_) => {
210 vim.clear_operator(cx);
211 }
212 _ => {}
213 });
214}
215
216/// The state pertaining to Vim mode.
217#[derive(Default)]
218struct Vim {
219 active_editor: Option<WeakView<Editor>>,
220 editor_subscription: Option<Subscription>,
221 enabled: bool,
222 editor_states: HashMap<EntityId, EditorState>,
223 workspace_state: WorkspaceState,
224 default_state: EditorState,
225}
226
227impl Global for Vim {}
228
229impl Vim {
230 /// The namespace for Vim actions.
231 const NAMESPACE: &'static str = "vim";
232
233 fn read(cx: &mut AppContext) -> &Self {
234 cx.global::<Self>()
235 }
236
237 fn update<F, S>(cx: &mut WindowContext, update: F) -> S
238 where
239 F: FnOnce(&mut Self, &mut WindowContext) -> S,
240 {
241 cx.update_global(update)
242 }
243
244 fn activate_editor(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
245 if !editor.read(cx).use_modal_editing() {
246 return;
247 }
248
249 self.active_editor = Some(editor.clone().downgrade());
250 self.editor_subscription = Some(cx.subscribe(&editor, |editor, event, cx| match event {
251 EditorEvent::SelectionsChanged { local: true } => {
252 if editor.read(cx).leader_peer_id().is_none() {
253 Vim::update(cx, |vim, cx| {
254 vim.local_selections_changed(editor, cx);
255 })
256 }
257 }
258 EditorEvent::InputIgnored { text } => {
259 Vim::active_editor_input_ignored(text.clone(), cx);
260 Vim::record_insertion(text, None, cx)
261 }
262 EditorEvent::InputHandled {
263 text,
264 utf16_range_to_replace: range_to_replace,
265 } => Vim::record_insertion(text, range_to_replace.clone(), cx),
266 EditorEvent::TransactionBegun { transaction_id } => Vim::update(cx, |vim, cx| {
267 vim.transaction_begun(*transaction_id, cx);
268 }),
269 EditorEvent::TransactionUndone { transaction_id } => Vim::update(cx, |vim, cx| {
270 vim.transaction_undone(transaction_id, cx);
271 }),
272 EditorEvent::Edited { .. } => {
273 Vim::update(cx, |vim, cx| vim.transaction_ended(editor, cx))
274 }
275 _ => {}
276 }));
277
278 let editor = editor.read(cx);
279 let editor_mode = editor.mode();
280 let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
281
282 if editor_mode == EditorMode::Full
283 && !newest_selection_empty
284 && self.state().mode == Mode::Normal
285 // When following someone, don't switch vim mode.
286 && editor.leader_peer_id().is_none()
287 {
288 self.switch_mode(Mode::Visual, true, cx);
289 }
290
291 self.sync_vim_settings(cx);
292 }
293
294 fn record_insertion(
295 text: &Arc<str>,
296 range_to_replace: Option<Range<isize>>,
297 cx: &mut WindowContext,
298 ) {
299 Vim::update(cx, |vim, _| {
300 if vim.workspace_state.recording {
301 vim.workspace_state
302 .recorded_actions
303 .push(ReplayableAction::Insertion {
304 text: text.clone(),
305 utf16_range_to_replace: range_to_replace,
306 });
307 if vim.workspace_state.stop_recording_after_next_action {
308 vim.workspace_state.recording = false;
309 vim.workspace_state.stop_recording_after_next_action = false;
310 }
311 }
312 });
313 }
314
315 fn update_active_editor<S>(
316 &mut self,
317 cx: &mut WindowContext,
318 update: impl FnOnce(&mut Vim, &mut Editor, &mut ViewContext<Editor>) -> S,
319 ) -> Option<S> {
320 let editor = self.active_editor.clone()?.upgrade()?;
321 Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
322 }
323
324 fn editor_selections(&mut self, cx: &mut WindowContext) -> Vec<Range<Anchor>> {
325 self.update_active_editor(cx, |_, editor, _| {
326 editor
327 .selections
328 .disjoint_anchors()
329 .iter()
330 .map(|selection| selection.tail()..selection.head())
331 .collect()
332 })
333 .unwrap_or_default()
334 }
335
336 /// When doing an action that modifies the buffer, we start recording so that `.`
337 /// will replay the action.
338 pub fn start_recording(&mut self, cx: &mut WindowContext) {
339 if !self.workspace_state.replaying {
340 self.workspace_state.recording = true;
341 self.workspace_state.recorded_actions = Default::default();
342 self.workspace_state.recorded_count = None;
343
344 let selections = self
345 .active_editor
346 .as_ref()
347 .and_then(|editor| editor.upgrade())
348 .map(|editor| {
349 let editor = editor.read(cx);
350 (
351 editor.selections.oldest::<Point>(cx),
352 editor.selections.newest::<Point>(cx),
353 )
354 });
355
356 if let Some((oldest, newest)) = selections {
357 self.workspace_state.recorded_selection = match self.state().mode {
358 Mode::Visual if newest.end.row == newest.start.row => {
359 RecordedSelection::SingleLine {
360 cols: newest.end.column - newest.start.column,
361 }
362 }
363 Mode::Visual => RecordedSelection::Visual {
364 rows: newest.end.row - newest.start.row,
365 cols: newest.end.column,
366 },
367 Mode::VisualLine => RecordedSelection::VisualLine {
368 rows: newest.end.row - newest.start.row,
369 },
370 Mode::VisualBlock => RecordedSelection::VisualBlock {
371 rows: newest.end.row.abs_diff(oldest.start.row),
372 cols: newest.end.column.abs_diff(oldest.start.column),
373 },
374 _ => RecordedSelection::None,
375 }
376 } else {
377 self.workspace_state.recorded_selection = RecordedSelection::None;
378 }
379 }
380 }
381
382 pub fn stop_replaying(&mut self) {
383 self.workspace_state.replaying = false;
384 }
385
386 /// When finishing an action that modifies the buffer, stop recording.
387 /// as you usually call this within a keystroke handler we also ensure that
388 /// the current action is recorded.
389 pub fn stop_recording(&mut self) {
390 if self.workspace_state.recording {
391 self.workspace_state.stop_recording_after_next_action = true;
392 }
393 }
394
395 /// Stops recording actions immediately rather than waiting until after the
396 /// next action to stop recording.
397 ///
398 /// This doesn't include the current action.
399 pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>) {
400 if self.workspace_state.recording {
401 self.workspace_state
402 .recorded_actions
403 .push(ReplayableAction::Action(action.boxed_clone()));
404 self.workspace_state.recording = false;
405 self.workspace_state.stop_recording_after_next_action = false;
406 }
407 }
408
409 /// Explicitly record one action (equivalents to start_recording and stop_recording)
410 pub fn record_current_action(&mut self, cx: &mut WindowContext) {
411 self.start_recording(cx);
412 self.stop_recording();
413 }
414
415 fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut WindowContext) {
416 let state = self.state();
417 let last_mode = state.mode;
418 let prior_mode = state.last_mode;
419 let prior_tx = state.current_tx;
420 self.update_state(|state| {
421 state.last_mode = last_mode;
422 state.mode = mode;
423 state.operator_stack.clear();
424 state.current_tx.take();
425 state.current_anchor.take();
426 });
427 if mode != Mode::Insert {
428 self.take_count(cx);
429 }
430
431 // Sync editor settings like clip mode
432 self.sync_vim_settings(cx);
433
434 if mode != Mode::Insert && last_mode == Mode::Insert {
435 create_mark_after(self, "^".into(), cx)
436 }
437
438 if leave_selections {
439 return;
440 }
441
442 // Adjust selections
443 self.update_active_editor(cx, |_, editor, cx| {
444 if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
445 {
446 visual_block_motion(true, editor, cx, |_, point, goal| Some((point, goal)))
447 }
448 if last_mode == Mode::Insert || last_mode == Mode::Replace {
449 if let Some(prior_tx) = prior_tx {
450 editor.group_until_transaction(prior_tx, cx)
451 }
452 }
453
454 editor.change_selections(None, cx, |s| {
455 // we cheat with visual block mode and use multiple cursors.
456 // the cost of this cheat is we need to convert back to a single
457 // cursor whenever vim would.
458 if last_mode == Mode::VisualBlock
459 && (mode != Mode::VisualBlock && mode != Mode::Insert)
460 {
461 let tail = s.oldest_anchor().tail();
462 let head = s.newest_anchor().head();
463 s.select_anchor_ranges(vec![tail..head]);
464 } else if last_mode == Mode::Insert
465 && prior_mode == Mode::VisualBlock
466 && mode != Mode::VisualBlock
467 {
468 let pos = s.first_anchor().head();
469 s.select_anchor_ranges(vec![pos..pos])
470 }
471
472 let snapshot = s.display_map();
473 if let Some(pending) = s.pending.as_mut() {
474 if pending.selection.reversed && mode.is_visual() && !last_mode.is_visual() {
475 let mut end = pending.selection.end.to_point(&snapshot.buffer_snapshot);
476 end = snapshot
477 .buffer_snapshot
478 .clip_point(end + Point::new(0, 1), Bias::Right);
479 pending.selection.end = snapshot.buffer_snapshot.anchor_before(end);
480 }
481 }
482
483 s.move_with(|map, selection| {
484 if last_mode.is_visual() && !mode.is_visual() {
485 let mut point = selection.head();
486 if !selection.reversed && !selection.is_empty() {
487 point = movement::left(map, selection.head());
488 }
489 selection.collapse_to(point, selection.goal)
490 } else if !last_mode.is_visual() && mode.is_visual() {
491 if selection.is_empty() {
492 selection.end = movement::right(map, selection.start);
493 }
494 } else if last_mode == Mode::Replace {
495 if selection.head().column() != 0 {
496 let point = movement::left(map, selection.head());
497 selection.collapse_to(point, selection.goal)
498 }
499 }
500 });
501 })
502 });
503 }
504
505 fn push_count_digit(&mut self, number: usize, cx: &mut WindowContext) {
506 if self.active_operator().is_some() {
507 self.update_state(|state| {
508 state.post_count = Some(state.post_count.unwrap_or(0) * 10 + number)
509 })
510 } else {
511 self.update_state(|state| {
512 state.pre_count = Some(state.pre_count.unwrap_or(0) * 10 + number)
513 })
514 }
515 // update the keymap so that 0 works
516 self.sync_vim_settings(cx)
517 }
518
519 fn take_count(&mut self, cx: &mut WindowContext) -> Option<usize> {
520 if self.workspace_state.replaying {
521 return self.workspace_state.recorded_count;
522 }
523
524 let count = if self.state().post_count == None && self.state().pre_count == None {
525 return None;
526 } else {
527 Some(self.update_state(|state| {
528 state.post_count.take().unwrap_or(1) * state.pre_count.take().unwrap_or(1)
529 }))
530 };
531 if self.workspace_state.recording {
532 self.workspace_state.recorded_count = count;
533 }
534 self.sync_vim_settings(cx);
535 count
536 }
537
538 fn select_register(&mut self, register: Arc<str>, cx: &mut WindowContext) {
539 self.update_state(|state| {
540 if register.chars().count() == 1 {
541 state
542 .selected_register
543 .replace(register.chars().next().unwrap());
544 }
545 state.operator_stack.clear();
546 });
547 self.sync_vim_settings(cx);
548 }
549
550 fn write_registers(
551 &mut self,
552 content: Register,
553 register: Option<char>,
554 is_yank: bool,
555 linewise: bool,
556 cx: &mut ViewContext<Editor>,
557 ) {
558 if let Some(register) = register {
559 let lower = register.to_lowercase().next().unwrap_or(register);
560 if lower != register {
561 let current = self.workspace_state.registers.entry(lower).or_default();
562 current.text = (current.text.to_string() + &content.text).into();
563 // not clear how to support appending to registers with multiple cursors
564 current.clipboard_selections.take();
565 let yanked = current.clone();
566 self.workspace_state.registers.insert('"', yanked);
567 } else {
568 self.workspace_state.registers.insert('"', content.clone());
569 match lower {
570 '_' | ':' | '.' | '%' | '#' | '=' | '/' => {}
571 '+' => {
572 cx.write_to_clipboard(content.into());
573 }
574 '*' => {
575 #[cfg(target_os = "linux")]
576 cx.write_to_primary(content.into());
577 #[cfg(not(target_os = "linux"))]
578 cx.write_to_clipboard(content.into());
579 }
580 '"' => {
581 self.workspace_state.registers.insert('0', content.clone());
582 self.workspace_state.registers.insert('"', content);
583 }
584 _ => {
585 self.workspace_state.registers.insert(lower, content);
586 }
587 }
588 }
589 } else {
590 let setting = VimSettings::get_global(cx).use_system_clipboard;
591 if setting == UseSystemClipboard::Always
592 || setting == UseSystemClipboard::OnYank && is_yank
593 {
594 self.workspace_state.last_yank.replace(content.text.clone());
595 cx.write_to_clipboard(content.clone().into());
596 } else {
597 self.workspace_state.last_yank = cx
598 .read_from_clipboard()
599 .map(|item| item.text().to_owned().into());
600 }
601
602 self.workspace_state.registers.insert('"', content.clone());
603 if is_yank {
604 self.workspace_state.registers.insert('0', content);
605 } else {
606 let contains_newline = content.text.contains('\n');
607 if !contains_newline {
608 self.workspace_state.registers.insert('-', content.clone());
609 }
610 if linewise || contains_newline {
611 let mut content = content;
612 for i in '1'..'8' {
613 if let Some(moved) = self.workspace_state.registers.insert(i, content) {
614 content = moved;
615 } else {
616 break;
617 }
618 }
619 }
620 }
621 }
622 }
623
624 fn read_register(
625 &mut self,
626 register: Option<char>,
627 editor: Option<&mut Editor>,
628 cx: &mut WindowContext,
629 ) -> Option<Register> {
630 let Some(register) = register else {
631 let setting = VimSettings::get_global(cx).use_system_clipboard;
632 return match setting {
633 UseSystemClipboard::Always => cx.read_from_clipboard().map(|item| item.into()),
634 UseSystemClipboard::OnYank if self.system_clipboard_is_newer(cx) => {
635 cx.read_from_clipboard().map(|item| item.into())
636 }
637 _ => self.workspace_state.registers.get(&'"').cloned(),
638 };
639 };
640 let lower = register.to_lowercase().next().unwrap_or(register);
641 match lower {
642 '_' | ':' | '.' | '#' | '=' => None,
643 '+' => cx.read_from_clipboard().map(|item| item.into()),
644 '*' => {
645 #[cfg(target_os = "linux")]
646 {
647 cx.read_from_primary().map(|item| item.into())
648 }
649 #[cfg(not(target_os = "linux"))]
650 {
651 cx.read_from_clipboard().map(|item| item.into())
652 }
653 }
654 '%' => editor.and_then(|editor| {
655 let selection = editor.selections.newest::<Point>(cx);
656 if let Some((_, buffer, _)) = editor
657 .buffer()
658 .read(cx)
659 .excerpt_containing(selection.head(), cx)
660 {
661 buffer
662 .read(cx)
663 .file()
664 .map(|file| file.path().to_string_lossy().to_string().into())
665 } else {
666 None
667 }
668 }),
669 _ => self.workspace_state.registers.get(&lower).cloned(),
670 }
671 }
672
673 fn system_clipboard_is_newer(&self, cx: &mut AppContext) -> bool {
674 cx.read_from_clipboard().is_some_and(|item| {
675 if let Some(last_state) = &self.workspace_state.last_yank {
676 last_state != item.text()
677 } else {
678 true
679 }
680 })
681 }
682
683 fn push_operator(&mut self, operator: Operator, cx: &mut WindowContext) {
684 if matches!(
685 operator,
686 Operator::Change
687 | Operator::Delete
688 | Operator::Replace
689 | Operator::Indent
690 | Operator::Outdent
691 | Operator::Lowercase
692 | Operator::Uppercase
693 | Operator::OppositeCase
694 ) {
695 self.start_recording(cx)
696 };
697 // Since these operations can only be entered with pre-operators,
698 // we need to clear the previous operators when pushing,
699 // so that the current stack is the most correct
700 if matches!(
701 operator,
702 Operator::AddSurrounds { .. }
703 | Operator::ChangeSurrounds { .. }
704 | Operator::DeleteSurrounds
705 ) {
706 self.update_state(|state| state.operator_stack.clear());
707 };
708 self.update_state(|state| state.operator_stack.push(operator));
709 self.sync_vim_settings(cx);
710 }
711
712 fn maybe_pop_operator(&mut self) -> Option<Operator> {
713 self.update_state(|state| state.operator_stack.pop())
714 }
715
716 fn pop_operator(&mut self, cx: &mut WindowContext) -> Operator {
717 let popped_operator = self.update_state(|state| state.operator_stack.pop())
718 .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
719 self.sync_vim_settings(cx);
720 popped_operator
721 }
722
723 fn clear_operator(&mut self, cx: &mut WindowContext) {
724 self.take_count(cx);
725 self.update_state(|state| {
726 state.selected_register.take();
727 state.operator_stack.clear()
728 });
729 self.sync_vim_settings(cx);
730 }
731
732 fn active_operator(&self) -> Option<Operator> {
733 self.state().operator_stack.last().cloned()
734 }
735
736 fn transaction_begun(&mut self, transaction_id: TransactionId, _: &mut WindowContext) {
737 self.update_state(|state| {
738 let mode = if (state.mode == Mode::Insert
739 || state.mode == Mode::Replace
740 || state.mode == Mode::Normal)
741 && state.current_tx.is_none()
742 {
743 state.current_tx = Some(transaction_id);
744 state.last_mode
745 } else {
746 state.mode
747 };
748 if mode == Mode::VisualLine || mode == Mode::VisualBlock {
749 state.undo_modes.insert(transaction_id, mode);
750 }
751 });
752 }
753
754 fn transaction_undone(&mut self, transaction_id: &TransactionId, cx: &mut WindowContext) {
755 if !self.state().mode.is_visual() {
756 return;
757 };
758 self.update_active_editor(cx, |vim, editor, cx| {
759 let original_mode = vim.state().undo_modes.get(transaction_id);
760 editor.change_selections(None, cx, |s| match original_mode {
761 Some(Mode::VisualLine) => {
762 s.move_with(|map, selection| {
763 selection.collapse_to(
764 map.prev_line_boundary(selection.start.to_point(map)).1,
765 SelectionGoal::None,
766 )
767 });
768 }
769 Some(Mode::VisualBlock) => {
770 let mut first = s.first_anchor();
771 first.collapse_to(first.start, first.goal);
772 s.select_anchors(vec![first]);
773 }
774 _ => {
775 s.move_with(|_, selection| {
776 selection.collapse_to(selection.start, selection.goal);
777 });
778 }
779 });
780 });
781 self.switch_mode(Mode::Normal, true, cx)
782 }
783
784 fn transaction_ended(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
785 push_to_change_list(self, editor, cx)
786 }
787
788 fn local_selections_changed(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
789 let newest = editor.read(cx).selections.newest_anchor().clone();
790 let is_multicursor = editor.read(cx).selections.count() > 1;
791
792 let state = self.state();
793 let mut is_visual = state.mode.is_visual();
794 if state.mode == Mode::Insert && state.current_tx.is_some() {
795 if state.current_anchor.is_none() {
796 self.update_state(|state| state.current_anchor = Some(newest));
797 } else if state.current_anchor.as_ref().unwrap() != &newest {
798 if let Some(tx_id) = self.update_state(|state| state.current_tx.take()) {
799 self.update_active_editor(cx, |_, editor, cx| {
800 editor.group_until_transaction(tx_id, cx)
801 });
802 }
803 }
804 } else if state.mode == Mode::Normal && newest.start != newest.end {
805 if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
806 self.switch_mode(Mode::VisualBlock, false, cx);
807 } else {
808 self.switch_mode(Mode::Visual, false, cx)
809 }
810 is_visual = true;
811 } else if newest.start == newest.end
812 && !is_multicursor
813 && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&state.mode)
814 {
815 self.switch_mode(Mode::Normal, true, cx);
816 is_visual = false;
817 }
818
819 if is_visual {
820 create_mark_before(self, ">".into(), cx);
821 create_mark(self, "<".into(), true, cx)
822 }
823 }
824
825 fn active_editor_input_ignored(text: Arc<str>, cx: &mut WindowContext) {
826 if text.is_empty() {
827 return;
828 }
829
830 match Vim::read(cx).active_operator() {
831 Some(Operator::FindForward { before }) => {
832 let find = Motion::FindForward {
833 before,
834 char: text.chars().next().unwrap(),
835 mode: if VimSettings::get_global(cx).use_multiline_find {
836 FindRange::MultiLine
837 } else {
838 FindRange::SingleLine
839 },
840 smartcase: VimSettings::get_global(cx).use_smartcase_find,
841 };
842 Vim::update(cx, |vim, _| {
843 vim.workspace_state.last_find = Some(find.clone())
844 });
845 motion::motion(find, cx)
846 }
847 Some(Operator::FindBackward { after }) => {
848 let find = Motion::FindBackward {
849 after,
850 char: text.chars().next().unwrap(),
851 mode: if VimSettings::get_global(cx).use_multiline_find {
852 FindRange::MultiLine
853 } else {
854 FindRange::SingleLine
855 },
856 smartcase: VimSettings::get_global(cx).use_smartcase_find,
857 };
858 Vim::update(cx, |vim, _| {
859 vim.workspace_state.last_find = Some(find.clone())
860 });
861 motion::motion(find, cx)
862 }
863 Some(Operator::Replace) => match Vim::read(cx).state().mode {
864 Mode::Normal => normal_replace(text, cx),
865 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => visual_replace(text, cx),
866 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
867 },
868 Some(Operator::AddSurrounds { target }) => match Vim::read(cx).state().mode {
869 Mode::Normal => {
870 if let Some(target) = target {
871 add_surrounds(text, target, cx);
872 Vim::update(cx, |vim, cx| vim.clear_operator(cx));
873 }
874 }
875 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
876 },
877 Some(Operator::ChangeSurrounds { target }) => match Vim::read(cx).state().mode {
878 Mode::Normal => {
879 if let Some(target) = target {
880 change_surrounds(text, target, cx);
881 Vim::update(cx, |vim, cx| vim.clear_operator(cx));
882 }
883 }
884 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
885 },
886 Some(Operator::DeleteSurrounds) => match Vim::read(cx).state().mode {
887 Mode::Normal => {
888 delete_surrounds(text, cx);
889 Vim::update(cx, |vim, cx| vim.clear_operator(cx));
890 }
891 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
892 },
893 Some(Operator::Mark) => Vim::update(cx, |vim, cx| {
894 normal::mark::create_mark(vim, text, false, cx)
895 }),
896 Some(Operator::Register) => Vim::update(cx, |vim, cx| {
897 vim.select_register(text, cx);
898 }),
899 Some(Operator::Jump { line }) => normal::mark::jump(text, line, cx),
900 _ => match Vim::read(cx).state().mode {
901 Mode::Replace => multi_replace(text, cx),
902 _ => {}
903 },
904 }
905 }
906
907 fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
908 if self.enabled == enabled {
909 return;
910 }
911 if !enabled {
912 CommandPaletteInterceptor::update_global(cx, |interceptor, _| {
913 interceptor.clear();
914 });
915 CommandPaletteFilter::update_global(cx, |filter, _| {
916 filter.hide_namespace(Self::NAMESPACE);
917 });
918 *self = Default::default();
919 return;
920 }
921
922 self.enabled = true;
923 CommandPaletteFilter::update_global(cx, |filter, _| {
924 filter.show_namespace(Self::NAMESPACE);
925 });
926 CommandPaletteInterceptor::update_global(cx, |interceptor, _| {
927 interceptor.set(Box::new(command::command_interceptor));
928 });
929
930 if let Some(active_window) = cx
931 .active_window()
932 .and_then(|window| window.downcast::<Workspace>())
933 {
934 active_window
935 .update(cx, |workspace, cx| {
936 let active_editor = workspace.active_item_as::<Editor>(cx);
937 if let Some(active_editor) = active_editor {
938 self.activate_editor(active_editor, cx);
939 self.switch_mode(Mode::Normal, false, cx);
940 }
941 })
942 .ok();
943 }
944 }
945
946 /// Returns the state of the active editor.
947 pub fn state(&self) -> &EditorState {
948 if let Some(active_editor) = self.active_editor.as_ref() {
949 if let Some(state) = self.editor_states.get(&active_editor.entity_id()) {
950 return state;
951 }
952 }
953
954 &self.default_state
955 }
956
957 /// Updates the state of the active editor.
958 pub fn update_state<T>(&mut self, func: impl FnOnce(&mut EditorState) -> T) -> T {
959 let mut state = self.state().clone();
960 let ret = func(&mut state);
961
962 if let Some(active_editor) = self.active_editor.as_ref() {
963 self.editor_states.insert(active_editor.entity_id(), state);
964 }
965
966 ret
967 }
968
969 fn sync_vim_settings(&mut self, cx: &mut WindowContext) {
970 self.update_active_editor(cx, |vim, editor, cx| {
971 let state = vim.state();
972 editor.set_cursor_shape(state.cursor_shape(), cx);
973 editor.set_clip_at_line_ends(state.clip_at_line_ends(), cx);
974 editor.set_collapse_matches(true);
975 editor.set_input_enabled(!state.vim_controlled());
976 editor.set_autoindent(state.should_autoindent());
977 editor.selections.line_mode = matches!(state.mode, Mode::VisualLine);
978 if editor.is_focused(cx) || editor.mouse_menu_is_focused(cx) {
979 editor.set_keymap_context_layer::<Self>(state.keymap_context_layer(), cx);
980 // disable vim mode if a sub-editor (inline assist, rename, etc.) is focused
981 } else if editor.focus_handle(cx).contains_focused(cx) {
982 editor.remove_keymap_context_layer::<Self>(cx);
983 }
984 });
985 }
986
987 fn unhook_vim_settings(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
988 if editor.mode() == EditorMode::Full {
989 editor.set_cursor_shape(CursorShape::Bar, cx);
990 editor.set_clip_at_line_ends(false, cx);
991 editor.set_collapse_matches(false);
992 editor.set_input_enabled(true);
993 editor.set_autoindent(true);
994 editor.selections.line_mode = false;
995 }
996 editor.remove_keymap_context_layer::<Self>(cx)
997 }
998}
999
1000impl Settings for VimModeSetting {
1001 const KEY: Option<&'static str> = Some("vim_mode");
1002
1003 type FileContent = Option<bool>;
1004
1005 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1006 Ok(Self(sources.user.copied().flatten().unwrap_or(
1007 sources.default.ok_or_else(Self::missing_default)?,
1008 )))
1009 }
1010}
1011
1012/// Controls when to use system clipboard.
1013#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
1014#[serde(rename_all = "snake_case")]
1015pub enum UseSystemClipboard {
1016 /// Don't use system clipboard.
1017 Never,
1018 /// Use system clipboard.
1019 Always,
1020 /// Use system clipboard for yank operations.
1021 OnYank,
1022}
1023
1024#[derive(Deserialize)]
1025struct VimSettings {
1026 // all vim uses vim clipboard
1027 // vim always uses system cliupbaord
1028 // some magic where yy is system and dd is not.
1029 pub use_system_clipboard: UseSystemClipboard,
1030 pub use_multiline_find: bool,
1031 pub use_smartcase_find: bool,
1032}
1033
1034#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
1035struct VimSettingsContent {
1036 pub use_system_clipboard: Option<UseSystemClipboard>,
1037 pub use_multiline_find: Option<bool>,
1038 pub use_smartcase_find: Option<bool>,
1039}
1040
1041impl Settings for VimSettings {
1042 const KEY: Option<&'static str> = Some("vim");
1043
1044 type FileContent = VimSettingsContent;
1045
1046 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1047 sources.json_merge()
1048 }
1049}