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