1#[cfg(test)]
2mod test;
3
4mod editor_events;
5mod insert;
6mod motion;
7mod normal;
8mod object;
9mod state;
10mod utils;
11mod visual;
12
13use anyhow::Result;
14use collections::CommandPaletteFilter;
15use editor::{Bias, Editor, EditorMode, Event};
16use gpui::{
17 actions, impl_actions, keymap_matcher::KeymapContext, keymap_matcher::MatchResult, AppContext,
18 Subscription, ViewContext, ViewHandle, WeakViewHandle, WindowContext,
19};
20use language::CursorShape;
21use motion::Motion;
22use normal::normal_replace;
23use serde::Deserialize;
24use settings::{Setting, SettingsStore};
25use state::{Mode, Operator, VimState};
26use std::sync::Arc;
27use visual::visual_replace;
28use workspace::{self, Workspace};
29
30struct VimModeSetting(bool);
31
32#[derive(Clone, Deserialize, PartialEq)]
33pub struct SwitchMode(pub Mode);
34
35#[derive(Clone, Deserialize, PartialEq)]
36pub struct PushOperator(pub Operator);
37
38#[derive(Clone, Deserialize, PartialEq)]
39struct Number(u8);
40
41actions!(vim, [Tab, Enter]);
42impl_actions!(vim, [Number, SwitchMode, PushOperator]);
43
44pub fn init(cx: &mut AppContext) {
45 settings::register::<VimModeSetting>(cx);
46
47 editor_events::init(cx);
48 normal::init(cx);
49 visual::init(cx);
50 insert::init(cx);
51 object::init(cx);
52 motion::init(cx);
53
54 // Vim Actions
55 cx.add_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {
56 Vim::update(cx, |vim, cx| vim.switch_mode(mode, false, cx))
57 });
58 cx.add_action(
59 |_: &mut Workspace, &PushOperator(operator): &PushOperator, cx| {
60 Vim::update(cx, |vim, cx| vim.push_operator(operator, cx))
61 },
62 );
63 cx.add_action(|_: &mut Workspace, n: &Number, cx: _| {
64 Vim::update(cx, |vim, cx| vim.push_number(n, cx));
65 });
66
67 cx.add_action(|_: &mut Workspace, _: &Tab, cx| {
68 Vim::active_editor_input_ignored(" ".into(), cx)
69 });
70
71 cx.add_action(|_: &mut Workspace, _: &Enter, cx| {
72 Vim::active_editor_input_ignored("\n".into(), cx)
73 });
74
75 // Any time settings change, update vim mode to match. The Vim struct
76 // will be initialized as disabled by default, so we filter its commands
77 // out when starting up.
78 cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
79 filter.filtered_namespaces.insert("vim");
80 });
81 cx.update_default_global(|vim: &mut Vim, cx: &mut AppContext| {
82 vim.set_enabled(settings::get::<VimModeSetting>(cx).0, cx)
83 });
84 cx.observe_global::<SettingsStore, _>(|cx| {
85 cx.update_default_global(|vim: &mut Vim, cx: &mut AppContext| {
86 vim.set_enabled(settings::get::<VimModeSetting>(cx).0, cx)
87 });
88 })
89 .detach();
90}
91
92pub fn observe_keystrokes(cx: &mut WindowContext) {
93 cx.observe_keystrokes(|_keystroke, result, handled_by, cx| {
94 if result == &MatchResult::Pending {
95 return true;
96 }
97 if let Some(handled_by) = handled_by {
98 // Keystroke is handled by the vim system, so continue forward
99 if handled_by.namespace() == "vim" {
100 return true;
101 }
102 }
103
104 Vim::update(cx, |vim, cx| match vim.active_operator() {
105 Some(
106 Operator::FindForward { .. } | Operator::FindBackward { .. } | Operator::Replace,
107 ) => {}
108 Some(_) => {
109 vim.clear_operator(cx);
110 }
111 _ => {}
112 });
113 true
114 })
115 .detach()
116}
117
118#[derive(Default)]
119pub struct Vim {
120 active_editor: Option<WeakViewHandle<Editor>>,
121 editor_subscription: Option<Subscription>,
122
123 enabled: bool,
124 state: VimState,
125}
126
127impl Vim {
128 fn read(cx: &mut AppContext) -> &Self {
129 cx.default_global()
130 }
131
132 fn update<F, S>(cx: &mut WindowContext, update: F) -> S
133 where
134 F: FnOnce(&mut Self, &mut WindowContext) -> S,
135 {
136 cx.update_default_global(update)
137 }
138
139 fn set_active_editor(&mut self, editor: ViewHandle<Editor>, cx: &mut WindowContext) {
140 self.active_editor = Some(editor.downgrade());
141 self.editor_subscription = Some(cx.subscribe(&editor, |editor, event, cx| match event {
142 Event::SelectionsChanged { local: true } => {
143 let editor = editor.read(cx);
144 if editor.leader_replica_id().is_none() {
145 let newest_empty = editor.selections.newest::<usize>(cx).is_empty();
146 local_selections_changed(newest_empty, cx);
147 }
148 }
149 Event::InputIgnored { text } => {
150 Vim::active_editor_input_ignored(text.clone(), cx);
151 }
152 _ => {}
153 }));
154
155 if self.enabled {
156 let editor = editor.read(cx);
157 let editor_mode = editor.mode();
158 let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
159
160 if editor_mode == EditorMode::Full && !newest_selection_empty {
161 self.switch_mode(Mode::Visual { line: false }, true, cx);
162 }
163 }
164
165 self.sync_vim_settings(cx);
166 }
167
168 fn update_active_editor<S>(
169 &self,
170 cx: &mut WindowContext,
171 update: impl FnOnce(&mut Editor, &mut ViewContext<Editor>) -> S,
172 ) -> Option<S> {
173 let editor = self.active_editor.clone()?.upgrade(cx)?;
174 Some(editor.update(cx, update))
175 }
176
177 fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut WindowContext) {
178 self.state.mode = mode;
179 self.state.operator_stack.clear();
180
181 // Sync editor settings like clip mode
182 self.sync_vim_settings(cx);
183
184 if leave_selections {
185 return;
186 }
187
188 // Adjust selections
189 self.update_active_editor(cx, |editor, cx| {
190 editor.change_selections(None, cx, |s| {
191 s.move_with(|map, selection| {
192 if self.state.empty_selections_only() {
193 let new_head = map.clip_point(selection.head(), Bias::Left);
194 selection.collapse_to(new_head, selection.goal)
195 } else {
196 selection
197 .set_head(map.clip_point(selection.head(), Bias::Left), selection.goal);
198 }
199 });
200 })
201 });
202 }
203
204 fn push_operator(&mut self, operator: Operator, cx: &mut WindowContext) {
205 self.state.operator_stack.push(operator);
206 self.sync_vim_settings(cx);
207 }
208
209 fn push_number(&mut self, Number(number): &Number, cx: &mut WindowContext) {
210 if let Some(Operator::Number(current_number)) = self.active_operator() {
211 self.pop_operator(cx);
212 self.push_operator(Operator::Number(current_number * 10 + *number as usize), cx);
213 } else {
214 self.push_operator(Operator::Number(*number as usize), cx);
215 }
216 }
217
218 fn pop_operator(&mut self, cx: &mut WindowContext) -> Operator {
219 let popped_operator = self.state.operator_stack.pop()
220 .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
221 self.sync_vim_settings(cx);
222 popped_operator
223 }
224
225 fn pop_number_operator(&mut self, cx: &mut WindowContext) -> Option<usize> {
226 if let Some(Operator::Number(number)) = self.active_operator() {
227 self.pop_operator(cx);
228 return Some(number);
229 }
230 None
231 }
232
233 fn clear_operator(&mut self, cx: &mut WindowContext) {
234 self.state.operator_stack.clear();
235 self.sync_vim_settings(cx);
236 }
237
238 fn active_operator(&self) -> Option<Operator> {
239 self.state.operator_stack.last().copied()
240 }
241
242 fn active_editor_input_ignored(text: Arc<str>, cx: &mut WindowContext) {
243 if text.is_empty() {
244 return;
245 }
246
247 match Vim::read(cx).active_operator() {
248 Some(Operator::FindForward { before }) => {
249 let find = Motion::FindForward { before, text };
250 Vim::update(cx, |vim, _| vim.state.last_find = Some(find.clone()));
251 motion::motion(find, cx)
252 }
253 Some(Operator::FindBackward { after }) => {
254 let find = Motion::FindBackward { after, text };
255 Vim::update(cx, |vim, _| vim.state.last_find = Some(find.clone()));
256 motion::motion(find, cx)
257 }
258 Some(Operator::Replace) => match Vim::read(cx).state.mode {
259 Mode::Normal => normal_replace(text, cx),
260 Mode::Visual { line } => visual_replace(text, line, cx),
261 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
262 },
263 _ => {}
264 }
265 }
266
267 fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
268 if self.enabled != enabled {
269 self.enabled = enabled;
270 self.state = Default::default();
271
272 cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
273 if self.enabled {
274 filter.filtered_namespaces.remove("vim");
275 } else {
276 filter.filtered_namespaces.insert("vim");
277 }
278 });
279
280 cx.update_active_window(|cx| {
281 if self.enabled {
282 let active_editor = cx
283 .root_view()
284 .downcast_ref::<Workspace>()
285 .and_then(|workspace| workspace.read(cx).active_item(cx))
286 .and_then(|item| item.downcast::<Editor>());
287 if let Some(active_editor) = active_editor {
288 self.set_active_editor(active_editor, cx);
289 }
290 self.switch_mode(Mode::Normal, false, cx);
291 }
292 self.sync_vim_settings(cx);
293 });
294 }
295 }
296
297 fn sync_vim_settings(&self, cx: &mut WindowContext) {
298 let state = &self.state;
299 let cursor_shape = state.cursor_shape();
300
301 self.update_active_editor(cx, |editor, cx| {
302 if self.enabled && editor.mode() == EditorMode::Full {
303 editor.set_cursor_shape(cursor_shape, cx);
304 editor.set_clip_at_line_ends(state.clip_at_line_end(), cx);
305 editor.set_collapse_matches(true);
306 editor.set_input_enabled(!state.vim_controlled());
307 editor.selections.line_mode = matches!(state.mode, Mode::Visual { line: true });
308 let context_layer = state.keymap_context_layer();
309 editor.set_keymap_context_layer::<Self>(context_layer, cx);
310 } else {
311 // Note: set_collapse_matches is not in unhook_vim_settings, as that method is called on blur,
312 // but we need collapse_matches to persist when the search bar is focused.
313 editor.set_collapse_matches(false);
314 self.unhook_vim_settings(editor, cx);
315 }
316 });
317 }
318
319 fn unhook_vim_settings(&self, editor: &mut Editor, cx: &mut ViewContext<Editor>) {
320 editor.set_cursor_shape(CursorShape::Bar, cx);
321 editor.set_clip_at_line_ends(false, cx);
322 editor.set_input_enabled(true);
323 editor.selections.line_mode = false;
324
325 // we set the VimEnabled context on all editors so that we
326 // can distinguish between vim mode and non-vim mode in the BufferSearchBar.
327 // This is a bit of a hack, but currently the search crate does not depend on vim,
328 // and it seems nice to keep it that way.
329 if self.enabled {
330 let mut context = KeymapContext::default();
331 context.add_identifier("VimEnabled");
332 editor.set_keymap_context_layer::<Self>(context, cx)
333 } else {
334 editor.remove_keymap_context_layer::<Self>(cx);
335 }
336 }
337}
338
339impl Setting for VimModeSetting {
340 const KEY: Option<&'static str> = Some("vim_mode");
341
342 type FileContent = Option<bool>;
343
344 fn load(
345 default_value: &Self::FileContent,
346 user_values: &[&Self::FileContent],
347 _: &AppContext,
348 ) -> Result<Self> {
349 Ok(Self(user_values.iter().rev().find_map(|v| **v).unwrap_or(
350 default_value.ok_or_else(Self::missing_default)?,
351 )))
352 }
353}
354
355fn local_selections_changed(newest_empty: bool, cx: &mut WindowContext) {
356 Vim::update(cx, |vim, cx| {
357 if vim.enabled && vim.state.mode == Mode::Normal && !newest_empty {
358 vim.switch_mode(Mode::Visual { line: false }, false, cx)
359 }
360 })
361}