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