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