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