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