1//! Vim support for Zed.
2
3#[cfg(test)]
4mod test;
5
6mod change_list;
7mod command;
8mod editor_events;
9mod insert;
10mod mode_indicator;
11mod motion;
12mod normal;
13mod object;
14mod replace;
15mod state;
16mod surrounds;
17mod visual;
18
19use anyhow::Result;
20use change_list::push_to_change_list;
21use collections::HashMap;
22use command_palette_hooks::{CommandPaletteFilter, CommandPaletteInterceptor};
23use editor::{
24 movement::{self, FindRange},
25 Anchor, Bias, Editor, EditorEvent, EditorMode, ToPoint,
26};
27use gpui::{
28 actions, impl_actions, Action, AppContext, EntityId, FocusableView, Global, KeystrokeEvent,
29 Subscription, UpdateGlobal, View, ViewContext, WeakView, WindowContext,
30};
31use language::{CursorShape, Point, SelectionGoal, TransactionId};
32pub use mode_indicator::ModeIndicator;
33use motion::Motion;
34use normal::{
35 mark::create_visual_marks,
36 normal_replace,
37 repeat::{observe_action, observe_insertion, record_register, replay_register},
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, Register, WorkspaceState};
45use std::{ops::Range, sync::Arc};
46use surrounds::{add_surrounds, change_surrounds, delete_surrounds, SurroundsType};
47use ui::BorrowAppContext;
48use visual::{visual_block_motion, visual_replace};
49use workspace::{self, Workspace};
50
51use crate::state::ReplayableAction;
52
53/// Whether or not to enable Vim mode (work in progress).
54///
55/// Default: false
56pub struct VimModeSetting(pub bool);
57
58/// An Action to Switch between modes
59#[derive(Clone, Deserialize, PartialEq)]
60pub struct SwitchMode(pub Mode);
61
62/// PushOperator is used to put vim into a "minor" mode,
63/// where it's waiting for a specific next set of keystrokes.
64/// For example 'd' needs a motion to complete.
65#[derive(Clone, Deserialize, PartialEq)]
66pub struct PushOperator(pub Operator);
67
68/// Number is used to manage vim's count. Pushing a digit
69/// multiplis the current value by 10 and adds the digit.
70#[derive(Clone, Deserialize, PartialEq)]
71struct Number(usize);
72
73#[derive(Clone, Deserialize, PartialEq)]
74struct SelectRegister(String);
75
76actions!(
77 vim,
78 [
79 ClearOperators,
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, _: &ClearOperators, cx| {
134 Vim::update(cx, |vim, cx| vim.clear_operator(cx))
135 });
136 workspace.register_action(|_: &mut Workspace, n: &Number, cx: _| {
137 Vim::update(cx, |vim, cx| vim.push_count_digit(n.0, cx));
138 });
139 workspace.register_action(|_: &mut Workspace, _: &Tab, cx| {
140 Vim::active_editor_input_ignored(" ".into(), cx)
141 });
142
143 workspace.register_action(|_: &mut Workspace, _: &Enter, cx| {
144 Vim::active_editor_input_ignored("\n".into(), cx)
145 });
146
147 workspace.register_action(|workspace: &mut Workspace, _: &ToggleVimMode, cx| {
148 let fs = workspace.app_state().fs.clone();
149 let currently_enabled = VimModeSetting::get_global(cx).0;
150 update_settings_file::<VimModeSetting>(fs, cx, move |setting| {
151 *setting = Some(!currently_enabled)
152 })
153 });
154
155 workspace.register_action(|_: &mut Workspace, _: &OpenDefaultKeymap, cx| {
156 cx.emit(workspace::Event::OpenBundledFile {
157 text: settings::vim_keymap(),
158 title: "Default Vim Bindings",
159 language: "JSON",
160 });
161 });
162
163 normal::register(workspace, cx);
164 insert::register(workspace, cx);
165 motion::register(workspace, cx);
166 command::register(workspace, cx);
167 replace::register(workspace, cx);
168 object::register(workspace, cx);
169 visual::register(workspace, cx);
170 change_list::register(workspace, cx);
171}
172
173/// Called whenever an keystroke is typed so vim can observe all actions
174/// and keystrokes accordingly.
175fn observe_keystrokes(keystroke_event: &KeystrokeEvent, cx: &mut WindowContext) {
176 if let Some(action) = keystroke_event
177 .action
178 .as_ref()
179 .map(|action| action.boxed_clone())
180 {
181 observe_action(action.boxed_clone(), cx);
182
183 // Keystroke is handled by the vim system, so continue forward
184 if action.name().starts_with("vim::") {
185 return;
186 }
187 } else if cx.has_pending_keystrokes() || keystroke_event.keystroke.is_ime_in_progress() {
188 return;
189 }
190
191 Vim::update(cx, |vim, cx| match vim.active_operator() {
192 Some(
193 Operator::FindForward { .. }
194 | Operator::FindBackward { .. }
195 | Operator::Replace
196 | Operator::AddSurrounds { .. }
197 | Operator::ChangeSurrounds { .. }
198 | Operator::DeleteSurrounds
199 | Operator::Mark
200 | Operator::Jump { .. }
201 | Operator::Register
202 | Operator::RecordRegister
203 | Operator::ReplayRegister,
204 ) => {}
205 Some(_) => {
206 vim.clear_operator(cx);
207 }
208 _ => {}
209 });
210}
211
212/// The state pertaining to Vim mode.
213#[derive(Default)]
214struct Vim {
215 active_editor: Option<WeakView<Editor>>,
216 editor_subscription: Option<Subscription>,
217 enabled: bool,
218 editor_states: HashMap<EntityId, EditorState>,
219 workspace_state: WorkspaceState,
220 default_state: EditorState,
221}
222
223impl Global for Vim {}
224
225impl Vim {
226 /// The namespace for Vim actions.
227 const NAMESPACE: &'static str = "vim";
228
229 fn read(cx: &mut AppContext) -> &Self {
230 cx.global::<Self>()
231 }
232
233 fn update<F, S>(cx: &mut WindowContext, update: F) -> S
234 where
235 F: FnOnce(&mut Self, &mut WindowContext) -> S,
236 {
237 cx.update_global(update)
238 }
239
240 fn activate_editor(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
241 if !editor.read(cx).use_modal_editing() {
242 return;
243 }
244
245 self.active_editor = Some(editor.clone().downgrade());
246 self.editor_subscription = Some(cx.subscribe(&editor, |editor, event, cx| match event {
247 EditorEvent::SelectionsChanged { local: true } => {
248 if editor.read(cx).leader_peer_id().is_none() {
249 Vim::update(cx, |vim, cx| {
250 vim.local_selections_changed(editor, cx);
251 })
252 }
253 }
254 EditorEvent::InputIgnored { text } => {
255 Vim::active_editor_input_ignored(text.clone(), cx);
256 observe_insertion(text, None, cx)
257 }
258 EditorEvent::InputHandled {
259 text,
260 utf16_range_to_replace: range_to_replace,
261 } => observe_insertion(text, range_to_replace.clone(), cx),
262 EditorEvent::TransactionBegun { transaction_id } => Vim::update(cx, |vim, cx| {
263 vim.transaction_begun(*transaction_id, cx);
264 }),
265 EditorEvent::TransactionUndone { transaction_id } => Vim::update(cx, |vim, cx| {
266 vim.transaction_undone(transaction_id, cx);
267 }),
268 EditorEvent::Edited { .. } => {
269 Vim::update(cx, |vim, cx| vim.transaction_ended(editor, cx))
270 }
271 _ => {}
272 }));
273
274 let editor = editor.read(cx);
275 let editor_mode = editor.mode();
276 let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
277
278 if editor_mode == EditorMode::Full
279 && !newest_selection_empty
280 && self.state().mode == Mode::Normal
281 // When following someone, don't switch vim mode.
282 && editor.leader_peer_id().is_none()
283 {
284 self.switch_mode(Mode::Visual, true, cx);
285 }
286
287 self.sync_vim_settings(cx);
288 }
289
290 fn update_active_editor<S>(
291 &mut self,
292 cx: &mut WindowContext,
293 update: impl FnOnce(&mut Vim, &mut Editor, &mut ViewContext<Editor>) -> S,
294 ) -> Option<S> {
295 let editor = self.active_editor.clone()?.upgrade()?;
296 Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
297 }
298
299 fn editor_selections(&mut self, cx: &mut WindowContext) -> Vec<Range<Anchor>> {
300 self.update_active_editor(cx, |_, editor, _| {
301 editor
302 .selections
303 .disjoint_anchors()
304 .iter()
305 .map(|selection| selection.tail()..selection.head())
306 .collect()
307 })
308 .unwrap_or_default()
309 }
310
311 /// When doing an action that modifies the buffer, we start recording so that `.`
312 /// will replay the action.
313 pub fn start_recording(&mut self, cx: &mut WindowContext) {
314 if !self.workspace_state.dot_replaying {
315 self.workspace_state.dot_recording = true;
316 self.workspace_state.recorded_actions = Default::default();
317 self.workspace_state.recorded_count = None;
318
319 let selections = self
320 .active_editor
321 .as_ref()
322 .and_then(|editor| editor.upgrade())
323 .map(|editor| {
324 let editor = editor.read(cx);
325 (
326 editor.selections.oldest::<Point>(cx),
327 editor.selections.newest::<Point>(cx),
328 )
329 });
330
331 if let Some((oldest, newest)) = selections {
332 self.workspace_state.recorded_selection = match self.state().mode {
333 Mode::Visual if newest.end.row == newest.start.row => {
334 RecordedSelection::SingleLine {
335 cols: newest.end.column - newest.start.column,
336 }
337 }
338 Mode::Visual => RecordedSelection::Visual {
339 rows: newest.end.row - newest.start.row,
340 cols: newest.end.column,
341 },
342 Mode::VisualLine => RecordedSelection::VisualLine {
343 rows: newest.end.row - newest.start.row,
344 },
345 Mode::VisualBlock => RecordedSelection::VisualBlock {
346 rows: newest.end.row.abs_diff(oldest.start.row),
347 cols: newest.end.column.abs_diff(oldest.start.column),
348 },
349 _ => RecordedSelection::None,
350 }
351 } else {
352 self.workspace_state.recorded_selection = RecordedSelection::None;
353 }
354 }
355 }
356
357 pub fn stop_replaying(&mut self, _: &mut WindowContext) {
358 self.workspace_state.dot_replaying = false;
359 if let Some(replayer) = self.workspace_state.replayer.take() {
360 replayer.stop();
361 }
362 }
363
364 /// When finishing an action that modifies the buffer, stop recording.
365 /// as you usually call this within a keystroke handler we also ensure that
366 /// the current action is recorded.
367 pub fn stop_recording(&mut self) {
368 if self.workspace_state.dot_recording {
369 self.workspace_state.stop_recording_after_next_action = true;
370 }
371 }
372
373 /// Stops recording actions immediately rather than waiting until after the
374 /// next action to stop recording.
375 ///
376 /// This doesn't include the current action.
377 pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>) {
378 if self.workspace_state.dot_recording {
379 self.workspace_state
380 .recorded_actions
381 .push(ReplayableAction::Action(action.boxed_clone()));
382 self.workspace_state.dot_recording = false;
383 self.workspace_state.stop_recording_after_next_action = false;
384 }
385 }
386
387 /// Explicitly record one action (equivalents to start_recording and stop_recording)
388 pub fn record_current_action(&mut self, cx: &mut WindowContext) {
389 self.start_recording(cx);
390 self.stop_recording();
391 }
392
393 fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut WindowContext) {
394 let state = self.state();
395 let last_mode = state.mode;
396 let prior_mode = state.last_mode;
397 let prior_tx = state.current_tx;
398 self.update_state(|state| {
399 state.last_mode = last_mode;
400 state.mode = mode;
401 state.operator_stack.clear();
402 if mode == Mode::Normal || mode != last_mode {
403 state.current_tx.take();
404 state.current_anchor.take();
405 }
406 });
407 if mode != Mode::Insert && mode != Mode::Replace {
408 self.take_count(cx);
409 }
410
411 // Sync editor settings like clip mode
412 self.sync_vim_settings(cx);
413
414 if !mode.is_visual() && last_mode.is_visual() {
415 create_visual_marks(self, last_mode, cx);
416 }
417
418 if leave_selections {
419 return;
420 }
421
422 // Adjust selections
423 self.update_active_editor(cx, |_, editor, cx| {
424 if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
425 {
426 visual_block_motion(true, editor, cx, |_, point, goal| Some((point, goal)))
427 }
428 if last_mode == Mode::Insert || last_mode == Mode::Replace {
429 if let Some(prior_tx) = prior_tx {
430 editor.group_until_transaction(prior_tx, cx)
431 }
432 }
433
434 editor.change_selections(None, cx, |s| {
435 // we cheat with visual block mode and use multiple cursors.
436 // the cost of this cheat is we need to convert back to a single
437 // cursor whenever vim would.
438 if last_mode == Mode::VisualBlock
439 && (mode != Mode::VisualBlock && mode != Mode::Insert)
440 {
441 let tail = s.oldest_anchor().tail();
442 let head = s.newest_anchor().head();
443 s.select_anchor_ranges(vec![tail..head]);
444 } else if last_mode == Mode::Insert
445 && prior_mode == Mode::VisualBlock
446 && mode != Mode::VisualBlock
447 {
448 let pos = s.first_anchor().head();
449 s.select_anchor_ranges(vec![pos..pos])
450 }
451
452 let snapshot = s.display_map();
453 if let Some(pending) = s.pending.as_mut() {
454 if pending.selection.reversed && mode.is_visual() && !last_mode.is_visual() {
455 let mut end = pending.selection.end.to_point(&snapshot.buffer_snapshot);
456 end = snapshot
457 .buffer_snapshot
458 .clip_point(end + Point::new(0, 1), Bias::Right);
459 pending.selection.end = snapshot.buffer_snapshot.anchor_before(end);
460 }
461 }
462
463 s.move_with(|map, selection| {
464 if last_mode.is_visual() && !mode.is_visual() {
465 let mut point = selection.head();
466 if !selection.reversed && !selection.is_empty() {
467 point = movement::left(map, selection.head());
468 }
469 selection.collapse_to(point, selection.goal)
470 } else if !last_mode.is_visual() && mode.is_visual() {
471 if selection.is_empty() {
472 selection.end = movement::right(map, selection.start);
473 }
474 }
475 });
476 })
477 });
478 }
479
480 fn push_count_digit(&mut self, number: usize, cx: &mut WindowContext) {
481 if self.active_operator().is_some() {
482 self.update_state(|state| {
483 state.post_count = Some(state.post_count.unwrap_or(0) * 10 + number)
484 })
485 } else {
486 self.update_state(|state| {
487 state.pre_count = Some(state.pre_count.unwrap_or(0) * 10 + number)
488 })
489 }
490 // update the keymap so that 0 works
491 self.sync_vim_settings(cx)
492 }
493
494 fn take_count(&mut self, cx: &mut WindowContext) -> Option<usize> {
495 if self.workspace_state.dot_replaying {
496 return self.workspace_state.recorded_count;
497 }
498
499 let count = if self.state().post_count == None && self.state().pre_count == None {
500 return None;
501 } else {
502 Some(self.update_state(|state| {
503 state.post_count.take().unwrap_or(1) * state.pre_count.take().unwrap_or(1)
504 }))
505 };
506 if self.workspace_state.dot_recording {
507 self.workspace_state.recorded_count = count;
508 }
509 self.sync_vim_settings(cx);
510 count
511 }
512
513 fn select_register(&mut self, register: Arc<str>, cx: &mut WindowContext) {
514 self.update_state(|state| {
515 if register.chars().count() == 1 {
516 state
517 .selected_register
518 .replace(register.chars().next().unwrap());
519 }
520 state.operator_stack.clear();
521 });
522 self.sync_vim_settings(cx);
523 }
524
525 fn write_registers(
526 &mut self,
527 content: Register,
528 register: Option<char>,
529 is_yank: bool,
530 linewise: bool,
531 cx: &mut ViewContext<Editor>,
532 ) {
533 if let Some(register) = register {
534 let lower = register.to_lowercase().next().unwrap_or(register);
535 if lower != register {
536 let current = self.workspace_state.registers.entry(lower).or_default();
537 current.text = (current.text.to_string() + &content.text).into();
538 // not clear how to support appending to registers with multiple cursors
539 current.clipboard_selections.take();
540 let yanked = current.clone();
541 self.workspace_state.registers.insert('"', yanked);
542 } else {
543 self.workspace_state.registers.insert('"', content.clone());
544 match lower {
545 '_' | ':' | '.' | '%' | '#' | '=' | '/' => {}
546 '+' => {
547 cx.write_to_clipboard(content.into());
548 }
549 '*' => {
550 #[cfg(target_os = "linux")]
551 cx.write_to_primary(content.into());
552 #[cfg(not(target_os = "linux"))]
553 cx.write_to_clipboard(content.into());
554 }
555 '"' => {
556 self.workspace_state.registers.insert('0', content.clone());
557 self.workspace_state.registers.insert('"', content);
558 }
559 _ => {
560 self.workspace_state.registers.insert(lower, content);
561 }
562 }
563 }
564 } else {
565 let setting = VimSettings::get_global(cx).use_system_clipboard;
566 if setting == UseSystemClipboard::Always
567 || setting == UseSystemClipboard::OnYank && is_yank
568 {
569 self.workspace_state.last_yank.replace(content.text.clone());
570 cx.write_to_clipboard(content.clone().into());
571 } else {
572 self.workspace_state.last_yank = cx
573 .read_from_clipboard()
574 .map(|item| item.text().to_owned().into());
575 }
576
577 self.workspace_state.registers.insert('"', content.clone());
578 if is_yank {
579 self.workspace_state.registers.insert('0', content);
580 } else {
581 let contains_newline = content.text.contains('\n');
582 if !contains_newline {
583 self.workspace_state.registers.insert('-', content.clone());
584 }
585 if linewise || contains_newline {
586 let mut content = content;
587 for i in '1'..'8' {
588 if let Some(moved) = self.workspace_state.registers.insert(i, content) {
589 content = moved;
590 } else {
591 break;
592 }
593 }
594 }
595 }
596 }
597 }
598
599 fn read_register(
600 &mut self,
601 register: Option<char>,
602 editor: Option<&mut Editor>,
603 cx: &mut WindowContext,
604 ) -> Option<Register> {
605 let Some(register) = register.filter(|reg| *reg != '"') else {
606 let setting = VimSettings::get_global(cx).use_system_clipboard;
607 return match setting {
608 UseSystemClipboard::Always => cx.read_from_clipboard().map(|item| item.into()),
609 UseSystemClipboard::OnYank if self.system_clipboard_is_newer(cx) => {
610 cx.read_from_clipboard().map(|item| item.into())
611 }
612 _ => self.workspace_state.registers.get(&'"').cloned(),
613 };
614 };
615 let lower = register.to_lowercase().next().unwrap_or(register);
616 match lower {
617 '_' | ':' | '.' | '#' | '=' => None,
618 '+' => cx.read_from_clipboard().map(|item| item.into()),
619 '*' => {
620 #[cfg(target_os = "linux")]
621 {
622 cx.read_from_primary().map(|item| item.into())
623 }
624 #[cfg(not(target_os = "linux"))]
625 {
626 cx.read_from_clipboard().map(|item| item.into())
627 }
628 }
629 '%' => editor.and_then(|editor| {
630 let selection = editor.selections.newest::<Point>(cx);
631 if let Some((_, buffer, _)) = editor
632 .buffer()
633 .read(cx)
634 .excerpt_containing(selection.head(), cx)
635 {
636 buffer
637 .read(cx)
638 .file()
639 .map(|file| file.path().to_string_lossy().to_string().into())
640 } else {
641 None
642 }
643 }),
644 _ => self.workspace_state.registers.get(&lower).cloned(),
645 }
646 }
647
648 fn system_clipboard_is_newer(&self, cx: &mut AppContext) -> bool {
649 cx.read_from_clipboard().is_some_and(|item| {
650 if let Some(last_state) = &self.workspace_state.last_yank {
651 last_state != item.text()
652 } else {
653 true
654 }
655 })
656 }
657
658 fn push_operator(&mut self, operator: Operator, cx: &mut WindowContext) {
659 if matches!(
660 operator,
661 Operator::Change
662 | Operator::Delete
663 | Operator::Replace
664 | Operator::Indent
665 | Operator::Outdent
666 | Operator::Lowercase
667 | Operator::Uppercase
668 | Operator::OppositeCase
669 ) {
670 self.start_recording(cx)
671 };
672 // Since these operations can only be entered with pre-operators,
673 // we need to clear the previous operators when pushing,
674 // so that the current stack is the most correct
675 if matches!(
676 operator,
677 Operator::AddSurrounds { .. }
678 | Operator::ChangeSurrounds { .. }
679 | Operator::DeleteSurrounds
680 ) {
681 self.update_state(|state| state.operator_stack.clear());
682 };
683 self.update_state(|state| state.operator_stack.push(operator));
684 self.sync_vim_settings(cx);
685 }
686
687 fn maybe_pop_operator(&mut self) -> Option<Operator> {
688 self.update_state(|state| state.operator_stack.pop())
689 }
690
691 fn pop_operator(&mut self, cx: &mut WindowContext) -> Operator {
692 let popped_operator = self.update_state(|state| state.operator_stack.pop())
693 .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
694 self.sync_vim_settings(cx);
695 popped_operator
696 }
697
698 fn clear_operator(&mut self, cx: &mut WindowContext) {
699 self.take_count(cx);
700 self.update_state(|state| {
701 state.selected_register.take();
702 state.operator_stack.clear()
703 });
704 self.sync_vim_settings(cx);
705 }
706
707 fn active_operator(&self) -> Option<Operator> {
708 self.state().operator_stack.last().cloned()
709 }
710
711 fn transaction_begun(&mut self, transaction_id: TransactionId, _: &mut WindowContext) {
712 self.update_state(|state| {
713 let mode = if (state.mode == Mode::Insert
714 || state.mode == Mode::Replace
715 || state.mode == Mode::Normal)
716 && state.current_tx.is_none()
717 {
718 state.current_tx = Some(transaction_id);
719 state.last_mode
720 } else {
721 state.mode
722 };
723 if mode == Mode::VisualLine || mode == Mode::VisualBlock {
724 state.undo_modes.insert(transaction_id, mode);
725 }
726 });
727 }
728
729 fn transaction_undone(&mut self, transaction_id: &TransactionId, cx: &mut WindowContext) {
730 match self.state().mode {
731 Mode::VisualLine | Mode::VisualBlock | Mode::Visual => {
732 self.update_active_editor(cx, |vim, editor, cx| {
733 let original_mode = vim.state().undo_modes.get(transaction_id);
734 editor.change_selections(None, cx, |s| match original_mode {
735 Some(Mode::VisualLine) => {
736 s.move_with(|map, selection| {
737 selection.collapse_to(
738 map.prev_line_boundary(selection.start.to_point(map)).1,
739 SelectionGoal::None,
740 )
741 });
742 }
743 Some(Mode::VisualBlock) => {
744 let mut first = s.first_anchor();
745 first.collapse_to(first.start, first.goal);
746 s.select_anchors(vec![first]);
747 }
748 _ => {
749 s.move_with(|map, selection| {
750 selection.collapse_to(
751 map.clip_at_line_end(selection.start),
752 selection.goal,
753 );
754 });
755 }
756 });
757 });
758 self.switch_mode(Mode::Normal, true, cx)
759 }
760 Mode::Normal => {
761 self.update_active_editor(cx, |_, editor, cx| {
762 editor.change_selections(None, cx, |s| {
763 s.move_with(|map, selection| {
764 selection
765 .collapse_to(map.clip_at_line_end(selection.end), selection.goal)
766 })
767 })
768 });
769 }
770 Mode::Insert | Mode::Replace => {}
771 }
772 }
773
774 fn transaction_ended(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
775 push_to_change_list(self, editor, cx)
776 }
777
778 fn local_selections_changed(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
779 let newest = editor.read(cx).selections.newest_anchor().clone();
780 let is_multicursor = editor.read(cx).selections.count() > 1;
781
782 let state = self.state();
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 } else if newest.start == newest.end
800 && !is_multicursor
801 && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&state.mode)
802 {
803 self.switch_mode(Mode::Normal, true, cx);
804 }
805 }
806
807 fn active_editor_input_ignored(text: Arc<str>, cx: &mut WindowContext) {
808 if text.is_empty() {
809 return;
810 }
811
812 match Vim::read(cx).active_operator() {
813 Some(Operator::FindForward { before }) => {
814 let find = Motion::FindForward {
815 before,
816 char: text.chars().next().unwrap(),
817 mode: if VimSettings::get_global(cx).use_multiline_find {
818 FindRange::MultiLine
819 } else {
820 FindRange::SingleLine
821 },
822 smartcase: VimSettings::get_global(cx).use_smartcase_find,
823 };
824 Vim::update(cx, |vim, _| {
825 vim.workspace_state.last_find = Some(find.clone())
826 });
827 motion::motion(find, cx)
828 }
829 Some(Operator::FindBackward { after }) => {
830 let find = Motion::FindBackward {
831 after,
832 char: text.chars().next().unwrap(),
833 mode: if VimSettings::get_global(cx).use_multiline_find {
834 FindRange::MultiLine
835 } else {
836 FindRange::SingleLine
837 },
838 smartcase: VimSettings::get_global(cx).use_smartcase_find,
839 };
840 Vim::update(cx, |vim, _| {
841 vim.workspace_state.last_find = Some(find.clone())
842 });
843 motion::motion(find, cx)
844 }
845 Some(Operator::Replace) => match Vim::read(cx).state().mode {
846 Mode::Normal => normal_replace(text, cx),
847 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => visual_replace(text, cx),
848 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
849 },
850 Some(Operator::AddSurrounds { target }) => match Vim::read(cx).state().mode {
851 Mode::Normal => {
852 if let Some(target) = target {
853 add_surrounds(text, target, cx);
854 Vim::update(cx, |vim, cx| vim.clear_operator(cx));
855 }
856 }
857 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
858 add_surrounds(text, SurroundsType::Selection, cx);
859 Vim::update(cx, |vim, cx| vim.clear_operator(cx));
860 }
861 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
862 },
863 Some(Operator::ChangeSurrounds { target }) => match Vim::read(cx).state().mode {
864 Mode::Normal => {
865 if let Some(target) = target {
866 change_surrounds(text, target, cx);
867 Vim::update(cx, |vim, cx| vim.clear_operator(cx));
868 }
869 }
870 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
871 },
872 Some(Operator::DeleteSurrounds) => match Vim::read(cx).state().mode {
873 Mode::Normal => {
874 delete_surrounds(text, cx);
875 Vim::update(cx, |vim, cx| vim.clear_operator(cx));
876 }
877 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
878 },
879 Some(Operator::Mark) => Vim::update(cx, |vim, cx| {
880 normal::mark::create_mark(vim, text, false, cx)
881 }),
882 Some(Operator::RecordRegister) => record_register(text.chars().next().unwrap(), cx),
883 Some(Operator::ReplayRegister) => replay_register(text.chars().next().unwrap(), cx),
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.editor_input_enabled());
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}