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