1#[cfg(test)]
2mod test_contexts;
3
4mod editor_events;
5mod insert;
6mod motion;
7mod normal;
8mod object;
9mod state;
10mod utils;
11mod visual;
12
13use collections::HashMap;
14use command_palette::CommandPaletteFilter;
15use editor::{Bias, Cancel, CursorShape, Editor};
16use gpui::{impl_actions, MutableAppContext, Subscription, ViewContext, WeakViewHandle};
17use serde::Deserialize;
18
19use settings::Settings;
20use state::{Mode, Operator, VimState};
21use workspace::{self, Workspace};
22
23#[derive(Clone, Deserialize, PartialEq)]
24pub struct SwitchMode(pub Mode);
25
26#[derive(Clone, Deserialize, PartialEq)]
27pub struct PushOperator(pub Operator);
28
29#[derive(Clone, Deserialize, PartialEq)]
30struct Number(u8);
31
32impl_actions!(vim, [Number, SwitchMode, PushOperator]);
33
34pub fn init(cx: &mut MutableAppContext) {
35 editor_events::init(cx);
36 normal::init(cx);
37 visual::init(cx);
38 insert::init(cx);
39 object::init(cx);
40 motion::init(cx);
41
42 // Vim Actions
43 cx.add_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {
44 Vim::update(cx, |vim, cx| vim.switch_mode(mode, false, cx))
45 });
46 cx.add_action(
47 |_: &mut Workspace, &PushOperator(operator): &PushOperator, cx| {
48 Vim::update(cx, |vim, cx| vim.push_operator(operator, cx))
49 },
50 );
51 cx.add_action(|_: &mut Workspace, n: &Number, cx: _| {
52 Vim::update(cx, |vim, cx| vim.push_number(n, cx));
53 });
54
55 // Editor Actions
56 cx.add_action(|_: &mut Editor, _: &Cancel, cx| {
57 // If we are in a non normal mode or have an active operator, swap to normal mode
58 // Otherwise forward cancel on to the editor
59 let vim = Vim::read(cx);
60 if vim.state.mode != Mode::Normal || vim.active_operator().is_some() {
61 MutableAppContext::defer(cx, |cx| {
62 Vim::update(cx, |state, cx| {
63 state.switch_mode(Mode::Normal, false, cx);
64 });
65 });
66 } else {
67 cx.propagate_action();
68 }
69 });
70
71 // Sync initial settings with the rest of the app
72 Vim::update(cx, |state, cx| state.sync_vim_settings(cx));
73
74 // Any time settings change, update vim mode to match
75 cx.observe_global::<Settings, _>(|cx| {
76 Vim::update(cx, |state, cx| {
77 state.set_enabled(cx.global::<Settings>().vim_mode, cx)
78 })
79 })
80 .detach();
81}
82
83#[derive(Default)]
84pub struct Vim {
85 editors: HashMap<usize, WeakViewHandle<Editor>>,
86 active_editor: Option<WeakViewHandle<Editor>>,
87 selection_subscription: Option<Subscription>,
88
89 enabled: bool,
90 state: VimState,
91}
92
93impl Vim {
94 fn read(cx: &mut MutableAppContext) -> &Self {
95 cx.default_global()
96 }
97
98 fn update<F, S>(cx: &mut MutableAppContext, update: F) -> S
99 where
100 F: FnOnce(&mut Self, &mut MutableAppContext) -> S,
101 {
102 cx.update_default_global(update)
103 }
104
105 fn update_active_editor<S>(
106 &self,
107 cx: &mut MutableAppContext,
108 update: impl FnOnce(&mut Editor, &mut ViewContext<Editor>) -> S,
109 ) -> Option<S> {
110 self.active_editor
111 .clone()
112 .and_then(|ae| ae.upgrade(cx))
113 .map(|ae| ae.update(cx, update))
114 }
115
116 fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut MutableAppContext) {
117 self.state.mode = mode;
118 self.state.operator_stack.clear();
119
120 // Sync editor settings like clip mode
121 self.sync_vim_settings(cx);
122
123 if leave_selections {
124 return;
125 }
126
127 // Adjust selections
128 for editor in self.editors.values() {
129 if let Some(editor) = editor.upgrade(cx) {
130 editor.update(cx, |editor, cx| {
131 editor.change_selections(None, cx, |s| {
132 s.move_with(|map, selection| {
133 if self.state.empty_selections_only() {
134 let new_head = map.clip_point(selection.head(), Bias::Left);
135 selection.collapse_to(new_head, selection.goal)
136 } else {
137 selection.set_head(
138 map.clip_point(selection.head(), Bias::Left),
139 selection.goal,
140 );
141 }
142 });
143 })
144 })
145 }
146 }
147 }
148
149 fn push_operator(&mut self, operator: Operator, cx: &mut MutableAppContext) {
150 self.state.operator_stack.push(operator);
151 self.sync_vim_settings(cx);
152 }
153
154 fn push_number(&mut self, Number(number): &Number, cx: &mut MutableAppContext) {
155 if let Some(Operator::Number(current_number)) = self.active_operator() {
156 self.pop_operator(cx);
157 self.push_operator(Operator::Number(current_number * 10 + *number as usize), cx);
158 } else {
159 self.push_operator(Operator::Number(*number as usize), cx);
160 }
161 }
162
163 fn pop_operator(&mut self, cx: &mut MutableAppContext) -> Operator {
164 let popped_operator = self.state.operator_stack.pop()
165 .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
166 self.sync_vim_settings(cx);
167 popped_operator
168 }
169
170 fn pop_number_operator(&mut self, cx: &mut MutableAppContext) -> usize {
171 let mut times = 1;
172 if let Some(Operator::Number(number)) = self.active_operator() {
173 times = number;
174 self.pop_operator(cx);
175 }
176 times
177 }
178
179 fn clear_operator(&mut self, cx: &mut MutableAppContext) {
180 self.state.operator_stack.clear();
181 self.sync_vim_settings(cx);
182 }
183
184 fn active_operator(&self) -> Option<Operator> {
185 self.state.operator_stack.last().copied()
186 }
187
188 fn set_enabled(&mut self, enabled: bool, cx: &mut MutableAppContext) {
189 if self.enabled != enabled {
190 self.enabled = enabled;
191 self.state = Default::default();
192 if enabled {
193 self.switch_mode(Mode::Normal, false, cx);
194 }
195 self.sync_vim_settings(cx);
196 }
197 }
198
199 fn sync_vim_settings(&self, cx: &mut MutableAppContext) {
200 let state = &self.state;
201 let cursor_shape = state.cursor_shape();
202
203 cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
204 if self.enabled {
205 filter.filtered_namespaces.remove("vim");
206 } else {
207 filter.filtered_namespaces.insert("vim");
208 }
209 });
210
211 for editor in self.editors.values() {
212 if let Some(editor) = editor.upgrade(cx) {
213 editor.update(cx, |editor, cx| {
214 if self.enabled {
215 editor.set_cursor_shape(cursor_shape, cx);
216 editor.set_clip_at_line_ends(state.clip_at_line_end(), cx);
217 editor.set_input_enabled(!state.vim_controlled());
218 editor.selections.line_mode =
219 matches!(state.mode, Mode::Visual { line: true });
220 let context_layer = state.keymap_context_layer();
221 editor.set_keymap_context_layer::<Self>(context_layer);
222 } else {
223 editor.set_cursor_shape(CursorShape::Bar, cx);
224 editor.set_clip_at_line_ends(false, cx);
225 editor.set_input_enabled(true);
226 editor.selections.line_mode = false;
227 editor.remove_keymap_context_layer::<Self>();
228 }
229 });
230 }
231 }
232 }
233}
234
235#[cfg(test)]
236mod test {
237 use indoc::indoc;
238 use search::BufferSearchBar;
239
240 use crate::{
241 state::Mode,
242 test_contexts::{NeovimBackedTestContext, VimTestContext},
243 };
244
245 #[gpui::test]
246 async fn test_initially_disabled(cx: &mut gpui::TestAppContext) {
247 let mut cx = VimTestContext::new(cx, false).await;
248 cx.simulate_keystrokes(["h", "j", "k", "l"]);
249 cx.assert_editor_state("hjklˇ");
250 }
251
252 #[gpui::test]
253 async fn test_neovim(cx: &mut gpui::TestAppContext) {
254 let mut cx = NeovimBackedTestContext::new(cx).await;
255
256 cx.simulate_shared_keystroke("i").await;
257 cx.simulate_shared_keystrokes([
258 "shift-T", "e", "s", "t", " ", "t", "e", "s", "t", "escape", "0", "d", "w",
259 ])
260 .await;
261 cx.assert_state_matches().await;
262 cx.assert_editor_state("ˇtest");
263 }
264
265 #[gpui::test]
266 async fn test_toggle_through_settings(cx: &mut gpui::TestAppContext) {
267 let mut cx = VimTestContext::new(cx, true).await;
268
269 cx.simulate_keystroke("i");
270 assert_eq!(cx.mode(), Mode::Insert);
271
272 // Editor acts as though vim is disabled
273 cx.disable_vim();
274 cx.simulate_keystrokes(["h", "j", "k", "l"]);
275 cx.assert_editor_state("hjklˇ");
276
277 // Selections aren't changed if editor is blurred but vim-mode is still disabled.
278 cx.set_state("«hjklˇ»", Mode::Normal);
279 cx.assert_editor_state("«hjklˇ»");
280 cx.update_editor(|_, cx| cx.blur());
281 cx.assert_editor_state("«hjklˇ»");
282 cx.update_editor(|_, cx| cx.focus_self());
283 cx.assert_editor_state("«hjklˇ»");
284
285 // Enabling dynamically sets vim mode again and restores normal mode
286 cx.enable_vim();
287 assert_eq!(cx.mode(), Mode::Normal);
288 cx.simulate_keystrokes(["h", "h", "h", "l"]);
289 assert_eq!(cx.buffer_text(), "hjkl".to_owned());
290 cx.assert_editor_state("hˇjkl");
291 cx.simulate_keystrokes(["i", "T", "e", "s", "t"]);
292 cx.assert_editor_state("hTestˇjkl");
293
294 // Disabling and enabling resets to normal mode
295 assert_eq!(cx.mode(), Mode::Insert);
296 cx.disable_vim();
297 cx.enable_vim();
298 assert_eq!(cx.mode(), Mode::Normal);
299 }
300
301 #[gpui::test]
302 async fn test_buffer_search(cx: &mut gpui::TestAppContext) {
303 let mut cx = VimTestContext::new(cx, true).await;
304
305 cx.set_state(
306 indoc! {"
307 The quick brown
308 fox juˇmps over
309 the lazy dog"},
310 Mode::Normal,
311 );
312 cx.simulate_keystroke("/");
313
314 // We now use a weird insert mode with selection when jumping to a single line editor
315 assert_eq!(cx.mode(), Mode::Insert);
316
317 let search_bar = cx.workspace(|workspace, cx| {
318 workspace
319 .active_pane()
320 .read(cx)
321 .toolbar()
322 .read(cx)
323 .item_of_type::<BufferSearchBar>()
324 .expect("Buffer search bar should be deployed")
325 });
326
327 search_bar.read_with(cx.cx, |bar, cx| {
328 assert_eq!(bar.query_editor.read(cx).text(cx), "jumps");
329 })
330 }
331}