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