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, Cancel, Editor, EditorMode, Event};
16use gpui::{
17 actions, impl_actions, AppContext, Subscription, ViewContext, ViewHandle, WeakViewHandle,
18 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 // Editor Actions
68 cx.add_action(|_: &mut Editor, _: &Cancel, cx| {
69 // If we are in aren't in normal mode or have an active operator, swap to normal mode
70 // Otherwise forward cancel on to the editor
71 let vim = Vim::read(cx);
72 if vim.state.mode != Mode::Normal || vim.active_operator().is_some() {
73 WindowContext::defer(cx, |cx| {
74 Vim::update(cx, |state, cx| {
75 state.switch_mode(Mode::Normal, false, cx);
76 });
77 });
78 } else {
79 cx.propagate_action();
80 }
81 });
82
83 cx.add_action(|_: &mut Workspace, _: &Tab, cx| {
84 Vim::active_editor_input_ignored(" ".into(), cx)
85 });
86
87 cx.add_action(|_: &mut Workspace, _: &Enter, cx| {
88 Vim::active_editor_input_ignored("\n".into(), cx)
89 });
90
91 // Any time settings change, update vim mode to match. The Vim struct
92 // will be initialized as disabled by default, so we filter its commands
93 // out when starting up.
94 cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
95 filter.filtered_namespaces.insert("vim");
96 });
97 cx.update_default_global(|vim: &mut Vim, cx: &mut AppContext| {
98 vim.set_enabled(settings::get::<VimModeSetting>(cx).0, cx)
99 });
100 cx.observe_global::<SettingsStore, _>(|cx| {
101 cx.update_default_global(|vim: &mut Vim, cx: &mut AppContext| {
102 vim.set_enabled(settings::get::<VimModeSetting>(cx).0, cx)
103 });
104 })
105 .detach();
106}
107
108pub fn observe_keystrokes(cx: &mut WindowContext) {
109 cx.observe_keystrokes(|_keystroke, _result, handled_by, cx| {
110 if let Some(handled_by) = handled_by {
111 // Keystroke is handled by the vim system, so continue forward
112 // Also short circuit if it is the special cancel action
113 if handled_by.namespace() == "vim"
114 || (handled_by.namespace() == "editor" && handled_by.name() == "Cancel")
115 {
116 return true;
117 }
118 }
119
120 Vim::update(cx, |vim, cx| match vim.active_operator() {
121 Some(
122 Operator::FindForward { .. } | Operator::FindBackward { .. } | Operator::Replace,
123 ) => {}
124 Some(_) => {
125 vim.clear_operator(cx);
126 }
127 _ => {}
128 });
129 true
130 })
131 .detach()
132}
133
134#[derive(Default)]
135pub struct Vim {
136 active_editor: Option<WeakViewHandle<Editor>>,
137 editor_subscription: Option<Subscription>,
138
139 enabled: bool,
140 state: VimState,
141}
142
143impl Vim {
144 fn read(cx: &mut AppContext) -> &Self {
145 cx.default_global()
146 }
147
148 fn update<F, S>(cx: &mut WindowContext, update: F) -> S
149 where
150 F: FnOnce(&mut Self, &mut WindowContext) -> S,
151 {
152 cx.update_default_global(update)
153 }
154
155 fn set_active_editor(&mut self, editor: ViewHandle<Editor>, cx: &mut WindowContext) {
156 self.active_editor = Some(editor.downgrade());
157 self.editor_subscription = Some(cx.subscribe(&editor, |editor, event, cx| match event {
158 Event::SelectionsChanged { local: true } => {
159 let editor = editor.read(cx);
160 if editor.leader_replica_id().is_none() {
161 let newest_empty = editor.selections.newest::<usize>(cx).is_empty();
162 local_selections_changed(newest_empty, cx);
163 }
164 }
165 Event::InputIgnored { text } => {
166 Vim::active_editor_input_ignored(text.clone(), cx);
167 }
168 _ => {}
169 }));
170
171 if self.enabled {
172 let editor = editor.read(cx);
173 let editor_mode = editor.mode();
174 let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
175
176 if editor_mode == EditorMode::Full && !newest_selection_empty {
177 self.switch_mode(Mode::Visual { line: false }, true, cx);
178 }
179 }
180
181 self.sync_vim_settings(cx);
182 }
183
184 fn update_active_editor<S>(
185 &self,
186 cx: &mut WindowContext,
187 update: impl FnOnce(&mut Editor, &mut ViewContext<Editor>) -> S,
188 ) -> Option<S> {
189 let editor = self.active_editor.clone()?.upgrade(cx)?;
190 Some(editor.update(cx, update))
191 }
192
193 fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut WindowContext) {
194 self.state.mode = mode;
195 self.state.operator_stack.clear();
196
197 // Sync editor settings like clip mode
198 self.sync_vim_settings(cx);
199
200 if leave_selections {
201 return;
202 }
203
204 // Adjust selections
205 self.update_active_editor(cx, |editor, cx| {
206 editor.change_selections(None, cx, |s| {
207 s.move_with(|map, selection| {
208 if self.state.empty_selections_only() {
209 let new_head = map.clip_point(selection.head(), Bias::Left);
210 selection.collapse_to(new_head, selection.goal)
211 } else {
212 selection
213 .set_head(map.clip_point(selection.head(), Bias::Left), selection.goal);
214 }
215 });
216 })
217 });
218 }
219
220 fn push_operator(&mut self, operator: Operator, cx: &mut WindowContext) {
221 self.state.operator_stack.push(operator);
222 self.sync_vim_settings(cx);
223 }
224
225 fn push_number(&mut self, Number(number): &Number, cx: &mut WindowContext) {
226 if let Some(Operator::Number(current_number)) = self.active_operator() {
227 self.pop_operator(cx);
228 self.push_operator(Operator::Number(current_number * 10 + *number as usize), cx);
229 } else {
230 self.push_operator(Operator::Number(*number as usize), cx);
231 }
232 }
233
234 fn pop_operator(&mut self, cx: &mut WindowContext) -> Operator {
235 let popped_operator = self.state.operator_stack.pop()
236 .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
237 self.sync_vim_settings(cx);
238 popped_operator
239 }
240
241 fn pop_number_operator(&mut self, cx: &mut WindowContext) -> usize {
242 let mut times = 1;
243 if let Some(Operator::Number(number)) = self.active_operator() {
244 times = number;
245 self.pop_operator(cx);
246 }
247 times
248 }
249
250 fn clear_operator(&mut self, cx: &mut WindowContext) {
251 self.state.operator_stack.clear();
252 self.sync_vim_settings(cx);
253 }
254
255 fn active_operator(&self) -> Option<Operator> {
256 self.state.operator_stack.last().copied()
257 }
258
259 fn active_editor_input_ignored(text: Arc<str>, cx: &mut WindowContext) {
260 if text.is_empty() {
261 return;
262 }
263
264 match Vim::read(cx).active_operator() {
265 Some(Operator::FindForward { before }) => {
266 motion::motion(Motion::FindForward { before, text }, cx)
267 }
268 Some(Operator::FindBackward { after }) => {
269 motion::motion(Motion::FindBackward { after, text }, cx)
270 }
271 Some(Operator::Replace) => match Vim::read(cx).state.mode {
272 Mode::Normal => normal_replace(text, cx),
273 Mode::Visual { line } => visual_replace(text, line, 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_end(), cx);
318 editor.set_input_enabled(!state.vim_controlled());
319 editor.selections.line_mode = matches!(state.mode, Mode::Visual { line: true });
320 let context_layer = state.keymap_context_layer();
321 editor.set_keymap_context_layer::<Self>(context_layer, cx);
322 } else {
323 Self::unhook_vim_settings(editor, cx);
324 }
325 });
326 }
327
328 fn unhook_vim_settings(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
329 editor.set_cursor_shape(CursorShape::Bar, cx);
330 editor.set_clip_at_line_ends(false, cx);
331 editor.set_input_enabled(true);
332 editor.selections.line_mode = false;
333 editor.remove_keymap_context_layer::<Self>(cx);
334 }
335}
336
337impl Setting for VimModeSetting {
338 const KEY: Option<&'static str> = Some("vim_mode");
339
340 type FileContent = Option<bool>;
341
342 fn load(
343 default_value: &Self::FileContent,
344 user_values: &[&Self::FileContent],
345 _: &AppContext,
346 ) -> Result<Self> {
347 Ok(Self(user_values.iter().rev().find_map(|v| **v).unwrap_or(
348 default_value.ok_or_else(Self::missing_default)?,
349 )))
350 }
351}
352
353fn local_selections_changed(newest_empty: bool, cx: &mut WindowContext) {
354 Vim::update(cx, |vim, cx| {
355 if vim.enabled && vim.state.mode == Mode::Normal && !newest_empty {
356 vim.switch_mode(Mode::Visual { line: false }, false, cx)
357 }
358 })
359}