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 { .. } => {
275 Vim::update(cx, |vim, cx| vim.transaction_ended(editor, cx))
276 }
277 _ => {}
278 }));
279
280 let editor = editor.read(cx);
281 let editor_mode = editor.mode();
282 let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
283
284 if editor_mode == EditorMode::Full
285 && !newest_selection_empty
286 && self.state().mode == Mode::Normal
287 // When following someone, don't switch vim mode.
288 && editor.leader_peer_id().is_none()
289 {
290 self.switch_mode(Mode::Visual, true, cx);
291 }
292
293 self.sync_vim_settings(cx);
294 }
295
296 fn record_insertion(
297 text: &Arc<str>,
298 range_to_replace: Option<Range<isize>>,
299 cx: &mut WindowContext,
300 ) {
301 Vim::update(cx, |vim, _| {
302 if vim.workspace_state.recording {
303 vim.workspace_state
304 .recorded_actions
305 .push(ReplayableAction::Insertion {
306 text: text.clone(),
307 utf16_range_to_replace: range_to_replace,
308 });
309 if vim.workspace_state.stop_recording_after_next_action {
310 vim.workspace_state.recording = false;
311 vim.workspace_state.stop_recording_after_next_action = false;
312 }
313 }
314 });
315 }
316
317 fn update_active_editor<S>(
318 &mut self,
319 cx: &mut WindowContext,
320 update: impl FnOnce(&mut Vim, &mut Editor, &mut ViewContext<Editor>) -> S,
321 ) -> Option<S> {
322 let editor = self.active_editor.clone()?.upgrade()?;
323 Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
324 }
325
326 fn editor_selections(&mut self, cx: &mut WindowContext) -> Vec<Range<Anchor>> {
327 self.update_active_editor(cx, |_, editor, _| {
328 editor
329 .selections
330 .disjoint_anchors()
331 .iter()
332 .map(|selection| selection.tail()..selection.head())
333 .collect()
334 })
335 .unwrap_or_default()
336 }
337
338 /// When doing an action that modifies the buffer, we start recording so that `.`
339 /// will replay the action.
340 pub fn start_recording(&mut self, cx: &mut WindowContext) {
341 if !self.workspace_state.replaying {
342 self.workspace_state.recording = true;
343 self.workspace_state.recorded_actions = Default::default();
344 self.workspace_state.recorded_count = None;
345
346 let selections = self
347 .active_editor
348 .as_ref()
349 .and_then(|editor| editor.upgrade())
350 .map(|editor| {
351 let editor = editor.read(cx);
352 (
353 editor.selections.oldest::<Point>(cx),
354 editor.selections.newest::<Point>(cx),
355 )
356 });
357
358 if let Some((oldest, newest)) = selections {
359 self.workspace_state.recorded_selection = match self.state().mode {
360 Mode::Visual if newest.end.row == newest.start.row => {
361 RecordedSelection::SingleLine {
362 cols: newest.end.column - newest.start.column,
363 }
364 }
365 Mode::Visual => RecordedSelection::Visual {
366 rows: newest.end.row - newest.start.row,
367 cols: newest.end.column,
368 },
369 Mode::VisualLine => RecordedSelection::VisualLine {
370 rows: newest.end.row - newest.start.row,
371 },
372 Mode::VisualBlock => RecordedSelection::VisualBlock {
373 rows: newest.end.row.abs_diff(oldest.start.row),
374 cols: newest.end.column.abs_diff(oldest.start.column),
375 },
376 _ => RecordedSelection::None,
377 }
378 } else {
379 self.workspace_state.recorded_selection = RecordedSelection::None;
380 }
381 }
382 }
383
384 pub fn stop_replaying(&mut self) {
385 self.workspace_state.replaying = false;
386 }
387
388 /// When finishing an action that modifies the buffer, stop recording.
389 /// as you usually call this within a keystroke handler we also ensure that
390 /// the current action is recorded.
391 pub fn stop_recording(&mut self) {
392 if self.workspace_state.recording {
393 self.workspace_state.stop_recording_after_next_action = true;
394 }
395 }
396
397 /// Stops recording actions immediately rather than waiting until after the
398 /// next action to stop recording.
399 ///
400 /// This doesn't include the current action.
401 pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>) {
402 if self.workspace_state.recording {
403 self.workspace_state
404 .recorded_actions
405 .push(ReplayableAction::Action(action.boxed_clone()));
406 self.workspace_state.recording = false;
407 self.workspace_state.stop_recording_after_next_action = false;
408 }
409 }
410
411 /// Explicitly record one action (equivalents to start_recording and stop_recording)
412 pub fn record_current_action(&mut self, cx: &mut WindowContext) {
413 self.start_recording(cx);
414 self.stop_recording();
415 }
416
417 fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut WindowContext) {
418 let state = self.state();
419 let last_mode = state.mode;
420 let prior_mode = state.last_mode;
421 let prior_tx = state.current_tx;
422 self.update_state(|state| {
423 state.last_mode = last_mode;
424 state.mode = mode;
425 state.operator_stack.clear();
426 state.current_tx.take();
427 state.current_anchor.take();
428 });
429 if mode != Mode::Insert {
430 self.take_count(cx);
431 }
432
433 // Sync editor settings like clip mode
434 self.sync_vim_settings(cx);
435
436 if mode != Mode::Insert && last_mode == Mode::Insert {
437 create_mark_after(self, "^".into(), cx)
438 }
439
440 if leave_selections {
441 return;
442 }
443
444 // Adjust selections
445 self.update_active_editor(cx, |_, editor, cx| {
446 if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
447 {
448 visual_block_motion(true, editor, cx, |_, point, goal| Some((point, goal)))
449 }
450 if last_mode == Mode::Insert || last_mode == Mode::Replace {
451 if let Some(prior_tx) = prior_tx {
452 editor.group_until_transaction(prior_tx, cx)
453 }
454 }
455
456 editor.change_selections(None, cx, |s| {
457 // we cheat with visual block mode and use multiple cursors.
458 // the cost of this cheat is we need to convert back to a single
459 // cursor whenever vim would.
460 if last_mode == Mode::VisualBlock
461 && (mode != Mode::VisualBlock && mode != Mode::Insert)
462 {
463 let tail = s.oldest_anchor().tail();
464 let head = s.newest_anchor().head();
465 s.select_anchor_ranges(vec![tail..head]);
466 } else if last_mode == Mode::Insert
467 && prior_mode == Mode::VisualBlock
468 && mode != Mode::VisualBlock
469 {
470 let pos = s.first_anchor().head();
471 s.select_anchor_ranges(vec![pos..pos])
472 }
473
474 let snapshot = s.display_map();
475 if let Some(pending) = s.pending.as_mut() {
476 if pending.selection.reversed && mode.is_visual() && !last_mode.is_visual() {
477 let mut end = pending.selection.end.to_point(&snapshot.buffer_snapshot);
478 end = snapshot
479 .buffer_snapshot
480 .clip_point(end + Point::new(0, 1), Bias::Right);
481 pending.selection.end = snapshot.buffer_snapshot.anchor_before(end);
482 }
483 }
484
485 s.move_with(|map, selection| {
486 if last_mode.is_visual() && !mode.is_visual() {
487 let mut point = selection.head();
488 if !selection.reversed && !selection.is_empty() {
489 point = movement::left(map, selection.head());
490 }
491 selection.collapse_to(point, selection.goal)
492 } else if !last_mode.is_visual() && mode.is_visual() {
493 if selection.is_empty() {
494 selection.end = movement::right(map, selection.start);
495 }
496 } else if last_mode == Mode::Replace {
497 if selection.head().column() != 0 {
498 let point = movement::left(map, selection.head());
499 selection.collapse_to(point, selection.goal)
500 }
501 }
502 });
503 })
504 });
505 }
506
507 fn push_count_digit(&mut self, number: usize, cx: &mut WindowContext) {
508 if self.active_operator().is_some() {
509 self.update_state(|state| {
510 state.post_count = Some(state.post_count.unwrap_or(0) * 10 + number)
511 })
512 } else {
513 self.update_state(|state| {
514 state.pre_count = Some(state.pre_count.unwrap_or(0) * 10 + number)
515 })
516 }
517 // update the keymap so that 0 works
518 self.sync_vim_settings(cx)
519 }
520
521 fn take_count(&mut self, cx: &mut WindowContext) -> Option<usize> {
522 if self.workspace_state.replaying {
523 return self.workspace_state.recorded_count;
524 }
525
526 let count = if self.state().post_count == None && self.state().pre_count == None {
527 return None;
528 } else {
529 Some(self.update_state(|state| {
530 state.post_count.take().unwrap_or(1) * state.pre_count.take().unwrap_or(1)
531 }))
532 };
533 if self.workspace_state.recording {
534 self.workspace_state.recorded_count = count;
535 }
536 self.sync_vim_settings(cx);
537 count
538 }
539
540 fn select_register(&mut self, register: Arc<str>, cx: &mut WindowContext) {
541 self.update_state(|state| {
542 if register.chars().count() == 1 {
543 state
544 .selected_register
545 .replace(register.chars().next().unwrap());
546 }
547 state.operator_stack.clear();
548 });
549 self.sync_vim_settings(cx);
550 }
551
552 fn write_registers(
553 &mut self,
554 is_yank: bool,
555 linewise: bool,
556 text: String,
557 clipboard_selections: Vec<ClipboardSelection>,
558 cx: &mut ViewContext<Editor>,
559 ) {
560 self.workspace_state.registers.insert('"', text.clone());
561 if let Some(register) = self.update_state(|vim| vim.selected_register.take()) {
562 let lower = register.to_lowercase().next().unwrap_or(register);
563 if lower != register {
564 let current = self.workspace_state.registers.entry(lower).or_default();
565 *current += &text;
566 } else {
567 match lower {
568 '_' | ':' | '.' | '%' | '#' | '=' | '/' => {}
569 '+' => {
570 cx.write_to_clipboard(
571 ClipboardItem::new(text.clone()).with_metadata(clipboard_selections),
572 );
573 }
574 '*' => {
575 #[cfg(target_os = "linux")]
576 cx.write_to_primary(
577 ClipboardItem::new(text.clone()).with_metadata(clipboard_selections),
578 );
579 #[cfg(not(target_os = "linux"))]
580 cx.write_to_clipboard(
581 ClipboardItem::new(text.clone()).with_metadata(clipboard_selections),
582 );
583 }
584 '"' => {
585 self.workspace_state.registers.insert('0', text.clone());
586 self.workspace_state.registers.insert('"', text);
587 }
588 _ => {
589 self.workspace_state.registers.insert(lower, text);
590 }
591 }
592 }
593 } else {
594 let setting = VimSettings::get_global(cx).use_system_clipboard;
595 if setting == UseSystemClipboard::Always
596 || setting == UseSystemClipboard::OnYank && is_yank
597 {
598 cx.write_to_clipboard(
599 ClipboardItem::new(text.clone()).with_metadata(clipboard_selections.clone()),
600 );
601 self.workspace_state
602 .registers
603 .insert(SYSTEM_CLIPBOARD, text.clone());
604 } else {
605 self.workspace_state.registers.insert(
606 SYSTEM_CLIPBOARD,
607 cx.read_from_clipboard()
608 .map(|item| item.text().clone())
609 .unwrap_or_default(),
610 );
611 }
612
613 if is_yank {
614 self.workspace_state.registers.insert('0', text);
615 } else {
616 if !text.contains('\n') {
617 self.workspace_state.registers.insert('-', text.clone());
618 }
619 if linewise || text.contains('\n') {
620 let mut content = text;
621 for i in '1'..'8' {
622 if let Some(moved) = self.workspace_state.registers.insert(i, content) {
623 content = moved;
624 } else {
625 break;
626 }
627 }
628 }
629 }
630 }
631 }
632
633 fn read_register(
634 &mut self,
635 register: char,
636 editor: Option<&mut Editor>,
637 cx: &mut WindowContext,
638 ) -> Option<String> {
639 let lower = register.to_lowercase().next().unwrap_or(register);
640 match lower {
641 '_' | ':' | '.' | '#' | '=' | '/' => None,
642 '+' => cx.read_from_clipboard().map(|item| item.text().clone()),
643 '*' => {
644 #[cfg(target_os = "linux")]
645 {
646 cx.read_from_primary().map(|item| item.text().clone())
647 }
648 #[cfg(not(target_os = "linux"))]
649 {
650 cx.read_from_clipboard().map(|item| item.text().clone())
651 }
652 }
653 '%' => editor.and_then(|editor| {
654 let selection = editor.selections.newest::<Point>(cx);
655 if let Some((_, buffer, _)) = editor
656 .buffer()
657 .read(cx)
658 .excerpt_containing(selection.head(), cx)
659 {
660 buffer
661 .read(cx)
662 .file()
663 .map(|file| file.path().to_string_lossy().to_string())
664 } else {
665 None
666 }
667 }),
668 _ => self.workspace_state.registers.get(&lower).cloned(),
669 }
670 }
671
672 fn push_operator(&mut self, operator: Operator, cx: &mut WindowContext) {
673 if matches!(
674 operator,
675 Operator::Change
676 | Operator::Delete
677 | Operator::Replace
678 | Operator::Indent
679 | Operator::Outdent
680 | Operator::Lowercase
681 | Operator::Uppercase
682 | Operator::OppositeCase
683 ) {
684 self.start_recording(cx)
685 };
686 // Since these operations can only be entered with pre-operators,
687 // we need to clear the previous operators when pushing,
688 // so that the current stack is the most correct
689 if matches!(
690 operator,
691 Operator::AddSurrounds { .. }
692 | Operator::ChangeSurrounds { .. }
693 | Operator::DeleteSurrounds
694 ) {
695 self.update_state(|state| state.operator_stack.clear());
696 };
697 self.update_state(|state| state.operator_stack.push(operator));
698 self.sync_vim_settings(cx);
699 }
700
701 fn maybe_pop_operator(&mut self) -> Option<Operator> {
702 self.update_state(|state| state.operator_stack.pop())
703 }
704
705 fn pop_operator(&mut self, cx: &mut WindowContext) -> Operator {
706 let popped_operator = self.update_state(|state| state.operator_stack.pop())
707 .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
708 self.sync_vim_settings(cx);
709 popped_operator
710 }
711
712 fn clear_operator(&mut self, cx: &mut WindowContext) {
713 self.take_count(cx);
714 self.update_state(|state| {
715 state.selected_register.take();
716 state.operator_stack.clear()
717 });
718 self.sync_vim_settings(cx);
719 }
720
721 fn active_operator(&self) -> Option<Operator> {
722 self.state().operator_stack.last().cloned()
723 }
724
725 fn transaction_begun(&mut self, transaction_id: TransactionId, _: &mut WindowContext) {
726 self.update_state(|state| {
727 let mode = if (state.mode == Mode::Insert
728 || state.mode == Mode::Replace
729 || state.mode == Mode::Normal)
730 && state.current_tx.is_none()
731 {
732 state.current_tx = Some(transaction_id);
733 state.last_mode
734 } else {
735 state.mode
736 };
737 if mode == Mode::VisualLine || mode == Mode::VisualBlock {
738 state.undo_modes.insert(transaction_id, mode);
739 }
740 });
741 }
742
743 fn transaction_undone(&mut self, transaction_id: &TransactionId, cx: &mut WindowContext) {
744 if !self.state().mode.is_visual() {
745 return;
746 };
747 self.update_active_editor(cx, |vim, editor, cx| {
748 let original_mode = vim.state().undo_modes.get(transaction_id);
749 editor.change_selections(None, cx, |s| match original_mode {
750 Some(Mode::VisualLine) => {
751 s.move_with(|map, selection| {
752 selection.collapse_to(
753 map.prev_line_boundary(selection.start.to_point(map)).1,
754 SelectionGoal::None,
755 )
756 });
757 }
758 Some(Mode::VisualBlock) => {
759 let mut first = s.first_anchor();
760 first.collapse_to(first.start, first.goal);
761 s.select_anchors(vec![first]);
762 }
763 _ => {
764 s.move_with(|_, selection| {
765 selection.collapse_to(selection.start, selection.goal);
766 });
767 }
768 });
769 });
770 self.switch_mode(Mode::Normal, true, cx)
771 }
772
773 fn transaction_ended(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
774 push_to_change_list(self, editor, cx)
775 }
776
777 fn local_selections_changed(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
778 let newest = editor.read(cx).selections.newest_anchor().clone();
779 let is_multicursor = editor.read(cx).selections.count() > 1;
780
781 let state = self.state();
782 let mut is_visual = state.mode.is_visual();
783 if state.mode == Mode::Insert && state.current_tx.is_some() {
784 if state.current_anchor.is_none() {
785 self.update_state(|state| state.current_anchor = Some(newest));
786 } else if state.current_anchor.as_ref().unwrap() != &newest {
787 if let Some(tx_id) = self.update_state(|state| state.current_tx.take()) {
788 self.update_active_editor(cx, |_, editor, cx| {
789 editor.group_until_transaction(tx_id, cx)
790 });
791 }
792 }
793 } else if state.mode == Mode::Normal && newest.start != newest.end {
794 if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
795 self.switch_mode(Mode::VisualBlock, false, cx);
796 } else {
797 self.switch_mode(Mode::Visual, false, cx)
798 }
799 is_visual = true;
800 } else if newest.start == newest.end
801 && !is_multicursor
802 && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&state.mode)
803 {
804 self.switch_mode(Mode::Normal, true, cx);
805 is_visual = false;
806 }
807
808 if is_visual {
809 create_mark_before(self, ">".into(), cx);
810 create_mark(self, "<".into(), true, cx)
811 }
812 }
813
814 fn active_editor_input_ignored(text: Arc<str>, cx: &mut WindowContext) {
815 if text.is_empty() {
816 return;
817 }
818
819 match Vim::read(cx).active_operator() {
820 Some(Operator::FindForward { before }) => {
821 let find = Motion::FindForward {
822 before,
823 char: text.chars().next().unwrap(),
824 mode: if VimSettings::get_global(cx).use_multiline_find {
825 FindRange::MultiLine
826 } else {
827 FindRange::SingleLine
828 },
829 smartcase: VimSettings::get_global(cx).use_smartcase_find,
830 };
831 Vim::update(cx, |vim, _| {
832 vim.workspace_state.last_find = Some(find.clone())
833 });
834 motion::motion(find, cx)
835 }
836 Some(Operator::FindBackward { after }) => {
837 let find = Motion::FindBackward {
838 after,
839 char: text.chars().next().unwrap(),
840 mode: if VimSettings::get_global(cx).use_multiline_find {
841 FindRange::MultiLine
842 } else {
843 FindRange::SingleLine
844 },
845 smartcase: VimSettings::get_global(cx).use_smartcase_find,
846 };
847 Vim::update(cx, |vim, _| {
848 vim.workspace_state.last_find = Some(find.clone())
849 });
850 motion::motion(find, cx)
851 }
852 Some(Operator::Replace) => match Vim::read(cx).state().mode {
853 Mode::Normal => normal_replace(text, cx),
854 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => visual_replace(text, cx),
855 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
856 },
857 Some(Operator::AddSurrounds { target }) => match Vim::read(cx).state().mode {
858 Mode::Normal => {
859 if let Some(target) = target {
860 add_surrounds(text, target, cx);
861 Vim::update(cx, |vim, cx| vim.clear_operator(cx));
862 }
863 }
864 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
865 },
866 Some(Operator::ChangeSurrounds { target }) => match Vim::read(cx).state().mode {
867 Mode::Normal => {
868 if let Some(target) = target {
869 change_surrounds(text, target, cx);
870 Vim::update(cx, |vim, cx| vim.clear_operator(cx));
871 }
872 }
873 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
874 },
875 Some(Operator::DeleteSurrounds) => match Vim::read(cx).state().mode {
876 Mode::Normal => {
877 delete_surrounds(text, cx);
878 Vim::update(cx, |vim, cx| vim.clear_operator(cx));
879 }
880 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
881 },
882 Some(Operator::Mark) => Vim::update(cx, |vim, cx| {
883 normal::mark::create_mark(vim, text, false, cx)
884 }),
885 Some(Operator::Register) => Vim::update(cx, |vim, cx| {
886 vim.select_register(text, cx);
887 }),
888 Some(Operator::Jump { line }) => normal::mark::jump(text, line, cx),
889 _ => match Vim::read(cx).state().mode {
890 Mode::Replace => multi_replace(text, cx),
891 _ => {}
892 },
893 }
894 }
895
896 fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
897 if self.enabled == enabled {
898 return;
899 }
900 if !enabled {
901 CommandPaletteInterceptor::update_global(cx, |interceptor, _| {
902 interceptor.clear();
903 });
904 CommandPaletteFilter::update_global(cx, |filter, _| {
905 filter.hide_namespace(Self::NAMESPACE);
906 });
907 *self = Default::default();
908 return;
909 }
910
911 self.enabled = true;
912 CommandPaletteFilter::update_global(cx, |filter, _| {
913 filter.show_namespace(Self::NAMESPACE);
914 });
915 CommandPaletteInterceptor::update_global(cx, |interceptor, _| {
916 interceptor.set(Box::new(command::command_interceptor));
917 });
918
919 if let Some(active_window) = cx
920 .active_window()
921 .and_then(|window| window.downcast::<Workspace>())
922 {
923 active_window
924 .update(cx, |workspace, cx| {
925 let active_editor = workspace.active_item_as::<Editor>(cx);
926 if let Some(active_editor) = active_editor {
927 self.activate_editor(active_editor, cx);
928 self.switch_mode(Mode::Normal, false, cx);
929 }
930 })
931 .ok();
932 }
933 }
934
935 /// Returns the state of the active editor.
936 pub fn state(&self) -> &EditorState {
937 if let Some(active_editor) = self.active_editor.as_ref() {
938 if let Some(state) = self.editor_states.get(&active_editor.entity_id()) {
939 return state;
940 }
941 }
942
943 &self.default_state
944 }
945
946 /// Updates the state of the active editor.
947 pub fn update_state<T>(&mut self, func: impl FnOnce(&mut EditorState) -> T) -> T {
948 let mut state = self.state().clone();
949 let ret = func(&mut state);
950
951 if let Some(active_editor) = self.active_editor.as_ref() {
952 self.editor_states.insert(active_editor.entity_id(), state);
953 }
954
955 ret
956 }
957
958 fn sync_vim_settings(&mut self, cx: &mut WindowContext) {
959 self.update_active_editor(cx, |vim, editor, cx| {
960 let state = vim.state();
961 editor.set_cursor_shape(state.cursor_shape(), cx);
962 editor.set_clip_at_line_ends(state.clip_at_line_ends(), cx);
963 editor.set_collapse_matches(true);
964 editor.set_input_enabled(!state.vim_controlled());
965 editor.set_autoindent(state.should_autoindent());
966 editor.selections.line_mode = matches!(state.mode, Mode::VisualLine);
967 if editor.is_focused(cx) || editor.mouse_menu_is_focused(cx) {
968 editor.set_keymap_context_layer::<Self>(state.keymap_context_layer(), cx);
969 // disable vim mode if a sub-editor (inline assist, rename, etc.) is focused
970 } else if editor.focus_handle(cx).contains_focused(cx) {
971 editor.remove_keymap_context_layer::<Self>(cx);
972 }
973 });
974 }
975
976 fn unhook_vim_settings(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
977 if editor.mode() == EditorMode::Full {
978 editor.set_cursor_shape(CursorShape::Bar, cx);
979 editor.set_clip_at_line_ends(false, cx);
980 editor.set_collapse_matches(false);
981 editor.set_input_enabled(true);
982 editor.set_autoindent(true);
983 editor.selections.line_mode = false;
984 }
985 editor.remove_keymap_context_layer::<Self>(cx)
986 }
987}
988
989impl Settings for VimModeSetting {
990 const KEY: Option<&'static str> = Some("vim_mode");
991
992 type FileContent = Option<bool>;
993
994 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
995 Ok(Self(sources.user.copied().flatten().unwrap_or(
996 sources.default.ok_or_else(Self::missing_default)?,
997 )))
998 }
999}
1000
1001/// Controls when to use system clipboard.
1002#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
1003#[serde(rename_all = "snake_case")]
1004pub enum UseSystemClipboard {
1005 /// Don't use system clipboard.
1006 Never,
1007 /// Use system clipboard.
1008 Always,
1009 /// Use system clipboard for yank operations.
1010 OnYank,
1011}
1012
1013#[derive(Deserialize)]
1014struct VimSettings {
1015 // all vim uses vim clipboard
1016 // vim always uses system cliupbaord
1017 // some magic where yy is system and dd is not.
1018 pub use_system_clipboard: UseSystemClipboard,
1019 pub use_multiline_find: bool,
1020 pub use_smartcase_find: bool,
1021}
1022
1023#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
1024struct VimSettingsContent {
1025 pub use_system_clipboard: Option<UseSystemClipboard>,
1026 pub use_multiline_find: Option<bool>,
1027 pub use_smartcase_find: Option<bool>,
1028}
1029
1030impl Settings for VimSettings {
1031 const KEY: Option<&'static str> = Some("vim");
1032
1033 type FileContent = VimSettingsContent;
1034
1035 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1036 sources.json_merge()
1037 }
1038}