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