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