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, 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, _: &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, false, 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, leave_selections: bool, cx: &mut MutableAppContext) {
109 self.state.mode = mode;
110 self.state.operator_stack.clear();
111
112 // Sync editor settings like clip mode
113 self.sync_vim_settings(cx);
114
115 if leave_selections {
116 return;
117 }
118
119 // Adjust selections
120 for editor in self.editors.values() {
121 if let Some(editor) = editor.upgrade(cx) {
122 editor.update(cx, |editor, cx| {
123 editor.change_selections(None, cx, |s| {
124 s.move_with(|map, selection| {
125 if self.state.empty_selections_only() {
126 let new_head = map.clip_point(selection.head(), Bias::Left);
127 selection.collapse_to(new_head, selection.goal)
128 } else {
129 selection.set_head(
130 map.clip_point(selection.head(), Bias::Left),
131 selection.goal,
132 );
133 }
134 });
135 })
136 })
137 }
138 }
139 }
140
141 fn push_operator(&mut self, operator: Operator, cx: &mut MutableAppContext) {
142 self.state.operator_stack.push(operator);
143 self.sync_vim_settings(cx);
144 }
145
146 fn pop_operator(&mut self, cx: &mut MutableAppContext) -> Operator {
147 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");
148 self.sync_vim_settings(cx);
149 popped_operator
150 }
151
152 fn clear_operator(&mut self, cx: &mut MutableAppContext) {
153 self.state.operator_stack.clear();
154 self.sync_vim_settings(cx);
155 }
156
157 fn active_operator(&self) -> Option<Operator> {
158 self.state.operator_stack.last().copied()
159 }
160
161 fn set_enabled(&mut self, enabled: bool, cx: &mut MutableAppContext) {
162 if self.enabled != enabled {
163 self.enabled = enabled;
164 self.state = Default::default();
165 if enabled {
166 self.switch_mode(Mode::Normal, false, cx);
167 }
168 self.sync_vim_settings(cx);
169 }
170 }
171
172 fn sync_vim_settings(&self, cx: &mut MutableAppContext) {
173 let state = &self.state;
174 let cursor_shape = state.cursor_shape();
175
176 cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
177 if self.enabled {
178 filter.filtered_namespaces.remove("vim");
179 } else {
180 filter.filtered_namespaces.insert("vim");
181 }
182 });
183
184 for editor in self.editors.values() {
185 if let Some(editor) = editor.upgrade(cx) {
186 editor.update(cx, |editor, cx| {
187 if self.enabled {
188 editor.set_cursor_shape(cursor_shape, cx);
189 editor.set_clip_at_line_ends(state.clip_at_line_end(), cx);
190 editor.set_input_enabled(!state.vim_controlled());
191 editor.selections.line_mode =
192 matches!(state.mode, Mode::Visual { line: true });
193 let context_layer = state.keymap_context_layer();
194 editor.set_keymap_context_layer::<Self>(context_layer);
195 } else {
196 editor.set_cursor_shape(CursorShape::Bar, cx);
197 editor.set_clip_at_line_ends(false, cx);
198 editor.set_input_enabled(true);
199 editor.selections.line_mode = false;
200 editor.remove_keymap_context_layer::<Self>();
201 }
202 });
203 }
204 }
205 }
206}
207
208#[cfg(test)]
209mod test {
210 use indoc::indoc;
211 use search::BufferSearchBar;
212
213 use crate::{state::Mode, vim_test_context::VimTestContext};
214
215 #[gpui::test]
216 async fn test_initially_disabled(cx: &mut gpui::TestAppContext) {
217 let mut cx = VimTestContext::new(cx, false).await;
218 cx.simulate_keystrokes(["h", "j", "k", "l"]);
219 cx.assert_editor_state("hjklˇ");
220 }
221
222 #[gpui::test]
223 async fn test_toggle_through_settings(cx: &mut gpui::TestAppContext) {
224 let mut cx = VimTestContext::new(cx, true).await;
225
226 cx.simulate_keystroke("i");
227 assert_eq!(cx.mode(), Mode::Insert);
228
229 // Editor acts as though vim is disabled
230 cx.disable_vim();
231 cx.simulate_keystrokes(["h", "j", "k", "l"]);
232 cx.assert_editor_state("hjklˇ");
233
234 // Selections aren't changed if editor is blurred but vim-mode is still disabled.
235 cx.set_state("«hjklˇ»", Mode::Normal);
236 cx.assert_editor_state("«hjklˇ»");
237 cx.update_editor(|_, cx| cx.blur());
238 cx.assert_editor_state("«hjklˇ»");
239 cx.update_editor(|_, cx| cx.focus_self());
240 cx.assert_editor_state("«hjklˇ»");
241
242 // Enabling dynamically sets vim mode again and restores normal mode
243 cx.enable_vim();
244 assert_eq!(cx.mode(), Mode::Normal);
245 cx.simulate_keystrokes(["h", "h", "h", "l"]);
246 assert_eq!(cx.buffer_text(), "hjkl".to_owned());
247 cx.assert_editor_state("hˇjkl");
248 cx.simulate_keystrokes(["i", "T", "e", "s", "t"]);
249 cx.assert_editor_state("hTestˇjkl");
250
251 // Disabling and enabling resets to normal mode
252 assert_eq!(cx.mode(), Mode::Insert);
253 cx.disable_vim();
254 cx.enable_vim();
255 assert_eq!(cx.mode(), Mode::Normal);
256 }
257
258 #[gpui::test]
259 async fn test_buffer_search(cx: &mut gpui::TestAppContext) {
260 let mut cx = VimTestContext::new(cx, true).await;
261
262 cx.set_state(
263 indoc! {"
264 The quick brown
265 fox juˇmps over
266 the lazy dog"},
267 Mode::Normal,
268 );
269 cx.simulate_keystroke("/");
270
271 // We now use a weird insert mode with selection when jumping to a single line editor
272 assert_eq!(cx.mode(), Mode::Insert);
273
274 let search_bar = cx.workspace(|workspace, cx| {
275 workspace
276 .active_pane()
277 .read(cx)
278 .toolbar()
279 .read(cx)
280 .item_of_type::<BufferSearchBar>()
281 .expect("Buffer search bar should be deployed")
282 });
283
284 search_bar.read_with(cx.cx, |bar, cx| {
285 assert_eq!(bar.query_editor.read(cx).text(cx), "jumps");
286 })
287 }
288}