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 utils;
18mod visual;
19
20use anyhow::Result;
21use change_list::push_to_change_list;
22use collections::HashMap;
23use command_palette_hooks::{CommandPaletteFilter, CommandPaletteInterceptor};
24use editor::{
25 movement::{self, FindRange},
26 Anchor, Bias, ClipboardSelection, Editor, EditorEvent, EditorMode, ToPoint,
27};
28use gpui::{
29 actions, impl_actions, Action, AppContext, ClipboardItem, EntityId, FocusableView, Global,
30 KeystrokeEvent, Subscription, UpdateGlobal, View, ViewContext, WeakView, WindowContext,
31};
32use language::{CursorShape, Point, SelectionGoal, TransactionId};
33pub use mode_indicator::ModeIndicator;
34use motion::Motion;
35use normal::{
36 mark::{create_mark, create_mark_after, create_mark_before},
37 normal_replace,
38};
39use replace::multi_replace;
40use schemars::JsonSchema;
41use serde::Deserialize;
42use serde_derive::Serialize;
43use settings::{update_settings_file, Settings, SettingsSources, SettingsStore};
44use state::{EditorState, Mode, Operator, RecordedSelection, WorkspaceState};
45use std::{ops::Range, sync::Arc};
46use surrounds::{add_surrounds, change_surrounds, delete_surrounds};
47use ui::BorrowAppContext;
48use utils::SYSTEM_CLIPBOARD;
49use visual::{visual_block_motion, visual_replace};
50use workspace::{self, Workspace};
51
52use crate::state::ReplayableAction;
53
54/// Whether or not to enable Vim mode (work in progress).
55///
56/// Default: false
57pub struct VimModeSetting(pub bool);
58
59/// An Action to Switch between modes
60#[derive(Clone, Deserialize, PartialEq)]
61pub struct SwitchMode(pub Mode);
62
63/// PushOperator is used to put vim into a "minor" mode,
64/// where it's waiting for a specific next set of keystrokes.
65/// For example 'd' needs a motion to complete.
66#[derive(Clone, Deserialize, PartialEq)]
67pub struct PushOperator(pub Operator);
68
69/// Number is used to manage vim's count. Pushing a digit
70/// multiplis the current value by 10 and adds the digit.
71#[derive(Clone, Deserialize, PartialEq)]
72struct Number(usize);
73
74#[derive(Clone, Deserialize, PartialEq)]
75struct SelectRegister(String);
76
77actions!(
78 vim,
79 [
80 Tab,
81 Enter,
82 Object,
83 InnerObject,
84 FindForward,
85 FindBackward,
86 OpenDefaultKeymap
87 ]
88);
89
90// in the workspace namespace so it's not filtered out when vim is disabled.
91actions!(workspace, [ToggleVimMode]);
92
93impl_actions!(vim, [SwitchMode, PushOperator, Number, SelectRegister]);
94
95/// Initializes the `vim` crate.
96pub fn init(cx: &mut AppContext) {
97 cx.set_global(Vim::default());
98 VimModeSetting::register(cx);
99 VimSettings::register(cx);
100
101 cx.observe_keystrokes(observe_keystrokes).detach();
102 editor_events::init(cx);
103
104 cx.observe_new_views(|workspace: &mut Workspace, cx| register(workspace, cx))
105 .detach();
106
107 // Any time settings change, update vim mode to match. The Vim struct
108 // will be initialized as disabled by default, so we filter its commands
109 // out when starting up.
110 CommandPaletteFilter::update_global(cx, |filter, _| {
111 filter.hide_namespace(Vim::NAMESPACE);
112 });
113 Vim::update_global(cx, |vim, cx| {
114 vim.set_enabled(VimModeSetting::get_global(cx).0, cx)
115 });
116 cx.observe_global::<SettingsStore>(|cx| {
117 Vim::update_global(cx, |vim, cx| {
118 vim.set_enabled(VimModeSetting::get_global(cx).0, cx)
119 });
120 })
121 .detach();
122}
123
124fn register(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
125 workspace.register_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {
126 Vim::update(cx, |vim, cx| vim.switch_mode(mode, false, cx))
127 });
128 workspace.register_action(
129 |_: &mut Workspace, PushOperator(operator): &PushOperator, cx| {
130 Vim::update(cx, |vim, cx| vim.push_operator(operator.clone(), cx))
131 },
132 );
133 workspace.register_action(|_: &mut Workspace, n: &Number, cx: _| {
134 Vim::update(cx, |vim, cx| vim.push_count_digit(n.0, cx));
135 });
136 workspace.register_action(|_: &mut Workspace, _: &Tab, cx| {
137 Vim::active_editor_input_ignored(" ".into(), cx)
138 });
139
140 workspace.register_action(|_: &mut Workspace, _: &Enter, cx| {
141 Vim::active_editor_input_ignored("\n".into(), cx)
142 });
143
144 workspace.register_action(|workspace: &mut Workspace, _: &ToggleVimMode, cx| {
145 let fs = workspace.app_state().fs.clone();
146 let currently_enabled = VimModeSetting::get_global(cx).0;
147 update_settings_file::<VimModeSetting>(fs, cx, move |setting| {
148 *setting = Some(!currently_enabled)
149 })
150 });
151
152 workspace.register_action(|_: &mut Workspace, _: &OpenDefaultKeymap, cx| {
153 cx.emit(workspace::Event::OpenBundledFile {
154 text: settings::vim_keymap(),
155 title: "Default Vim Bindings",
156 language: "JSON",
157 });
158 });
159
160 normal::register(workspace, cx);
161 insert::register(workspace, cx);
162 motion::register(workspace, cx);
163 command::register(workspace, cx);
164 replace::register(workspace, cx);
165 object::register(workspace, cx);
166 visual::register(workspace, cx);
167 change_list::register(workspace, cx);
168}
169
170/// Called whenever an keystroke is typed so vim can observe all actions
171/// and keystrokes accordingly.
172fn observe_keystrokes(keystroke_event: &KeystrokeEvent, cx: &mut WindowContext) {
173 if let Some(action) = keystroke_event
174 .action
175 .as_ref()
176 .map(|action| action.boxed_clone())
177 {
178 Vim::update(cx, |vim, _| {
179 if vim.workspace_state.recording {
180 vim.workspace_state
181 .recorded_actions
182 .push(ReplayableAction::Action(action.boxed_clone()));
183
184 if vim.workspace_state.stop_recording_after_next_action {
185 vim.workspace_state.recording = false;
186 vim.workspace_state.stop_recording_after_next_action = false;
187 }
188 }
189 });
190
191 // Keystroke is handled by the vim system, so continue forward
192 if action.name().starts_with("vim::") {
193 return;
194 }
195 } else if cx.has_pending_keystrokes() {
196 return;
197 }
198
199 Vim::update(cx, |vim, cx| match vim.active_operator() {
200 Some(
201 Operator::FindForward { .. }
202 | Operator::FindBackward { .. }
203 | Operator::Replace
204 | Operator::AddSurrounds { .. }
205 | Operator::ChangeSurrounds { .. }
206 | Operator::DeleteSurrounds
207 | Operator::Mark
208 | Operator::Jump { .. }
209 | Operator::Register,
210 ) => {}
211 Some(_) => {
212 vim.clear_operator(cx);
213 }
214 _ => {}
215 });
216}
217
218/// The state pertaining to Vim mode.
219#[derive(Default)]
220struct Vim {
221 active_editor: Option<WeakView<Editor>>,
222 editor_subscription: Option<Subscription>,
223 enabled: bool,
224 editor_states: HashMap<EntityId, EditorState>,
225 workspace_state: WorkspaceState,
226 default_state: EditorState,
227}
228
229impl Global for Vim {}
230
231impl Vim {
232 /// The namespace for Vim actions.
233 const NAMESPACE: &'static str = "vim";
234
235 fn read(cx: &mut AppContext) -> &Self {
236 cx.global::<Self>()
237 }
238
239 fn update<F, S>(cx: &mut WindowContext, update: F) -> S
240 where
241 F: FnOnce(&mut Self, &mut WindowContext) -> S,
242 {
243 cx.update_global(update)
244 }
245
246 fn activate_editor(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
247 if !editor.read(cx).use_modal_editing() {
248 return;
249 }
250
251 self.active_editor = Some(editor.clone().downgrade());
252 self.editor_subscription = Some(cx.subscribe(&editor, |editor, event, cx| match event {
253 EditorEvent::SelectionsChanged { local: true } => {
254 if editor.read(cx).leader_peer_id().is_none() {
255 Vim::update(cx, |vim, cx| {
256 vim.local_selections_changed(editor, cx);
257 })
258 }
259 }
260 EditorEvent::InputIgnored { text } => {
261 Vim::active_editor_input_ignored(text.clone(), cx);
262 Vim::record_insertion(text, None, cx)
263 }
264 EditorEvent::InputHandled {
265 text,
266 utf16_range_to_replace: range_to_replace,
267 } => Vim::record_insertion(text, range_to_replace.clone(), cx),
268 EditorEvent::TransactionBegun { transaction_id } => Vim::update(cx, |vim, cx| {
269 vim.transaction_begun(*transaction_id, cx);
270 }),
271 EditorEvent::TransactionUndone { transaction_id } => Vim::update(cx, |vim, cx| {
272 vim.transaction_undone(transaction_id, cx);
273 }),
274 EditorEvent::Edited => Vim::update(cx, |vim, cx| vim.transaction_ended(editor, cx)),
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 is_yank: bool,
553 linewise: bool,
554 text: String,
555 clipboard_selections: Vec<ClipboardSelection>,
556 cx: &mut ViewContext<Editor>,
557 ) {
558 self.workspace_state.registers.insert('"', text.clone());
559 if let Some(register) = self.update_state(|vim| vim.selected_register.take()) {
560 let lower = register.to_lowercase().next().unwrap_or(register);
561 if lower != register {
562 let current = self.workspace_state.registers.entry(lower).or_default();
563 *current += &text;
564 } else {
565 match lower {
566 '_' | ':' | '.' | '%' | '#' | '=' | '/' => {}
567 '+' => {
568 cx.write_to_clipboard(
569 ClipboardItem::new(text.clone()).with_metadata(clipboard_selections),
570 );
571 }
572 '*' => {
573 #[cfg(target_os = "linux")]
574 cx.write_to_primary(
575 ClipboardItem::new(text.clone()).with_metadata(clipboard_selections),
576 );
577 #[cfg(not(target_os = "linux"))]
578 cx.write_to_clipboard(
579 ClipboardItem::new(text.clone()).with_metadata(clipboard_selections),
580 );
581 }
582 '"' => {
583 self.workspace_state.registers.insert('0', text.clone());
584 self.workspace_state.registers.insert('"', text);
585 }
586 _ => {
587 self.workspace_state.registers.insert(lower, text);
588 }
589 }
590 }
591 } else {
592 let setting = VimSettings::get_global(cx).use_system_clipboard;
593 if setting == UseSystemClipboard::Always
594 || setting == UseSystemClipboard::OnYank && is_yank
595 {
596 cx.write_to_clipboard(
597 ClipboardItem::new(text.clone()).with_metadata(clipboard_selections.clone()),
598 );
599 self.workspace_state
600 .registers
601 .insert(SYSTEM_CLIPBOARD, text.clone());
602 } else {
603 self.workspace_state.registers.insert(
604 SYSTEM_CLIPBOARD,
605 cx.read_from_clipboard()
606 .map(|item| item.text().clone())
607 .unwrap_or_default(),
608 );
609 }
610
611 if is_yank {
612 self.workspace_state.registers.insert('0', text);
613 } else {
614 if !text.contains('\n') {
615 self.workspace_state.registers.insert('-', text.clone());
616 }
617 if linewise || text.contains('\n') {
618 let mut content = text;
619 for i in '1'..'8' {
620 if let Some(moved) = self.workspace_state.registers.insert(i, content) {
621 content = moved;
622 } else {
623 break;
624 }
625 }
626 }
627 }
628 }
629 }
630
631 fn read_register(
632 &mut self,
633 register: char,
634 editor: Option<&mut Editor>,
635 cx: &mut WindowContext,
636 ) -> Option<String> {
637 let lower = register.to_lowercase().next().unwrap_or(register);
638 match lower {
639 '_' | ':' | '.' | '#' | '=' | '/' => None,
640 '+' => cx.read_from_clipboard().map(|item| item.text().clone()),
641 '*' => {
642 #[cfg(target_os = "linux")]
643 {
644 cx.read_from_primary().map(|item| item.text().clone())
645 }
646 #[cfg(not(target_os = "linux"))]
647 {
648 cx.read_from_clipboard().map(|item| item.text().clone())
649 }
650 }
651 '%' => editor.and_then(|editor| {
652 let selection = editor.selections.newest::<Point>(cx);
653 if let Some((_, buffer, _)) = editor
654 .buffer()
655 .read(cx)
656 .excerpt_containing(selection.head(), cx)
657 {
658 buffer
659 .read(cx)
660 .file()
661 .map(|file| file.path().to_string_lossy().to_string())
662 } else {
663 None
664 }
665 }),
666 _ => self.workspace_state.registers.get(&lower).cloned(),
667 }
668 }
669
670 fn push_operator(&mut self, operator: Operator, cx: &mut WindowContext) {
671 if matches!(
672 operator,
673 Operator::Change
674 | Operator::Delete
675 | Operator::Replace
676 | Operator::Indent
677 | Operator::Outdent
678 | Operator::Lowercase
679 | Operator::Uppercase
680 | Operator::OppositeCase
681 ) {
682 self.start_recording(cx)
683 };
684 // Since these operations can only be entered with pre-operators,
685 // we need to clear the previous operators when pushing,
686 // so that the current stack is the most correct
687 if matches!(
688 operator,
689 Operator::AddSurrounds { .. }
690 | Operator::ChangeSurrounds { .. }
691 | Operator::DeleteSurrounds
692 ) {
693 self.update_state(|state| state.operator_stack.clear());
694 };
695 self.update_state(|state| state.operator_stack.push(operator));
696 self.sync_vim_settings(cx);
697 }
698
699 fn maybe_pop_operator(&mut self) -> Option<Operator> {
700 self.update_state(|state| state.operator_stack.pop())
701 }
702
703 fn pop_operator(&mut self, cx: &mut WindowContext) -> Operator {
704 let popped_operator = self.update_state(|state| state.operator_stack.pop())
705 .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
706 self.sync_vim_settings(cx);
707 popped_operator
708 }
709
710 fn clear_operator(&mut self, cx: &mut WindowContext) {
711 self.take_count(cx);
712 self.update_state(|state| {
713 state.selected_register.take();
714 state.operator_stack.clear()
715 });
716 self.sync_vim_settings(cx);
717 }
718
719 fn active_operator(&self) -> Option<Operator> {
720 self.state().operator_stack.last().cloned()
721 }
722
723 fn transaction_begun(&mut self, transaction_id: TransactionId, _: &mut WindowContext) {
724 self.update_state(|state| {
725 let mode = if (state.mode == Mode::Insert
726 || state.mode == Mode::Replace
727 || state.mode == Mode::Normal)
728 && state.current_tx.is_none()
729 {
730 state.current_tx = Some(transaction_id);
731 state.last_mode
732 } else {
733 state.mode
734 };
735 if mode == Mode::VisualLine || mode == Mode::VisualBlock {
736 state.undo_modes.insert(transaction_id, mode);
737 }
738 });
739 }
740
741 fn transaction_undone(&mut self, transaction_id: &TransactionId, cx: &mut WindowContext) {
742 if !self.state().mode.is_visual() {
743 return;
744 };
745 self.update_active_editor(cx, |vim, editor, cx| {
746 let original_mode = vim.state().undo_modes.get(transaction_id);
747 editor.change_selections(None, cx, |s| match original_mode {
748 Some(Mode::VisualLine) => {
749 s.move_with(|map, selection| {
750 selection.collapse_to(
751 map.prev_line_boundary(selection.start.to_point(map)).1,
752 SelectionGoal::None,
753 )
754 });
755 }
756 Some(Mode::VisualBlock) => {
757 let mut first = s.first_anchor();
758 first.collapse_to(first.start, first.goal);
759 s.select_anchors(vec![first]);
760 }
761 _ => {
762 s.move_with(|_, selection| {
763 selection.collapse_to(selection.start, selection.goal);
764 });
765 }
766 });
767 });
768 self.switch_mode(Mode::Normal, true, cx)
769 }
770
771 fn transaction_ended(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
772 push_to_change_list(self, editor, cx)
773 }
774
775 fn local_selections_changed(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
776 let newest = editor.read(cx).selections.newest_anchor().clone();
777 let is_multicursor = editor.read(cx).selections.count() > 1;
778
779 let state = self.state();
780 let mut is_visual = state.mode.is_visual();
781 if state.mode == Mode::Insert && state.current_tx.is_some() {
782 if state.current_anchor.is_none() {
783 self.update_state(|state| state.current_anchor = Some(newest));
784 } else if state.current_anchor.as_ref().unwrap() != &newest {
785 if let Some(tx_id) = self.update_state(|state| state.current_tx.take()) {
786 self.update_active_editor(cx, |_, editor, cx| {
787 editor.group_until_transaction(tx_id, cx)
788 });
789 }
790 }
791 } else if state.mode == Mode::Normal && newest.start != newest.end {
792 if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
793 self.switch_mode(Mode::VisualBlock, false, cx);
794 } else {
795 self.switch_mode(Mode::Visual, false, cx)
796 }
797 is_visual = true;
798 } else if newest.start == newest.end
799 && !is_multicursor
800 && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&state.mode)
801 {
802 self.switch_mode(Mode::Normal, true, cx);
803 is_visual = false;
804 }
805
806 if is_visual {
807 create_mark_before(self, ">".into(), cx);
808 create_mark(self, "<".into(), true, cx)
809 }
810 }
811
812 fn active_editor_input_ignored(text: Arc<str>, cx: &mut WindowContext) {
813 if text.is_empty() {
814 return;
815 }
816
817 match Vim::read(cx).active_operator() {
818 Some(Operator::FindForward { before }) => {
819 let find = Motion::FindForward {
820 before,
821 char: text.chars().next().unwrap(),
822 mode: if VimSettings::get_global(cx).use_multiline_find {
823 FindRange::MultiLine
824 } else {
825 FindRange::SingleLine
826 },
827 smartcase: VimSettings::get_global(cx).use_smartcase_find,
828 };
829 Vim::update(cx, |vim, _| {
830 vim.workspace_state.last_find = Some(find.clone())
831 });
832 motion::motion(find, cx)
833 }
834 Some(Operator::FindBackward { after }) => {
835 let find = Motion::FindBackward {
836 after,
837 char: text.chars().next().unwrap(),
838 mode: if VimSettings::get_global(cx).use_multiline_find {
839 FindRange::MultiLine
840 } else {
841 FindRange::SingleLine
842 },
843 smartcase: VimSettings::get_global(cx).use_smartcase_find,
844 };
845 Vim::update(cx, |vim, _| {
846 vim.workspace_state.last_find = Some(find.clone())
847 });
848 motion::motion(find, cx)
849 }
850 Some(Operator::Replace) => match Vim::read(cx).state().mode {
851 Mode::Normal => normal_replace(text, cx),
852 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => visual_replace(text, cx),
853 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
854 },
855 Some(Operator::AddSurrounds { target }) => match Vim::read(cx).state().mode {
856 Mode::Normal => {
857 if let Some(target) = target {
858 add_surrounds(text, target, cx);
859 Vim::update(cx, |vim, cx| vim.clear_operator(cx));
860 }
861 }
862 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
863 },
864 Some(Operator::ChangeSurrounds { target }) => match Vim::read(cx).state().mode {
865 Mode::Normal => {
866 if let Some(target) = target {
867 change_surrounds(text, target, cx);
868 Vim::update(cx, |vim, cx| vim.clear_operator(cx));
869 }
870 }
871 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
872 },
873 Some(Operator::DeleteSurrounds) => match Vim::read(cx).state().mode {
874 Mode::Normal => {
875 delete_surrounds(text, cx);
876 Vim::update(cx, |vim, cx| vim.clear_operator(cx));
877 }
878 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
879 },
880 Some(Operator::Mark) => Vim::update(cx, |vim, cx| {
881 normal::mark::create_mark(vim, text, false, cx)
882 }),
883 Some(Operator::Register) => Vim::update(cx, |vim, cx| {
884 vim.select_register(text, cx);
885 }),
886 Some(Operator::Jump { line }) => normal::mark::jump(text, line, cx),
887 _ => match Vim::read(cx).state().mode {
888 Mode::Replace => multi_replace(text, cx),
889 _ => {}
890 },
891 }
892 }
893
894 fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
895 if self.enabled == enabled {
896 return;
897 }
898 if !enabled {
899 CommandPaletteInterceptor::update_global(cx, |interceptor, _| {
900 interceptor.clear();
901 });
902 CommandPaletteFilter::update_global(cx, |filter, _| {
903 filter.hide_namespace(Self::NAMESPACE);
904 });
905 *self = Default::default();
906 return;
907 }
908
909 self.enabled = true;
910 CommandPaletteFilter::update_global(cx, |filter, _| {
911 filter.show_namespace(Self::NAMESPACE);
912 });
913 CommandPaletteInterceptor::update_global(cx, |interceptor, _| {
914 interceptor.set(Box::new(command::command_interceptor));
915 });
916
917 if let Some(active_window) = cx
918 .active_window()
919 .and_then(|window| window.downcast::<Workspace>())
920 {
921 active_window
922 .update(cx, |workspace, cx| {
923 let active_editor = workspace.active_item_as::<Editor>(cx);
924 if let Some(active_editor) = active_editor {
925 self.activate_editor(active_editor, cx);
926 self.switch_mode(Mode::Normal, false, cx);
927 }
928 })
929 .ok();
930 }
931 }
932
933 /// Returns the state of the active editor.
934 pub fn state(&self) -> &EditorState {
935 if let Some(active_editor) = self.active_editor.as_ref() {
936 if let Some(state) = self.editor_states.get(&active_editor.entity_id()) {
937 return state;
938 }
939 }
940
941 &self.default_state
942 }
943
944 /// Updates the state of the active editor.
945 pub fn update_state<T>(&mut self, func: impl FnOnce(&mut EditorState) -> T) -> T {
946 let mut state = self.state().clone();
947 let ret = func(&mut state);
948
949 if let Some(active_editor) = self.active_editor.as_ref() {
950 self.editor_states.insert(active_editor.entity_id(), state);
951 }
952
953 ret
954 }
955
956 fn sync_vim_settings(&mut self, cx: &mut WindowContext) {
957 self.update_active_editor(cx, |vim, editor, cx| {
958 let state = vim.state();
959 editor.set_cursor_shape(state.cursor_shape(), cx);
960 editor.set_clip_at_line_ends(state.clip_at_line_ends(), cx);
961 editor.set_collapse_matches(true);
962 editor.set_input_enabled(!state.vim_controlled());
963 editor.set_autoindent(state.should_autoindent());
964 editor.selections.line_mode = matches!(state.mode, Mode::VisualLine);
965 if editor.is_focused(cx) || editor.mouse_menu_is_focused(cx) {
966 editor.set_keymap_context_layer::<Self>(state.keymap_context_layer(), cx);
967 // disable vim mode if a sub-editor (inline assist, rename, etc.) is focused
968 } else if editor.focus_handle(cx).contains_focused(cx) {
969 editor.remove_keymap_context_layer::<Self>(cx);
970 }
971 });
972 }
973
974 fn unhook_vim_settings(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
975 if editor.mode() == EditorMode::Full {
976 editor.set_cursor_shape(CursorShape::Bar, cx);
977 editor.set_clip_at_line_ends(false, cx);
978 editor.set_collapse_matches(false);
979 editor.set_input_enabled(true);
980 editor.set_autoindent(true);
981 editor.selections.line_mode = false;
982 }
983 editor.remove_keymap_context_layer::<Self>(cx)
984 }
985}
986
987impl Settings for VimModeSetting {
988 const KEY: Option<&'static str> = Some("vim_mode");
989
990 type FileContent = Option<bool>;
991
992 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
993 Ok(Self(sources.user.copied().flatten().unwrap_or(
994 sources.default.ok_or_else(Self::missing_default)?,
995 )))
996 }
997}
998
999/// Controls when to use system clipboard.
1000#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
1001#[serde(rename_all = "snake_case")]
1002pub enum UseSystemClipboard {
1003 /// Don't use system clipboard.
1004 Never,
1005 /// Use system clipboard.
1006 Always,
1007 /// Use system clipboard for yank operations.
1008 OnYank,
1009}
1010
1011#[derive(Deserialize)]
1012struct VimSettings {
1013 // all vim uses vim clipboard
1014 // vim always uses system cliupbaord
1015 // some magic where yy is system and dd is not.
1016 pub use_system_clipboard: UseSystemClipboard,
1017 pub use_multiline_find: bool,
1018 pub use_smartcase_find: bool,
1019}
1020
1021#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
1022struct VimSettingsContent {
1023 pub use_system_clipboard: Option<UseSystemClipboard>,
1024 pub use_multiline_find: Option<bool>,
1025 pub use_smartcase_find: Option<bool>,
1026}
1027
1028impl Settings for VimSettings {
1029 const KEY: Option<&'static str> = Some("vim");
1030
1031 type FileContent = VimSettingsContent;
1032
1033 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1034 sources.json_merge()
1035 }
1036}