1#[cfg(test)]
2mod vim_test_context;
3
4mod editor_events;
5mod insert;
6mod motion;
7mod normal;
8mod state;
9mod utils;
10mod visual;
11
12use collections::HashMap;
13use command_palette::CommandPaletteFilter;
14use editor::{Bias, CursorShape, Editor, Input};
15use gpui::{impl_actions, MutableAppContext, Subscription, ViewContext, WeakViewHandle};
16use serde::Deserialize;
17
18use settings::Settings;
19use state::{Mode, Operator, VimState};
20use workspace::{self, Workspace};
21
22#[derive(Clone, Deserialize, PartialEq)]
23pub struct SwitchMode(pub Mode);
24
25#[derive(Clone, Deserialize, PartialEq)]
26pub struct PushOperator(pub Operator);
27
28impl_actions!(vim, [SwitchMode, PushOperator]);
29
30pub fn init(cx: &mut MutableAppContext) {
31 editor_events::init(cx);
32 normal::init(cx);
33 visual::init(cx);
34 insert::init(cx);
35 motion::init(cx);
36
37 cx.add_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {
38 Vim::update(cx, |vim, cx| vim.switch_mode(mode, cx))
39 });
40 cx.add_action(
41 |_: &mut Workspace, &PushOperator(operator): &PushOperator, cx| {
42 Vim::update(cx, |vim, cx| vim.push_operator(operator, cx))
43 },
44 );
45 cx.add_action(|_: &mut Editor, _: &Input, cx| {
46 if Vim::read(cx).active_operator().is_some() {
47 // Defer without updating editor
48 MutableAppContext::defer(cx, |cx| Vim::update(cx, |vim, cx| vim.clear_operator(cx)))
49 } else {
50 cx.propagate_action()
51 }
52 });
53
54 // Sync initial settings with the rest of the app
55 Vim::update(cx, |state, cx| state.sync_vim_settings(cx));
56
57 // Any time settings change, update vim mode to match
58 cx.observe_global::<Settings, _>(|cx| {
59 Vim::update(cx, |state, cx| {
60 state.set_enabled(cx.global::<Settings>().vim_mode, cx)
61 })
62 })
63 .detach();
64}
65
66#[derive(Default)]
67pub struct Vim {
68 editors: HashMap<usize, WeakViewHandle<Editor>>,
69 active_editor: Option<WeakViewHandle<Editor>>,
70 selection_subscription: Option<Subscription>,
71
72 enabled: bool,
73 state: VimState,
74}
75
76impl Vim {
77 fn read(cx: &mut MutableAppContext) -> &Self {
78 cx.default_global()
79 }
80
81 fn update<F, S>(cx: &mut MutableAppContext, update: F) -> S
82 where
83 F: FnOnce(&mut Self, &mut MutableAppContext) -> S,
84 {
85 cx.update_default_global(update)
86 }
87
88 fn update_active_editor<S>(
89 &self,
90 cx: &mut MutableAppContext,
91 update: impl FnOnce(&mut Editor, &mut ViewContext<Editor>) -> S,
92 ) -> Option<S> {
93 self.active_editor
94 .clone()
95 .and_then(|ae| ae.upgrade(cx))
96 .map(|ae| ae.update(cx, update))
97 }
98
99 fn switch_mode(&mut self, mode: Mode, cx: &mut MutableAppContext) {
100 self.state.mode = mode;
101 self.state.operator_stack.clear();
102 self.sync_vim_settings(cx);
103 }
104
105 fn push_operator(&mut self, operator: Operator, cx: &mut MutableAppContext) {
106 self.state.operator_stack.push(operator);
107 self.sync_vim_settings(cx);
108 }
109
110 fn pop_operator(&mut self, cx: &mut MutableAppContext) -> Operator {
111 let popped_operator = self.state.operator_stack.pop().expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
112 self.sync_vim_settings(cx);
113 popped_operator
114 }
115
116 fn clear_operator(&mut self, cx: &mut MutableAppContext) {
117 self.state.operator_stack.clear();
118 self.sync_vim_settings(cx);
119 }
120
121 fn active_operator(&self) -> Option<Operator> {
122 self.state.operator_stack.last().copied()
123 }
124
125 fn set_enabled(&mut self, enabled: bool, cx: &mut MutableAppContext) {
126 if self.enabled != enabled {
127 self.enabled = enabled;
128 self.state = Default::default();
129 if enabled {
130 self.state.mode = Mode::Normal;
131 }
132 self.sync_vim_settings(cx);
133 }
134 }
135
136 fn sync_vim_settings(&self, cx: &mut MutableAppContext) {
137 let state = &self.state;
138 let cursor_shape = state.cursor_shape();
139
140 cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
141 if self.enabled {
142 filter.filtered_namespaces.remove("vim");
143 } else {
144 filter.filtered_namespaces.insert("vim");
145 }
146 });
147
148 for editor in self.editors.values() {
149 if let Some(editor) = editor.upgrade(cx) {
150 editor.update(cx, |editor, cx| {
151 if self.enabled {
152 editor.set_cursor_shape(cursor_shape, cx);
153 editor.set_clip_at_line_ends(state.clip_at_line_end(), cx);
154 editor.set_input_enabled(!state.vim_controlled());
155 editor.selections.line_mode =
156 matches!(state.mode, Mode::Visual { line: true });
157 let context_layer = state.keymap_context_layer();
158 editor.set_keymap_context_layer::<Self>(context_layer);
159 editor.change_selections(None, cx, |s| {
160 s.move_with(|map, selection| {
161 selection.set_head(
162 map.clip_point(selection.head(), Bias::Left),
163 selection.goal,
164 );
165 if state.empty_selections_only() {
166 selection.collapse_to(selection.head(), selection.goal)
167 }
168 });
169 })
170 } else {
171 editor.set_cursor_shape(CursorShape::Bar, cx);
172 editor.set_clip_at_line_ends(false, cx);
173 editor.set_input_enabled(true);
174 editor.selections.line_mode = false;
175 editor.remove_keymap_context_layer::<Self>();
176 }
177 });
178 }
179 }
180 }
181}
182
183#[cfg(test)]
184mod test {
185 use crate::{state::Mode, vim_test_context::VimTestContext};
186
187 #[gpui::test]
188 async fn test_initially_disabled(cx: &mut gpui::TestAppContext) {
189 let mut cx = VimTestContext::new(cx, false).await;
190 cx.simulate_keystrokes(["h", "j", "k", "l"]);
191 cx.assert_editor_state("hjkl|");
192 }
193
194 #[gpui::test]
195 async fn test_toggle_through_settings(cx: &mut gpui::TestAppContext) {
196 let mut cx = VimTestContext::new(cx, true).await;
197
198 cx.simulate_keystroke("i");
199 assert_eq!(cx.mode(), Mode::Insert);
200
201 // Editor acts as though vim is disabled
202 cx.disable_vim();
203 cx.simulate_keystrokes(["h", "j", "k", "l"]);
204 cx.assert_editor_state("hjkl|");
205
206 // Selections aren't changed if editor is blurred but vim-mode is still disabled.
207 cx.set_state("[hjkl}", Mode::Normal);
208 cx.assert_editor_state("[hjkl}");
209 cx.update_editor(|_, cx| cx.blur());
210 cx.assert_editor_state("[hjkl}");
211 cx.update_editor(|_, cx| cx.focus_self());
212 cx.assert_editor_state("[hjkl}");
213
214 // Enabling dynamically sets vim mode again and restores normal mode
215 cx.enable_vim();
216 assert_eq!(cx.mode(), Mode::Normal);
217 cx.simulate_keystrokes(["h", "h", "h", "l"]);
218 assert_eq!(cx.buffer_text(), "hjkl".to_owned());
219 cx.assert_editor_state("h|jkl");
220 cx.simulate_keystrokes(["i", "T", "e", "s", "t"]);
221 cx.assert_editor_state("hTest|jkl");
222
223 // Disabling and enabling resets to normal mode
224 assert_eq!(cx.mode(), Mode::Insert);
225 cx.disable_vim();
226 cx.enable_vim();
227 assert_eq!(cx.mode(), Mode::Normal);
228 }
229}