1#[cfg(test)]
2mod test;
3
4mod command;
5mod editor_events;
6mod insert;
7mod mode_indicator;
8mod motion;
9mod normal;
10mod object;
11mod state;
12mod utils;
13mod visual;
14
15use anyhow::Result;
16use collections::{CommandPaletteFilter, HashMap};
17use command_palette::CommandPaletteInterceptor;
18use editor::{movement, Editor, EditorEvent, EditorMode};
19use gpui::{
20 actions, impl_actions, Action, AppContext, EntityId, KeyContext, Subscription, View,
21 ViewContext, WeakView, WindowContext,
22};
23use language::{CursorShape, Point, Selection, SelectionGoal};
24pub use mode_indicator::ModeIndicator;
25use motion::Motion;
26use normal::normal_replace;
27use serde::Deserialize;
28use settings::{update_settings_file, Settings, SettingsStore};
29use state::{EditorState, Mode, Operator, RecordedSelection, WorkspaceState};
30use std::{ops::Range, sync::Arc};
31use visual::{visual_block_motion, visual_replace};
32use workspace::{self, Workspace};
33
34use crate::state::ReplayableAction;
35
36pub struct VimModeSetting(pub bool);
37
38#[derive(Clone, Deserialize, PartialEq)]
39pub struct SwitchMode(pub Mode);
40
41#[derive(Clone, Deserialize, PartialEq)]
42pub struct PushOperator(pub Operator);
43
44#[derive(Clone, Deserialize, PartialEq)]
45struct Number(usize);
46
47actions!(
48 vim,
49 [Tab, Enter, Object, InnerObject, FindForward, FindBackward]
50);
51// in the workspace namespace so it's not filtered out when vim is disabled.
52actions!(workspace, [ToggleVimMode]);
53
54impl_actions!(vim, [SwitchMode, PushOperator, Number]);
55
56pub fn init(cx: &mut AppContext) {
57 cx.set_global(Vim::default());
58 VimModeSetting::register(cx);
59
60 editor_events::init(cx);
61
62 cx.observe_new_views(|workspace: &mut Workspace, cx| register(workspace, cx))
63 .detach();
64
65 // Any time settings change, update vim mode to match. The Vim struct
66 // will be initialized as disabled by default, so we filter its commands
67 // out when starting up.
68 cx.update_global::<CommandPaletteFilter, _>(|filter, _| {
69 filter.hidden_namespaces.insert("vim");
70 });
71 cx.update_global(|vim: &mut Vim, cx: &mut AppContext| {
72 vim.set_enabled(VimModeSetting::get_global(cx).0, cx)
73 });
74 cx.observe_global::<SettingsStore>(|cx| {
75 cx.update_global(|vim: &mut Vim, cx: &mut AppContext| {
76 vim.set_enabled(VimModeSetting::get_global(cx).0, cx)
77 });
78 })
79 .detach();
80}
81
82fn register(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
83 workspace.register_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {
84 Vim::update(cx, |vim, cx| vim.switch_mode(mode, false, cx))
85 });
86 workspace.register_action(
87 |_: &mut Workspace, &PushOperator(operator): &PushOperator, cx| {
88 Vim::update(cx, |vim, cx| vim.push_operator(operator, cx))
89 },
90 );
91 workspace.register_action(|_: &mut Workspace, n: &Number, cx: _| {
92 Vim::update(cx, |vim, cx| vim.push_count_digit(n.0, cx));
93 });
94
95 workspace.register_action(|_: &mut Workspace, _: &Tab, cx| {
96 Vim::active_editor_input_ignored(" ".into(), cx)
97 });
98
99 workspace.register_action(|_: &mut Workspace, _: &Enter, cx| {
100 Vim::active_editor_input_ignored("\n".into(), cx)
101 });
102
103 workspace.register_action(|workspace: &mut Workspace, _: &ToggleVimMode, cx| {
104 let fs = workspace.app_state().fs.clone();
105 let currently_enabled = VimModeSetting::get_global(cx).0;
106 update_settings_file::<VimModeSetting>(fs, cx, move |setting| {
107 *setting = Some(!currently_enabled)
108 })
109 });
110
111 normal::register(workspace, cx);
112 insert::register(workspace, cx);
113 motion::register(workspace, cx);
114 command::register(workspace, cx);
115 object::register(workspace, cx);
116 visual::register(workspace, cx);
117}
118
119pub fn observe_keystrokes(cx: &mut WindowContext) {
120 cx.observe_keystrokes(|keystroke_event, cx| {
121 if let Some(action) = keystroke_event
122 .action
123 .as_ref()
124 .map(|action| action.boxed_clone())
125 {
126 Vim::update(cx, |vim, _| {
127 if vim.workspace_state.recording {
128 vim.workspace_state
129 .recorded_actions
130 .push(ReplayableAction::Action(action.boxed_clone()));
131
132 if vim.workspace_state.stop_recording_after_next_action {
133 vim.workspace_state.recording = false;
134 vim.workspace_state.stop_recording_after_next_action = false;
135 }
136 }
137 });
138
139 // Keystroke is handled by the vim system, so continue forward
140 if action.name().starts_with("vim::") {
141 return;
142 }
143 }
144
145 Vim::update(cx, |vim, cx| match vim.active_operator() {
146 Some(
147 Operator::FindForward { .. } | Operator::FindBackward { .. } | Operator::Replace,
148 ) => {}
149 Some(_) => {
150 vim.clear_operator(cx);
151 }
152 _ => {}
153 });
154 })
155 .detach()
156}
157
158#[derive(Default)]
159pub struct Vim {
160 active_editor: Option<WeakView<Editor>>,
161 editor_subscription: Option<Subscription>,
162 enabled: bool,
163 editor_states: HashMap<EntityId, EditorState>,
164 workspace_state: WorkspaceState,
165 default_state: EditorState,
166}
167
168impl Vim {
169 fn read(cx: &mut AppContext) -> &Self {
170 cx.global::<Self>()
171 }
172
173 fn update<F, S>(cx: &mut WindowContext, update: F) -> S
174 where
175 F: FnOnce(&mut Self, &mut WindowContext) -> S,
176 {
177 cx.update_global(update)
178 }
179
180 fn set_active_editor(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
181 self.active_editor = Some(editor.clone().downgrade());
182 self.editor_subscription = Some(cx.subscribe(&editor, |editor, event, cx| match event {
183 EditorEvent::SelectionsChanged { local: true } => {
184 let editor = editor.read(cx);
185 if editor.leader_peer_id().is_none() {
186 let newest = editor.selections.newest::<usize>(cx);
187 local_selections_changed(newest, cx);
188 }
189 }
190 EditorEvent::InputIgnored { text } => {
191 Vim::active_editor_input_ignored(text.clone(), cx);
192 Vim::record_insertion(text, None, cx)
193 }
194 EditorEvent::InputHandled {
195 text,
196 utf16_range_to_replace: range_to_replace,
197 } => Vim::record_insertion(text, range_to_replace.clone(), cx),
198 _ => {}
199 }));
200
201 if self.enabled {
202 let editor = editor.read(cx);
203 let editor_mode = editor.mode();
204 let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
205
206 if editor_mode == EditorMode::Full
207 && !newest_selection_empty
208 && self.state().mode == Mode::Normal
209 // When following someone, don't switch vim mode.
210 && editor.leader_peer_id().is_none()
211 {
212 self.switch_mode(Mode::Visual, true, cx);
213 }
214 }
215
216 self.sync_vim_settings(cx);
217 }
218
219 fn record_insertion(
220 text: &Arc<str>,
221 range_to_replace: Option<Range<isize>>,
222 cx: &mut WindowContext,
223 ) {
224 Vim::update(cx, |vim, _| {
225 if vim.workspace_state.recording {
226 vim.workspace_state
227 .recorded_actions
228 .push(ReplayableAction::Insertion {
229 text: text.clone(),
230 utf16_range_to_replace: range_to_replace,
231 });
232 if vim.workspace_state.stop_recording_after_next_action {
233 vim.workspace_state.recording = false;
234 vim.workspace_state.stop_recording_after_next_action = false;
235 }
236 }
237 });
238 }
239
240 fn update_active_editor<S>(
241 &self,
242 cx: &mut WindowContext,
243 update: impl FnOnce(&mut Editor, &mut ViewContext<Editor>) -> S,
244 ) -> Option<S> {
245 let editor = self.active_editor.clone()?.upgrade()?;
246 Some(editor.update(cx, update))
247 }
248
249 pub fn start_recording(&mut self, cx: &mut WindowContext) {
250 if !self.workspace_state.replaying {
251 self.workspace_state.recording = true;
252 self.workspace_state.recorded_actions = Default::default();
253 self.workspace_state.recorded_count = None;
254
255 let selections = self
256 .active_editor
257 .as_ref()
258 .and_then(|editor| editor.upgrade())
259 .map(|editor| {
260 let editor = editor.read(cx);
261 (
262 editor.selections.oldest::<Point>(cx),
263 editor.selections.newest::<Point>(cx),
264 )
265 });
266
267 if let Some((oldest, newest)) = selections {
268 self.workspace_state.recorded_selection = match self.state().mode {
269 Mode::Visual if newest.end.row == newest.start.row => {
270 RecordedSelection::SingleLine {
271 cols: newest.end.column - newest.start.column,
272 }
273 }
274 Mode::Visual => RecordedSelection::Visual {
275 rows: newest.end.row - newest.start.row,
276 cols: newest.end.column,
277 },
278 Mode::VisualLine => RecordedSelection::VisualLine {
279 rows: newest.end.row - newest.start.row,
280 },
281 Mode::VisualBlock => RecordedSelection::VisualBlock {
282 rows: newest.end.row.abs_diff(oldest.start.row),
283 cols: newest.end.column.abs_diff(oldest.start.column),
284 },
285 _ => RecordedSelection::None,
286 }
287 } else {
288 self.workspace_state.recorded_selection = RecordedSelection::None;
289 }
290 }
291 }
292
293 pub fn stop_recording(&mut self) {
294 if self.workspace_state.recording {
295 self.workspace_state.stop_recording_after_next_action = true;
296 }
297 }
298
299 pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>) {
300 if self.workspace_state.recording {
301 self.workspace_state
302 .recorded_actions
303 .push(ReplayableAction::Action(action.boxed_clone()));
304 self.workspace_state.recording = false;
305 self.workspace_state.stop_recording_after_next_action = false;
306 }
307 }
308
309 pub fn record_current_action(&mut self, cx: &mut WindowContext) {
310 self.start_recording(cx);
311 self.stop_recording();
312 }
313
314 fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut WindowContext) {
315 let state = self.state();
316 let last_mode = state.mode;
317 let prior_mode = state.last_mode;
318 self.update_state(|state| {
319 state.last_mode = last_mode;
320 state.mode = mode;
321 state.operator_stack.clear();
322 });
323 if mode != Mode::Insert {
324 self.take_count(cx);
325 }
326
327 // Sync editor settings like clip mode
328 self.sync_vim_settings(cx);
329
330 if leave_selections {
331 return;
332 }
333
334 // Adjust selections
335 self.update_active_editor(cx, |editor, cx| {
336 if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
337 {
338 visual_block_motion(true, editor, cx, |_, point, goal| Some((point, goal)))
339 }
340
341 editor.change_selections(None, cx, |s| {
342 // we cheat with visual block mode and use multiple cursors.
343 // the cost of this cheat is we need to convert back to a single
344 // cursor whenever vim would.
345 if last_mode == Mode::VisualBlock
346 && (mode != Mode::VisualBlock && mode != Mode::Insert)
347 {
348 let tail = s.oldest_anchor().tail();
349 let head = s.newest_anchor().head();
350 s.select_anchor_ranges(vec![tail..head]);
351 } else if last_mode == Mode::Insert
352 && prior_mode == Mode::VisualBlock
353 && mode != Mode::VisualBlock
354 {
355 let pos = s.first_anchor().head();
356 s.select_anchor_ranges(vec![pos..pos])
357 }
358
359 s.move_with(|map, selection| {
360 if last_mode.is_visual() && !mode.is_visual() {
361 let mut point = selection.head();
362 if !selection.reversed && !selection.is_empty() {
363 point = movement::left(map, selection.head());
364 }
365 selection.collapse_to(point, selection.goal)
366 } else if !last_mode.is_visual() && mode.is_visual() {
367 if selection.is_empty() {
368 selection.end = movement::right(map, selection.start);
369 }
370 }
371 });
372 })
373 });
374 }
375
376 fn push_count_digit(&mut self, number: usize, cx: &mut WindowContext) {
377 if self.active_operator().is_some() {
378 self.update_state(|state| {
379 state.post_count = Some(state.post_count.unwrap_or(0) * 10 + number)
380 })
381 } else {
382 self.update_state(|state| {
383 state.pre_count = Some(state.pre_count.unwrap_or(0) * 10 + number)
384 })
385 }
386 // update the keymap so that 0 works
387 self.sync_vim_settings(cx)
388 }
389
390 fn take_count(&mut self, cx: &mut WindowContext) -> Option<usize> {
391 if self.workspace_state.replaying {
392 return self.workspace_state.recorded_count;
393 }
394
395 let count = if self.state().post_count == None && self.state().pre_count == None {
396 return None;
397 } else {
398 Some(self.update_state(|state| {
399 state.post_count.take().unwrap_or(1) * state.pre_count.take().unwrap_or(1)
400 }))
401 };
402 if self.workspace_state.recording {
403 self.workspace_state.recorded_count = count;
404 }
405 self.sync_vim_settings(cx);
406 count
407 }
408
409 fn push_operator(&mut self, operator: Operator, cx: &mut WindowContext) {
410 if matches!(
411 operator,
412 Operator::Change | Operator::Delete | Operator::Replace
413 ) {
414 self.start_recording(cx)
415 };
416 self.update_state(|state| state.operator_stack.push(operator));
417 self.sync_vim_settings(cx);
418 }
419
420 fn maybe_pop_operator(&mut self) -> Option<Operator> {
421 self.update_state(|state| state.operator_stack.pop())
422 }
423
424 fn pop_operator(&mut self, cx: &mut WindowContext) -> Operator {
425 let popped_operator = self.update_state( |state| state.operator_stack.pop()
426 ) .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
427 self.sync_vim_settings(cx);
428 popped_operator
429 }
430 fn clear_operator(&mut self, cx: &mut WindowContext) {
431 self.take_count(cx);
432 self.update_state(|state| state.operator_stack.clear());
433 self.sync_vim_settings(cx);
434 }
435
436 fn active_operator(&self) -> Option<Operator> {
437 self.state().operator_stack.last().copied()
438 }
439
440 fn active_editor_input_ignored(text: Arc<str>, cx: &mut WindowContext) {
441 if text.is_empty() {
442 return;
443 }
444
445 match Vim::read(cx).active_operator() {
446 Some(Operator::FindForward { before }) => {
447 let find = Motion::FindForward {
448 before,
449 char: text.chars().next().unwrap(),
450 };
451 Vim::update(cx, |vim, _| {
452 vim.workspace_state.last_find = Some(find.clone())
453 });
454 motion::motion(find, cx)
455 }
456 Some(Operator::FindBackward { after }) => {
457 let find = Motion::FindBackward {
458 after,
459 char: text.chars().next().unwrap(),
460 };
461 Vim::update(cx, |vim, _| {
462 vim.workspace_state.last_find = Some(find.clone())
463 });
464 motion::motion(find, cx)
465 }
466 Some(Operator::Replace) => match Vim::read(cx).state().mode {
467 Mode::Normal => normal_replace(text, cx),
468 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => visual_replace(text, cx),
469 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
470 },
471 _ => {}
472 }
473 }
474
475 fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
476 if self.enabled != enabled {
477 self.enabled = enabled;
478
479 cx.update_global::<CommandPaletteFilter, _>(|filter, _| {
480 if self.enabled {
481 filter.hidden_namespaces.remove("vim");
482 } else {
483 filter.hidden_namespaces.insert("vim");
484 }
485 });
486
487 if self.enabled {
488 cx.set_global::<CommandPaletteInterceptor>(Box::new(command::command_interceptor));
489 } else if cx.has_global::<CommandPaletteInterceptor>() {
490 let _ = cx.remove_global::<CommandPaletteInterceptor>();
491 }
492
493 if let Some(active_window) = cx.active_window() {
494 active_window
495 .update(cx, |root_view, cx| {
496 if self.enabled {
497 let active_editor = root_view
498 .downcast::<Workspace>()
499 .ok()
500 .and_then(|workspace| workspace.read(cx).active_item(cx))
501 .and_then(|item| item.downcast::<Editor>());
502 if let Some(active_editor) = active_editor {
503 self.set_active_editor(active_editor, cx);
504 }
505 self.switch_mode(Mode::Normal, false, cx);
506 }
507 self.sync_vim_settings(cx);
508 })
509 .ok();
510 }
511 }
512 }
513
514 pub fn state(&self) -> &EditorState {
515 if let Some(active_editor) = self.active_editor.as_ref() {
516 if let Some(state) = self.editor_states.get(&active_editor.entity_id()) {
517 return state;
518 }
519 }
520
521 &self.default_state
522 }
523
524 pub fn update_state<T>(&mut self, func: impl FnOnce(&mut EditorState) -> T) -> T {
525 let mut state = self.state().clone();
526 let ret = func(&mut state);
527
528 if let Some(active_editor) = self.active_editor.as_ref() {
529 self.editor_states.insert(active_editor.entity_id(), state);
530 }
531
532 ret
533 }
534
535 fn sync_vim_settings(&self, cx: &mut WindowContext) {
536 let state = self.state();
537 let cursor_shape = state.cursor_shape();
538
539 self.update_active_editor(cx, |editor, cx| {
540 if self.enabled && editor.mode() == EditorMode::Full {
541 editor.set_cursor_shape(cursor_shape, cx);
542 editor.set_clip_at_line_ends(state.clip_at_line_ends(), cx);
543 editor.set_collapse_matches(true);
544 editor.set_input_enabled(!state.vim_controlled());
545 editor.set_autoindent(state.should_autoindent());
546 editor.selections.line_mode = matches!(state.mode, Mode::VisualLine);
547 let context_layer = state.keymap_context_layer();
548 editor.set_keymap_context_layer::<Self>(context_layer, cx);
549 } else {
550 // Note: set_collapse_matches is not in unhook_vim_settings, as that method is called on blur,
551 // but we need collapse_matches to persist when the search bar is focused.
552 editor.set_collapse_matches(false);
553 self.unhook_vim_settings(editor, cx);
554 }
555 });
556 }
557
558 fn unhook_vim_settings(&self, editor: &mut Editor, cx: &mut ViewContext<Editor>) {
559 editor.set_cursor_shape(CursorShape::Bar, cx);
560 editor.set_clip_at_line_ends(false, cx);
561 editor.set_input_enabled(true);
562 editor.set_autoindent(true);
563 editor.selections.line_mode = false;
564
565 // we set the VimEnabled context on all editors so that we
566 // can distinguish between vim mode and non-vim mode in the BufferSearchBar.
567 // This is a bit of a hack, but currently the search crate does not depend on vim,
568 // and it seems nice to keep it that way.
569 if self.enabled {
570 let mut context = KeyContext::default();
571 context.add("VimEnabled");
572 editor.set_keymap_context_layer::<Self>(context, cx)
573 } else {
574 editor.remove_keymap_context_layer::<Self>(cx);
575 }
576 }
577}
578
579impl Settings for VimModeSetting {
580 const KEY: Option<&'static str> = Some("vim_mode");
581
582 type FileContent = Option<bool>;
583
584 fn load(
585 default_value: &Self::FileContent,
586 user_values: &[&Self::FileContent],
587 _: &mut AppContext,
588 ) -> Result<Self> {
589 Ok(Self(user_values.iter().rev().find_map(|v| **v).unwrap_or(
590 default_value.ok_or_else(Self::missing_default)?,
591 )))
592 }
593}
594
595fn local_selections_changed(newest: Selection<usize>, cx: &mut WindowContext) {
596 Vim::update(cx, |vim, cx| {
597 if vim.enabled && vim.state().mode == Mode::Normal && !newest.is_empty() {
598 if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
599 vim.switch_mode(Mode::VisualBlock, false, cx);
600 } else {
601 vim.switch_mode(Mode::Visual, false, cx)
602 }
603 }
604 })
605}