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_peer_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 // if leader_replica_id is set, then you're following someone else's cursor
199 // don't switch vim mode.
200 && editor.leader_replica_id().is_none()
201 {
202 self.switch_mode(Mode::Visual, true, cx);
203 }
204 }
205
206 self.sync_vim_settings(cx);
207 }
208
209 fn record_insertion(
210 text: &Arc<str>,
211 range_to_replace: Option<Range<isize>>,
212 cx: &mut WindowContext,
213 ) {
214 Vim::update(cx, |vim, _| {
215 if vim.workspace_state.recording {
216 vim.workspace_state
217 .recorded_actions
218 .push(ReplayableAction::Insertion {
219 text: text.clone(),
220 utf16_range_to_replace: range_to_replace,
221 });
222 if vim.workspace_state.stop_recording_after_next_action {
223 vim.workspace_state.recording = false;
224 vim.workspace_state.stop_recording_after_next_action = false;
225 }
226 }
227 });
228 }
229
230 fn update_active_editor<S>(
231 &self,
232 cx: &mut WindowContext,
233 update: impl FnOnce(&mut Editor, &mut ViewContext<Editor>) -> S,
234 ) -> Option<S> {
235 let editor = self.active_editor.clone()?.upgrade(cx)?;
236 Some(editor.update(cx, update))
237 }
238
239 pub fn start_recording(&mut self, cx: &mut WindowContext) {
240 if !self.workspace_state.replaying {
241 self.workspace_state.recording = true;
242 self.workspace_state.recorded_actions = Default::default();
243 self.workspace_state.recorded_count = None;
244
245 let selections = self
246 .active_editor
247 .and_then(|editor| editor.upgrade(cx))
248 .map(|editor| {
249 let editor = editor.read(cx);
250 (
251 editor.selections.oldest::<Point>(cx),
252 editor.selections.newest::<Point>(cx),
253 )
254 });
255
256 if let Some((oldest, newest)) = selections {
257 self.workspace_state.recorded_selection = match self.state().mode {
258 Mode::Visual if newest.end.row == newest.start.row => {
259 RecordedSelection::SingleLine {
260 cols: newest.end.column - newest.start.column,
261 }
262 }
263 Mode::Visual => RecordedSelection::Visual {
264 rows: newest.end.row - newest.start.row,
265 cols: newest.end.column,
266 },
267 Mode::VisualLine => RecordedSelection::VisualLine {
268 rows: newest.end.row - newest.start.row,
269 },
270 Mode::VisualBlock => RecordedSelection::VisualBlock {
271 rows: newest.end.row.abs_diff(oldest.start.row),
272 cols: newest.end.column.abs_diff(oldest.start.column),
273 },
274 _ => RecordedSelection::None,
275 }
276 } else {
277 self.workspace_state.recorded_selection = RecordedSelection::None;
278 }
279 }
280 }
281
282 pub fn stop_recording(&mut self) {
283 if self.workspace_state.recording {
284 self.workspace_state.stop_recording_after_next_action = true;
285 }
286 }
287
288 pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>) {
289 if self.workspace_state.recording {
290 self.workspace_state
291 .recorded_actions
292 .push(ReplayableAction::Action(action.boxed_clone()));
293 self.workspace_state.recording = false;
294 self.workspace_state.stop_recording_after_next_action = false;
295 }
296 }
297
298 pub fn record_current_action(&mut self, cx: &mut WindowContext) {
299 self.start_recording(cx);
300 self.stop_recording();
301 }
302
303 fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut WindowContext) {
304 let state = self.state();
305 let last_mode = state.mode;
306 let prior_mode = state.last_mode;
307 self.update_state(|state| {
308 state.last_mode = last_mode;
309 state.mode = mode;
310 state.operator_stack.clear();
311 });
312 if mode != Mode::Insert {
313 self.take_count(cx);
314 }
315
316 cx.emit_global(VimEvent::ModeChanged { mode });
317
318 // Sync editor settings like clip mode
319 self.sync_vim_settings(cx);
320
321 if leave_selections {
322 return;
323 }
324
325 // Adjust selections
326 self.update_active_editor(cx, |editor, cx| {
327 if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
328 {
329 visual_block_motion(true, editor, cx, |_, point, goal| Some((point, goal)))
330 }
331
332 editor.change_selections(None, cx, |s| {
333 // we cheat with visual block mode and use multiple cursors.
334 // the cost of this cheat is we need to convert back to a single
335 // cursor whenever vim would.
336 if last_mode == Mode::VisualBlock
337 && (mode != Mode::VisualBlock && mode != Mode::Insert)
338 {
339 let tail = s.oldest_anchor().tail();
340 let head = s.newest_anchor().head();
341 s.select_anchor_ranges(vec![tail..head]);
342 } else if last_mode == Mode::Insert
343 && prior_mode == Mode::VisualBlock
344 && mode != Mode::VisualBlock
345 {
346 let pos = s.first_anchor().head();
347 s.select_anchor_ranges(vec![pos..pos])
348 }
349
350 s.move_with(|map, selection| {
351 if last_mode.is_visual() && !mode.is_visual() {
352 let mut point = selection.head();
353 if !selection.reversed && !selection.is_empty() {
354 point = movement::left(map, selection.head());
355 }
356 selection.collapse_to(point, selection.goal)
357 } else if !last_mode.is_visual() && mode.is_visual() {
358 if selection.is_empty() {
359 selection.end = movement::right(map, selection.start);
360 }
361 }
362 });
363 })
364 });
365 }
366
367 fn push_count_digit(&mut self, number: usize, cx: &mut WindowContext) {
368 if self.active_operator().is_some() {
369 self.update_state(|state| {
370 state.post_count = Some(state.post_count.unwrap_or(0) * 10 + number)
371 })
372 } else {
373 self.update_state(|state| {
374 state.pre_count = Some(state.pre_count.unwrap_or(0) * 10 + number)
375 })
376 }
377 // update the keymap so that 0 works
378 self.sync_vim_settings(cx)
379 }
380
381 fn take_count(&mut self, cx: &mut WindowContext) -> Option<usize> {
382 if self.workspace_state.replaying {
383 return self.workspace_state.recorded_count;
384 }
385
386 let count = if self.state().post_count == None && self.state().pre_count == None {
387 return None;
388 } else {
389 Some(self.update_state(|state| {
390 state.post_count.take().unwrap_or(1) * state.pre_count.take().unwrap_or(1)
391 }))
392 };
393 if self.workspace_state.recording {
394 self.workspace_state.recorded_count = count;
395 }
396 self.sync_vim_settings(cx);
397 count
398 }
399
400 fn push_operator(&mut self, operator: Operator, cx: &mut WindowContext) {
401 if matches!(
402 operator,
403 Operator::Change | Operator::Delete | Operator::Replace
404 ) {
405 self.start_recording(cx)
406 };
407 self.update_state(|state| state.operator_stack.push(operator));
408 self.sync_vim_settings(cx);
409 }
410
411 fn maybe_pop_operator(&mut self) -> Option<Operator> {
412 self.update_state(|state| state.operator_stack.pop())
413 }
414
415 fn pop_operator(&mut self, cx: &mut WindowContext) -> Operator {
416 let popped_operator = self.update_state( |state| state.operator_stack.pop()
417 ) .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
418 self.sync_vim_settings(cx);
419 popped_operator
420 }
421 fn clear_operator(&mut self, cx: &mut WindowContext) {
422 self.take_count(cx);
423 self.update_state(|state| state.operator_stack.clear());
424 self.sync_vim_settings(cx);
425 }
426
427 fn active_operator(&self) -> Option<Operator> {
428 self.state().operator_stack.last().copied()
429 }
430
431 fn active_editor_input_ignored(text: Arc<str>, cx: &mut WindowContext) {
432 if text.is_empty() {
433 return;
434 }
435
436 match Vim::read(cx).active_operator() {
437 Some(Operator::FindForward { before }) => {
438 let find = Motion::FindForward {
439 before,
440 char: text.chars().next().unwrap(),
441 };
442 Vim::update(cx, |vim, _| {
443 vim.workspace_state.last_find = Some(find.clone())
444 });
445 motion::motion(find, cx)
446 }
447 Some(Operator::FindBackward { after }) => {
448 let find = Motion::FindBackward {
449 after,
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::Replace) => match Vim::read(cx).state().mode {
458 Mode::Normal => normal_replace(text, cx),
459 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => visual_replace(text, cx),
460 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
461 },
462 _ => {}
463 }
464 }
465
466 fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
467 if self.enabled != enabled {
468 self.enabled = enabled;
469
470 cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
471 if self.enabled {
472 filter.filtered_namespaces.remove("vim");
473 } else {
474 filter.filtered_namespaces.insert("vim");
475 }
476 });
477
478 if self.enabled {
479 cx.set_global::<CommandPaletteInterceptor>(Box::new(command::command_interceptor));
480 } else if cx.has_global::<CommandPaletteInterceptor>() {
481 let _ = cx.remove_global::<CommandPaletteInterceptor>();
482 }
483
484 cx.update_active_window(|cx| {
485 if self.enabled {
486 let active_editor = cx
487 .root_view()
488 .downcast_ref::<Workspace>()
489 .and_then(|workspace| workspace.read(cx).active_item(cx))
490 .and_then(|item| item.downcast::<Editor>());
491 if let Some(active_editor) = active_editor {
492 self.set_active_editor(active_editor, cx);
493 }
494 self.switch_mode(Mode::Normal, false, cx);
495 }
496 self.sync_vim_settings(cx);
497 });
498 }
499 }
500
501 pub fn state(&self) -> &EditorState {
502 if let Some(active_editor) = self.active_editor.as_ref() {
503 if let Some(state) = self.editor_states.get(&active_editor.id()) {
504 return state;
505 }
506 }
507
508 &self.default_state
509 }
510
511 pub fn update_state<T>(&mut self, func: impl FnOnce(&mut EditorState) -> T) -> T {
512 let mut state = self.state().clone();
513 let ret = func(&mut state);
514
515 if let Some(active_editor) = self.active_editor.as_ref() {
516 self.editor_states.insert(active_editor.id(), state);
517 }
518
519 ret
520 }
521
522 fn sync_vim_settings(&self, cx: &mut WindowContext) {
523 let state = self.state();
524 let cursor_shape = state.cursor_shape();
525
526 self.update_active_editor(cx, |editor, cx| {
527 if self.enabled && editor.mode() == EditorMode::Full {
528 editor.set_cursor_shape(cursor_shape, cx);
529 editor.set_clip_at_line_ends(state.clip_at_line_ends(), cx);
530 editor.set_collapse_matches(true);
531 editor.set_input_enabled(!state.vim_controlled());
532 editor.set_autoindent(state.should_autoindent());
533 editor.selections.line_mode = matches!(state.mode, Mode::VisualLine);
534 let context_layer = state.keymap_context_layer();
535 editor.set_keymap_context_layer::<Self>(context_layer, cx);
536 } else {
537 // Note: set_collapse_matches is not in unhook_vim_settings, as that method is called on blur,
538 // but we need collapse_matches to persist when the search bar is focused.
539 editor.set_collapse_matches(false);
540 self.unhook_vim_settings(editor, cx);
541 }
542 });
543 }
544
545 fn unhook_vim_settings(&self, editor: &mut Editor, cx: &mut ViewContext<Editor>) {
546 editor.set_cursor_shape(CursorShape::Bar, cx);
547 editor.set_clip_at_line_ends(false, cx);
548 editor.set_input_enabled(true);
549 editor.set_autoindent(true);
550 editor.selections.line_mode = false;
551
552 // we set the VimEnabled context on all editors so that we
553 // can distinguish between vim mode and non-vim mode in the BufferSearchBar.
554 // This is a bit of a hack, but currently the search crate does not depend on vim,
555 // and it seems nice to keep it that way.
556 if self.enabled {
557 let mut context = KeymapContext::default();
558 context.add_identifier("VimEnabled");
559 editor.set_keymap_context_layer::<Self>(context, cx)
560 } else {
561 editor.remove_keymap_context_layer::<Self>(cx);
562 }
563 }
564}
565
566impl Setting for VimModeSetting {
567 const KEY: Option<&'static str> = Some("vim_mode");
568
569 type FileContent = Option<bool>;
570
571 fn load(
572 default_value: &Self::FileContent,
573 user_values: &[&Self::FileContent],
574 _: &AppContext,
575 ) -> Result<Self> {
576 Ok(Self(user_values.iter().rev().find_map(|v| **v).unwrap_or(
577 default_value.ok_or_else(Self::missing_default)?,
578 )))
579 }
580}
581
582fn local_selections_changed(newest: Selection<usize>, cx: &mut WindowContext) {
583 Vim::update(cx, |vim, cx| {
584 if vim.enabled && vim.state().mode == Mode::Normal && !newest.is_empty() {
585 if matches!(newest.goal, SelectionGoal::ColumnRange { .. }) {
586 vim.switch_mode(Mode::VisualBlock, false, cx);
587 } else {
588 vim.switch_mode(Mode::Visual, false, cx)
589 }
590 }
591 })
592}