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