1//! Vim support for Zed.
2
3#[cfg(test)]
4mod test;
5
6mod command;
7mod editor_events;
8mod insert;
9mod mode_indicator;
10mod motion;
11mod normal;
12mod object;
13mod replace;
14mod state;
15mod utils;
16mod visual;
17
18use anyhow::Result;
19use collections::HashMap;
20use command_palette_hooks::{CommandPaletteFilter, CommandPaletteInterceptor};
21use editor::{
22 movement::{self, FindRange},
23 Editor, EditorEvent, EditorMode,
24};
25use gpui::{
26 actions, impl_actions, Action, AppContext, EntityId, FocusableView, Global, KeystrokeEvent,
27 Subscription, View, ViewContext, WeakView, WindowContext,
28};
29use language::{CursorShape, Point, Selection, SelectionGoal, TransactionId};
30pub use mode_indicator::ModeIndicator;
31use motion::Motion;
32use normal::normal_replace;
33use replace::multi_replace;
34use schemars::JsonSchema;
35use serde::Deserialize;
36use serde_derive::Serialize;
37use settings::{update_settings_file, Settings, SettingsStore};
38use state::{EditorState, Mode, Operator, RecordedSelection, WorkspaceState};
39use std::{ops::Range, sync::Arc};
40use ui::BorrowAppContext;
41use visual::{visual_block_motion, visual_replace};
42use workspace::{self, Workspace};
43
44use crate::state::ReplayableAction;
45
46/// Whether or not to enable Vim mode (work in progress).
47///
48/// Default: false
49pub struct VimModeSetting(pub bool);
50
51/// An Action to Switch between modes
52#[derive(Clone, Deserialize, PartialEq)]
53pub struct SwitchMode(pub Mode);
54
55/// PushOperator is used to put vim into a "minor" mode,
56/// where it's waiting for a specific next set of keystrokes.
57/// For example 'd' needs a motion to complete.
58#[derive(Clone, Deserialize, PartialEq)]
59pub struct PushOperator(pub Operator);
60
61/// Number is used to manage vim's count. Pushing a digit
62/// multiplis the current value by 10 and adds the digit.
63#[derive(Clone, Deserialize, PartialEq)]
64struct Number(usize);
65
66actions!(
67 vim,
68 [Tab, Enter, Object, InnerObject, FindForward, FindBackward]
69);
70
71// in the workspace namespace so it's not filtered out when vim is disabled.
72actions!(workspace, [ToggleVimMode]);
73
74impl_actions!(vim, [SwitchMode, PushOperator, Number]);
75
76/// Initializes the `vim` crate.
77pub fn init(cx: &mut AppContext) {
78 cx.set_global(Vim::default());
79 VimModeSetting::register(cx);
80 VimSettings::register(cx);
81
82 cx.observe_keystrokes(observe_keystrokes).detach();
83 editor_events::init(cx);
84
85 cx.observe_new_views(|workspace: &mut Workspace, cx| register(workspace, cx))
86 .detach();
87
88 // Any time settings change, update vim mode to match. The Vim struct
89 // will be initialized as disabled by default, so we filter its commands
90 // out when starting up.
91 CommandPaletteFilter::update_global(cx, |filter, _| {
92 filter.hide_namespace(Vim::NAMESPACE);
93 });
94 cx.update_global(|vim: &mut Vim, cx: &mut AppContext| {
95 vim.set_enabled(VimModeSetting::get_global(cx).0, cx)
96 });
97 cx.observe_global::<SettingsStore>(|cx| {
98 cx.update_global(|vim: &mut Vim, cx: &mut AppContext| {
99 vim.set_enabled(VimModeSetting::get_global(cx).0, cx)
100 });
101 })
102 .detach();
103}
104
105fn register(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
106 workspace.register_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {
107 Vim::update(cx, |vim, cx| vim.switch_mode(mode, false, cx))
108 });
109 workspace.register_action(
110 |_: &mut Workspace, PushOperator(operator): &PushOperator, cx| {
111 Vim::update(cx, |vim, cx| vim.push_operator(operator.clone(), cx))
112 },
113 );
114 workspace.register_action(|_: &mut Workspace, n: &Number, cx: _| {
115 Vim::update(cx, |vim, cx| vim.push_count_digit(n.0, cx));
116 });
117
118 workspace.register_action(|_: &mut Workspace, _: &Tab, cx| {
119 Vim::active_editor_input_ignored(" ".into(), cx)
120 });
121
122 workspace.register_action(|_: &mut Workspace, _: &Enter, cx| {
123 Vim::active_editor_input_ignored("\n".into(), cx)
124 });
125
126 workspace.register_action(|workspace: &mut Workspace, _: &ToggleVimMode, cx| {
127 let fs = workspace.app_state().fs.clone();
128 let currently_enabled = VimModeSetting::get_global(cx).0;
129 update_settings_file::<VimModeSetting>(fs, cx, move |setting| {
130 *setting = Some(!currently_enabled)
131 })
132 });
133
134 normal::register(workspace, cx);
135 insert::register(workspace, cx);
136 motion::register(workspace, cx);
137 command::register(workspace, cx);
138 replace::register(workspace, cx);
139 object::register(workspace, cx);
140 visual::register(workspace, cx);
141}
142
143/// Called whenever an keystroke is typed so vim can observe all actions
144/// and keystrokes accordingly.
145fn observe_keystrokes(keystroke_event: &KeystrokeEvent, cx: &mut WindowContext) {
146 if let Some(action) = keystroke_event
147 .action
148 .as_ref()
149 .map(|action| action.boxed_clone())
150 {
151 Vim::update(cx, |vim, _| {
152 if vim.workspace_state.recording {
153 vim.workspace_state
154 .recorded_actions
155 .push(ReplayableAction::Action(action.boxed_clone()));
156
157 if vim.workspace_state.stop_recording_after_next_action {
158 vim.workspace_state.recording = false;
159 vim.workspace_state.stop_recording_after_next_action = false;
160 }
161 }
162 });
163
164 // Keystroke is handled by the vim system, so continue forward
165 if action.name().starts_with("vim::") {
166 return;
167 }
168 } else if cx.has_pending_keystrokes() {
169 return;
170 }
171
172 Vim::update(cx, |vim, cx| match vim.active_operator() {
173 Some(Operator::FindForward { .. } | Operator::FindBackward { .. } | Operator::Replace) => {}
174 Some(_) => {
175 vim.clear_operator(cx);
176 }
177 _ => {}
178 });
179}
180
181/// The state pertaining to Vim mode.
182#[derive(Default)]
183struct Vim {
184 active_editor: Option<WeakView<Editor>>,
185 editor_subscription: Option<Subscription>,
186 enabled: bool,
187 editor_states: HashMap<EntityId, EditorState>,
188 workspace_state: WorkspaceState,
189 default_state: EditorState,
190}
191
192impl Global for Vim {}
193
194impl Vim {
195 /// The namespace for Vim actions.
196 const NAMESPACE: &'static str = "vim";
197
198 fn read(cx: &mut AppContext) -> &Self {
199 cx.global::<Self>()
200 }
201
202 fn update<F, S>(cx: &mut WindowContext, update: F) -> S
203 where
204 F: FnOnce(&mut Self, &mut WindowContext) -> S,
205 {
206 cx.update_global(update)
207 }
208
209 fn activate_editor(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
210 if !editor.read(cx).use_modal_editing() {
211 return;
212 }
213
214 self.active_editor = Some(editor.clone().downgrade());
215 self.editor_subscription = Some(cx.subscribe(&editor, |editor, event, cx| match event {
216 EditorEvent::SelectionsChanged { local: true } => {
217 let editor = editor.read(cx);
218 if editor.leader_peer_id().is_none() {
219 let newest = editor.selections.newest_anchor().clone();
220 let is_multicursor = editor.selections.count() > 1;
221 Vim::update(cx, |vim, cx| {
222 vim.local_selections_changed(newest, is_multicursor, cx);
223 })
224 }
225 }
226 EditorEvent::InputIgnored { text } => {
227 Vim::active_editor_input_ignored(text.clone(), cx);
228 Vim::record_insertion(text, None, cx)
229 }
230 EditorEvent::InputHandled {
231 text,
232 utf16_range_to_replace: range_to_replace,
233 } => Vim::record_insertion(text, range_to_replace.clone(), cx),
234 EditorEvent::TransactionBegun { transaction_id } => Vim::update(cx, |vim, cx| {
235 vim.transaction_begun(*transaction_id, cx);
236 }),
237 EditorEvent::TransactionUndone { transaction_id } => Vim::update(cx, |vim, cx| {
238 vim.transaction_undone(transaction_id, cx);
239 }),
240 _ => {}
241 }));
242
243 let editor = editor.read(cx);
244 let editor_mode = editor.mode();
245 let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
246
247 if editor_mode == EditorMode::Full
248 && !newest_selection_empty
249 && self.state().mode == Mode::Normal
250 // When following someone, don't switch vim mode.
251 && editor.leader_peer_id().is_none()
252 {
253 self.switch_mode(Mode::Visual, true, cx);
254 }
255
256 self.sync_vim_settings(cx);
257 }
258
259 fn record_insertion(
260 text: &Arc<str>,
261 range_to_replace: Option<Range<isize>>,
262 cx: &mut WindowContext,
263 ) {
264 Vim::update(cx, |vim, _| {
265 if vim.workspace_state.recording {
266 vim.workspace_state
267 .recorded_actions
268 .push(ReplayableAction::Insertion {
269 text: text.clone(),
270 utf16_range_to_replace: range_to_replace,
271 });
272 if vim.workspace_state.stop_recording_after_next_action {
273 vim.workspace_state.recording = false;
274 vim.workspace_state.stop_recording_after_next_action = false;
275 }
276 }
277 });
278 }
279
280 fn update_active_editor<S>(
281 &mut self,
282 cx: &mut WindowContext,
283 update: impl FnOnce(&mut Vim, &mut Editor, &mut ViewContext<Editor>) -> S,
284 ) -> Option<S> {
285 let editor = self.active_editor.clone()?.upgrade()?;
286 Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
287 }
288
289 /// When doing an action that modifies the buffer, we start recording so that `.`
290 /// will replay the action.
291 pub fn start_recording(&mut self, cx: &mut WindowContext) {
292 if !self.workspace_state.replaying {
293 self.workspace_state.recording = true;
294 self.workspace_state.recorded_actions = Default::default();
295 self.workspace_state.recorded_count = None;
296
297 let selections = self
298 .active_editor
299 .as_ref()
300 .and_then(|editor| editor.upgrade())
301 .map(|editor| {
302 let editor = editor.read(cx);
303 (
304 editor.selections.oldest::<Point>(cx),
305 editor.selections.newest::<Point>(cx),
306 )
307 });
308
309 if let Some((oldest, newest)) = selections {
310 self.workspace_state.recorded_selection = match self.state().mode {
311 Mode::Visual if newest.end.row == newest.start.row => {
312 RecordedSelection::SingleLine {
313 cols: newest.end.column - newest.start.column,
314 }
315 }
316 Mode::Visual => RecordedSelection::Visual {
317 rows: newest.end.row - newest.start.row,
318 cols: newest.end.column,
319 },
320 Mode::VisualLine => RecordedSelection::VisualLine {
321 rows: newest.end.row - newest.start.row,
322 },
323 Mode::VisualBlock => RecordedSelection::VisualBlock {
324 rows: newest.end.row.abs_diff(oldest.start.row),
325 cols: newest.end.column.abs_diff(oldest.start.column),
326 },
327 _ => RecordedSelection::None,
328 }
329 } else {
330 self.workspace_state.recorded_selection = RecordedSelection::None;
331 }
332 }
333 }
334
335 /// When finishing an action that modifies the buffer, stop recording.
336 /// as you usually call this within a keystroke handler we also ensure that
337 /// the current action is recorded.
338 pub fn stop_recording(&mut self) {
339 if self.workspace_state.recording {
340 self.workspace_state.stop_recording_after_next_action = true;
341 }
342 }
343
344 /// Stops recording actions immediately rather than waiting until after the
345 /// next action to stop recording.
346 ///
347 /// This doesn't include the current action.
348 pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>) {
349 if self.workspace_state.recording {
350 self.workspace_state
351 .recorded_actions
352 .push(ReplayableAction::Action(action.boxed_clone()));
353 self.workspace_state.recording = false;
354 self.workspace_state.stop_recording_after_next_action = false;
355 }
356 }
357
358 /// Explicitly record one action (equivalents to start_recording and stop_recording)
359 pub fn record_current_action(&mut self, cx: &mut WindowContext) {
360 self.start_recording(cx);
361 self.stop_recording();
362 }
363
364 fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut WindowContext) {
365 let state = self.state();
366 let last_mode = state.mode;
367 let prior_mode = state.last_mode;
368 let prior_tx = state.current_tx;
369 self.update_state(|state| {
370 state.last_mode = last_mode;
371 state.mode = mode;
372 state.operator_stack.clear();
373 state.current_tx.take();
374 state.current_anchor.take();
375 });
376 if mode != Mode::Insert {
377 self.take_count(cx);
378 }
379
380 // Sync editor settings like clip mode
381 self.sync_vim_settings(cx);
382
383 if leave_selections {
384 return;
385 }
386
387 // Adjust selections
388 self.update_active_editor(cx, |_, editor, cx| {
389 if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
390 {
391 visual_block_motion(true, editor, cx, |_, point, goal| Some((point, goal)))
392 }
393 if last_mode == Mode::Insert {
394 if let Some(prior_tx) = prior_tx {
395 editor.group_until_transaction(prior_tx, cx)
396 }
397 }
398
399 editor.change_selections(None, cx, |s| {
400 // we cheat with visual block mode and use multiple cursors.
401 // the cost of this cheat is we need to convert back to a single
402 // cursor whenever vim would.
403 if last_mode == Mode::VisualBlock
404 && (mode != Mode::VisualBlock && mode != Mode::Insert)
405 {
406 let tail = s.oldest_anchor().tail();
407 let head = s.newest_anchor().head();
408 s.select_anchor_ranges(vec![tail..head]);
409 } else if last_mode == Mode::Insert
410 && prior_mode == Mode::VisualBlock
411 && mode != Mode::VisualBlock
412 {
413 let pos = s.first_anchor().head();
414 s.select_anchor_ranges(vec![pos..pos])
415 }
416
417 s.move_with(|map, selection| {
418 if last_mode.is_visual() && !mode.is_visual() {
419 let mut point = selection.head();
420 if !selection.reversed && !selection.is_empty() {
421 point = movement::left(map, selection.head());
422 }
423 selection.collapse_to(point, selection.goal)
424 } else if !last_mode.is_visual() && mode.is_visual() {
425 if selection.is_empty() {
426 selection.end = movement::right(map, selection.start);
427 }
428 } else if last_mode == Mode::Replace {
429 if selection.head().column() != 0 {
430 let point = movement::left(map, selection.head());
431 selection.collapse_to(point, selection.goal)
432 }
433 }
434 });
435 })
436 });
437 }
438
439 fn push_count_digit(&mut self, number: usize, cx: &mut WindowContext) {
440 if self.active_operator().is_some() {
441 self.update_state(|state| {
442 state.post_count = Some(state.post_count.unwrap_or(0) * 10 + number)
443 })
444 } else {
445 self.update_state(|state| {
446 state.pre_count = Some(state.pre_count.unwrap_or(0) * 10 + number)
447 })
448 }
449 // update the keymap so that 0 works
450 self.sync_vim_settings(cx)
451 }
452
453 fn take_count(&mut self, cx: &mut WindowContext) -> Option<usize> {
454 if self.workspace_state.replaying {
455 return self.workspace_state.recorded_count;
456 }
457
458 let count = if self.state().post_count == None && self.state().pre_count == None {
459 return None;
460 } else {
461 Some(self.update_state(|state| {
462 state.post_count.take().unwrap_or(1) * state.pre_count.take().unwrap_or(1)
463 }))
464 };
465 if self.workspace_state.recording {
466 self.workspace_state.recorded_count = count;
467 }
468 self.sync_vim_settings(cx);
469 count
470 }
471
472 fn push_operator(&mut self, operator: Operator, cx: &mut WindowContext) {
473 if matches!(
474 operator,
475 Operator::Change | Operator::Delete | Operator::Replace
476 ) {
477 self.start_recording(cx)
478 };
479 self.update_state(|state| state.operator_stack.push(operator));
480 self.sync_vim_settings(cx);
481 }
482
483 fn maybe_pop_operator(&mut self) -> Option<Operator> {
484 self.update_state(|state| state.operator_stack.pop())
485 }
486
487 fn pop_operator(&mut self, cx: &mut WindowContext) -> Operator {
488 let popped_operator = self.update_state(|state| state.operator_stack.pop())
489 .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
490 self.sync_vim_settings(cx);
491 popped_operator
492 }
493 fn clear_operator(&mut self, cx: &mut WindowContext) {
494 self.take_count(cx);
495 self.update_state(|state| state.operator_stack.clear());
496 self.sync_vim_settings(cx);
497 }
498
499 fn active_operator(&self) -> Option<Operator> {
500 self.state().operator_stack.last().cloned()
501 }
502
503 fn transaction_begun(&mut self, transaction_id: TransactionId, _: &mut WindowContext) {
504 self.update_state(|state| {
505 let mode = if (state.mode == Mode::Insert || state.mode == Mode::Normal)
506 && state.current_tx.is_none()
507 {
508 state.current_tx = Some(transaction_id);
509 state.last_mode
510 } else {
511 state.mode
512 };
513 if mode == Mode::VisualLine || mode == Mode::VisualBlock {
514 state.undo_modes.insert(transaction_id, mode);
515 }
516 });
517 }
518
519 fn transaction_undone(&mut self, transaction_id: &TransactionId, cx: &mut WindowContext) {
520 if !self.state().mode.is_visual() {
521 return;
522 };
523 self.update_active_editor(cx, |vim, editor, cx| {
524 let original_mode = vim.state().undo_modes.get(transaction_id);
525 editor.change_selections(None, cx, |s| match original_mode {
526 Some(Mode::VisualLine) => {
527 s.move_with(|map, selection| {
528 selection.collapse_to(
529 map.prev_line_boundary(selection.start.to_point(map)).1,
530 SelectionGoal::None,
531 )
532 });
533 }
534 Some(Mode::VisualBlock) => {
535 let mut first = s.first_anchor();
536 first.collapse_to(first.start, first.goal);
537 s.select_anchors(vec![first]);
538 }
539 _ => {
540 s.move_with(|_, selection| {
541 selection.collapse_to(selection.start, selection.goal);
542 });
543 }
544 });
545 });
546 self.switch_mode(Mode::Normal, true, cx)
547 }
548
549 fn local_selections_changed(
550 &mut self,
551 newest: Selection<editor::Anchor>,
552 is_multicursor: bool,
553 cx: &mut WindowContext,
554 ) {
555 let state = self.state();
556 if state.mode == Mode::Insert && state.current_tx.is_some() {
557 if state.current_anchor.is_none() {
558 self.update_state(|state| state.current_anchor = Some(newest));
559 } else if state.current_anchor.as_ref().unwrap() != &newest {
560 if let Some(tx_id) = self.update_state(|state| state.current_tx.take()) {
561 self.update_active_editor(cx, |_, editor, cx| {
562 editor.group_until_transaction(tx_id, cx)
563 });
564 }
565 }
566 } else if state.mode == Mode::Normal && newest.start != newest.end {
567 if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
568 self.switch_mode(Mode::VisualBlock, false, cx);
569 } else {
570 self.switch_mode(Mode::Visual, false, cx)
571 }
572 } else if newest.start == newest.end
573 && !is_multicursor
574 && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&state.mode)
575 {
576 self.switch_mode(Mode::Normal, true, cx)
577 }
578 }
579
580 fn active_editor_input_ignored(text: Arc<str>, cx: &mut WindowContext) {
581 if text.is_empty() {
582 return;
583 }
584
585 match Vim::read(cx).active_operator() {
586 Some(Operator::FindForward { before }) => {
587 let find = Motion::FindForward {
588 before,
589 char: text.chars().next().unwrap(),
590 mode: if VimSettings::get_global(cx).use_multiline_find {
591 FindRange::MultiLine
592 } else {
593 FindRange::SingleLine
594 },
595 smartcase: VimSettings::get_global(cx).use_smartcase_find,
596 };
597 Vim::update(cx, |vim, _| {
598 vim.workspace_state.last_find = Some(find.clone())
599 });
600 motion::motion(find, cx)
601 }
602 Some(Operator::FindBackward { after }) => {
603 let find = Motion::FindBackward {
604 after,
605 char: text.chars().next().unwrap(),
606 mode: if VimSettings::get_global(cx).use_multiline_find {
607 FindRange::MultiLine
608 } else {
609 FindRange::SingleLine
610 },
611 smartcase: VimSettings::get_global(cx).use_smartcase_find,
612 };
613 Vim::update(cx, |vim, _| {
614 vim.workspace_state.last_find = Some(find.clone())
615 });
616 motion::motion(find, cx)
617 }
618 Some(Operator::Replace) => match Vim::read(cx).state().mode {
619 Mode::Normal => normal_replace(text, cx),
620 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => visual_replace(text, cx),
621 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
622 },
623 _ => match Vim::read(cx).state().mode {
624 Mode::Replace => multi_replace(text, cx),
625 _ => {}
626 },
627 }
628 }
629
630 fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
631 if self.enabled == enabled {
632 return;
633 }
634 if !enabled {
635 CommandPaletteInterceptor::update_global(cx, |interceptor, _| {
636 interceptor.clear();
637 });
638 CommandPaletteFilter::update_global(cx, |filter, _| {
639 filter.hide_namespace(Self::NAMESPACE);
640 });
641 *self = Default::default();
642 return;
643 }
644
645 self.enabled = true;
646 CommandPaletteFilter::update_global(cx, |filter, _| {
647 filter.show_namespace(Self::NAMESPACE);
648 });
649 CommandPaletteInterceptor::update_global(cx, |interceptor, _| {
650 interceptor.set(Box::new(command::command_interceptor));
651 });
652
653 if let Some(active_window) = cx
654 .active_window()
655 .and_then(|window| window.downcast::<Workspace>())
656 {
657 active_window
658 .update(cx, |workspace, cx| {
659 let active_editor = workspace.active_item_as::<Editor>(cx);
660 if let Some(active_editor) = active_editor {
661 self.activate_editor(active_editor, cx);
662 self.switch_mode(Mode::Normal, false, cx);
663 }
664 })
665 .ok();
666 }
667 }
668
669 /// Returns the state of the active editor.
670 pub fn state(&self) -> &EditorState {
671 if let Some(active_editor) = self.active_editor.as_ref() {
672 if let Some(state) = self.editor_states.get(&active_editor.entity_id()) {
673 return state;
674 }
675 }
676
677 &self.default_state
678 }
679
680 /// Updates the state of the active editor.
681 pub fn update_state<T>(&mut self, func: impl FnOnce(&mut EditorState) -> T) -> T {
682 let mut state = self.state().clone();
683 let ret = func(&mut state);
684
685 if let Some(active_editor) = self.active_editor.as_ref() {
686 self.editor_states.insert(active_editor.entity_id(), state);
687 }
688
689 ret
690 }
691
692 fn sync_vim_settings(&mut self, cx: &mut WindowContext) {
693 self.update_active_editor(cx, |vim, editor, cx| {
694 let state = vim.state();
695 editor.set_cursor_shape(state.cursor_shape(), cx);
696 editor.set_clip_at_line_ends(state.clip_at_line_ends(), cx);
697 editor.set_collapse_matches(true);
698 editor.set_input_enabled(!state.vim_controlled());
699 editor.set_autoindent(state.should_autoindent());
700 editor.selections.line_mode = matches!(state.mode, Mode::VisualLine);
701 if editor.is_focused(cx) {
702 editor.set_keymap_context_layer::<Self>(state.keymap_context_layer(), cx);
703 // disables vim if the rename editor is focused,
704 // but not if the command palette is open.
705 } else if editor.focus_handle(cx).contains_focused(cx) {
706 editor.remove_keymap_context_layer::<Self>(cx)
707 }
708 });
709 }
710
711 fn unhook_vim_settings(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
712 if editor.mode() == EditorMode::Full {
713 editor.set_cursor_shape(CursorShape::Bar, cx);
714 editor.set_clip_at_line_ends(false, cx);
715 editor.set_collapse_matches(false);
716 editor.set_input_enabled(true);
717 editor.set_autoindent(true);
718 editor.selections.line_mode = false;
719 }
720 editor.remove_keymap_context_layer::<Self>(cx)
721 }
722}
723
724impl Settings for VimModeSetting {
725 const KEY: Option<&'static str> = Some("vim_mode");
726
727 type FileContent = Option<bool>;
728
729 fn load(
730 default_value: &Self::FileContent,
731 user_values: &[&Self::FileContent],
732 _: &mut AppContext,
733 ) -> Result<Self> {
734 Ok(Self(user_values.iter().rev().find_map(|v| **v).unwrap_or(
735 default_value.ok_or_else(Self::missing_default)?,
736 )))
737 }
738}
739
740/// Controls when to use system clipboard.
741#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
742#[serde(rename_all = "snake_case")]
743pub enum UseSystemClipboard {
744 /// Don't use system clipboard.
745 Never,
746 /// Use system clipboard.
747 Always,
748 /// Use system clipboard for yank operations.
749 OnYank,
750}
751
752#[derive(Deserialize)]
753struct VimSettings {
754 // all vim uses vim clipboard
755 // vim always uses system cliupbaord
756 // some magic where yy is system and dd is not.
757 pub use_system_clipboard: UseSystemClipboard,
758 pub use_multiline_find: bool,
759 pub use_smartcase_find: bool,
760}
761
762#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
763struct VimSettingsContent {
764 pub use_system_clipboard: Option<UseSystemClipboard>,
765 pub use_multiline_find: Option<bool>,
766 pub use_smartcase_find: Option<bool>,
767}
768
769impl Settings for VimSettings {
770 const KEY: Option<&'static str> = Some("vim");
771
772 type FileContent = VimSettingsContent;
773
774 fn load(
775 default_value: &Self::FileContent,
776 user_values: &[&Self::FileContent],
777 _: &mut AppContext,
778 ) -> Result<Self> {
779 Self::load_via_json_merge(default_value, user_values)
780 }
781}