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