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};
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, 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, _: &Cancel, cx| {
49 // If we are in a non normal mode or have an active operator, swap to normal mode
50 // Otherwise forward cancel on to the editor
51 let vim = Vim::read(cx);
52 if vim.state.mode != Mode::Normal || vim.active_operator().is_some() {
53 MutableAppContext::defer(cx, |cx| {
54 Vim::update(cx, |state, cx| {
55 state.switch_mode(Mode::Normal, cx);
56 });
57 });
58 } else {
59 cx.propagate_action();
60 }
61 });
62
63 // Sync initial settings with the rest of the app
64 Vim::update(cx, |state, cx| state.sync_vim_settings(cx));
65
66 // Any time settings change, update vim mode to match
67 cx.observe_global::<Settings, _>(|cx| {
68 Vim::update(cx, |state, cx| {
69 state.set_enabled(cx.global::<Settings>().vim_mode, cx)
70 })
71 })
72 .detach();
73}
74
75#[derive(Default)]
76pub struct Vim {
77 editors: HashMap<usize, WeakViewHandle<Editor>>,
78 active_editor: Option<WeakViewHandle<Editor>>,
79 selection_subscription: Option<Subscription>,
80
81 enabled: bool,
82 state: VimState,
83}
84
85impl Vim {
86 fn read(cx: &mut MutableAppContext) -> &Self {
87 cx.default_global()
88 }
89
90 fn update<F, S>(cx: &mut MutableAppContext, update: F) -> S
91 where
92 F: FnOnce(&mut Self, &mut MutableAppContext) -> S,
93 {
94 cx.update_default_global(update)
95 }
96
97 fn update_active_editor<S>(
98 &self,
99 cx: &mut MutableAppContext,
100 update: impl FnOnce(&mut Editor, &mut ViewContext<Editor>) -> S,
101 ) -> Option<S> {
102 self.active_editor
103 .clone()
104 .and_then(|ae| ae.upgrade(cx))
105 .map(|ae| ae.update(cx, update))
106 }
107
108 fn switch_mode(&mut self, mode: Mode, cx: &mut MutableAppContext) {
109 let previous_mode = self.state.mode;
110 self.state.mode = mode;
111 self.state.operator_stack.clear();
112
113 // Sync editor settings like clip mode
114 self.sync_vim_settings(cx);
115
116 // Adjust selections
117 for editor in self.editors.values() {
118 if let Some(editor) = editor.upgrade(cx) {
119 editor.update(cx, |editor, cx| {
120 editor.change_selections(None, cx, |s| {
121 s.move_with(|map, selection| {
122 // If empty selections
123 if self.state.empty_selections_only() {
124 let new_head = map.clip_point(selection.head(), Bias::Left);
125 selection.collapse_to(new_head, selection.goal)
126 } else {
127 if matches!(mode, Mode::Visual { line: false })
128 && !matches!(previous_mode, Mode::Visual { .. })
129 && !selection.reversed
130 && !selection.is_empty()
131 {
132 // Mode wasn't visual mode before, but is now. We need to move the end
133 // back by one character so that the region to be modifed stays the same
134 *selection.end.column_mut() =
135 selection.end.column().saturating_sub(1);
136 selection.end = map.clip_point(selection.end, Bias::Left);
137 }
138
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, 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_switches_mode(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 assert_eq!(cx.mode(), Mode::Visual { line: false });
282
283 let search_bar = cx.workspace(|workspace, cx| {
284 workspace
285 .active_pane()
286 .read(cx)
287 .toolbar()
288 .read(cx)
289 .item_of_type::<BufferSearchBar>()
290 .expect("Buffer search bar should be deployed")
291 });
292
293 search_bar.read_with(cx.cx, |bar, cx| {
294 assert_eq!(bar.query_editor.read(cx).text(cx), "jumps");
295 })
296 }
297}