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::MatchResult, keymap_matcher::KeymapContext, AppContext, Subscription, ViewContext,
18 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 motion::motion(Motion::FindForward { before, text }, cx)
250 }
251 Some(Operator::FindBackward { after }) => {
252 motion::motion(Motion::FindBackward { after, text }, cx)
253 }
254 Some(Operator::Replace) => match Vim::read(cx).state.mode {
255 Mode::Normal => normal_replace(text, cx),
256 Mode::Visual { line } => visual_replace(text, line, cx),
257 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
258 },
259 _ => {}
260 }
261 }
262
263 fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
264 if self.enabled != enabled {
265 self.enabled = enabled;
266 self.state = Default::default();
267
268 cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
269 if self.enabled {
270 filter.filtered_namespaces.remove("vim");
271 } else {
272 filter.filtered_namespaces.insert("vim");
273 }
274 });
275
276 cx.update_active_window(|cx| {
277 if self.enabled {
278 let active_editor = cx
279 .root_view()
280 .downcast_ref::<Workspace>()
281 .and_then(|workspace| workspace.read(cx).active_item(cx))
282 .and_then(|item| item.downcast::<Editor>());
283 if let Some(active_editor) = active_editor {
284 self.set_active_editor(active_editor, cx);
285 }
286 self.switch_mode(Mode::Normal, false, cx);
287 }
288 self.sync_vim_settings(cx);
289 });
290 }
291 }
292
293 fn sync_vim_settings(&self, cx: &mut WindowContext) {
294 let state = &self.state;
295 let cursor_shape = state.cursor_shape();
296
297 self.update_active_editor(cx, |editor, cx| {
298 if self.enabled && editor.mode() == EditorMode::Full {
299 editor.set_cursor_shape(cursor_shape, cx);
300 editor.set_clip_at_line_ends(state.clip_at_line_end(), cx);
301 editor.set_collapse_matches(true);
302 editor.set_input_enabled(!state.vim_controlled());
303 editor.selections.line_mode = matches!(state.mode, Mode::Visual { line: true });
304 let context_layer = state.keymap_context_layer();
305 editor.set_keymap_context_layer::<Self>(context_layer, cx);
306 } else {
307 // Note: set_collapse_matches is not in unhook_vim_settings, as that method is called on blur,
308 // but we need collapse_matches to persist when the search bar is focused.
309 editor.set_collapse_matches(false);
310 self.unhook_vim_settings(editor, cx);
311 }
312 });
313 }
314
315 fn unhook_vim_settings(&self, editor: &mut Editor, cx: &mut ViewContext<Editor>) {
316 editor.set_cursor_shape(CursorShape::Bar, cx);
317 editor.set_clip_at_line_ends(false, cx);
318 editor.set_input_enabled(true);
319 editor.selections.line_mode = false;
320
321 // we set the VimEnabled context on all editors so that we
322 // can distinguish between vim mode and non-vim mode in the BufferSearchBar.
323 // This is a bit of a hack, but currently the search crate does not depend on vim,
324 // and it seems nice to keep it that way.
325 if self.enabled {
326 let mut context = KeymapContext::default();
327 context.add_identifier("VimEnabled");
328 editor.set_keymap_context_layer::<Self>(context, cx)
329 } else {
330 editor.remove_keymap_context_layer::<Self>(cx);
331 }
332 }
333}
334
335impl Setting for VimModeSetting {
336 const KEY: Option<&'static str> = Some("vim_mode");
337
338 type FileContent = Option<bool>;
339
340 fn load(
341 default_value: &Self::FileContent,
342 user_values: &[&Self::FileContent],
343 _: &AppContext,
344 ) -> Result<Self> {
345 Ok(Self(user_values.iter().rev().find_map(|v| **v).unwrap_or(
346 default_value.ok_or_else(Self::missing_default)?,
347 )))
348 }
349}
350
351fn local_selections_changed(newest_empty: bool, cx: &mut WindowContext) {
352 Vim::update(cx, |vim, cx| {
353 if vim.enabled && vim.state.mode == Mode::Normal && !newest_empty {
354 vim.switch_mode(Mode::Visual { line: false }, false, cx)
355 }
356 })
357}