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