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 std::sync::Arc;
14
15use collections::CommandPaletteFilter;
16use editor::{Bias, Cancel, Editor, EditorMode, Event};
17use gpui::{
18 actions, impl_actions, AppContext, Subscription, ViewContext, ViewHandle, WeakViewHandle,
19 WindowContext,
20};
21use language::CursorShape;
22use motion::Motion;
23use normal::normal_replace;
24use serde::Deserialize;
25use settings::Settings;
26use state::{Mode, Operator, VimState};
27use visual::visual_replace;
28use workspace::{self, Workspace};
29
30#[derive(Clone, Deserialize, PartialEq)]
31pub struct SwitchMode(pub Mode);
32
33#[derive(Clone, Deserialize, PartialEq)]
34pub struct PushOperator(pub Operator);
35
36#[derive(Clone, Deserialize, PartialEq)]
37struct Number(u8);
38
39actions!(vim, [Tab, Enter]);
40impl_actions!(vim, [Number, SwitchMode, PushOperator]);
41
42pub fn init(cx: &mut AppContext) {
43 editor_events::init(cx);
44 normal::init(cx);
45 visual::init(cx);
46 insert::init(cx);
47 object::init(cx);
48 motion::init(cx);
49
50 // Vim Actions
51 cx.add_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {
52 Vim::update(cx, |vim, cx| vim.switch_mode(mode, false, cx))
53 });
54 cx.add_action(
55 |_: &mut Workspace, &PushOperator(operator): &PushOperator, cx| {
56 Vim::update(cx, |vim, cx| vim.push_operator(operator, cx))
57 },
58 );
59 cx.add_action(|_: &mut Workspace, n: &Number, cx: _| {
60 Vim::update(cx, |vim, cx| vim.push_number(n, cx));
61 });
62
63 // Editor Actions
64 cx.add_action(|_: &mut Editor, _: &Cancel, cx| {
65 // If we are in aren't in normal mode or have an active operator, swap to normal mode
66 // Otherwise forward cancel on to the editor
67 let vim = Vim::read(cx);
68 if vim.state.mode != Mode::Normal || vim.active_operator().is_some() {
69 WindowContext::defer(cx, |cx| {
70 Vim::update(cx, |state, cx| {
71 state.switch_mode(Mode::Normal, false, cx);
72 });
73 });
74 } else {
75 cx.propagate_action();
76 }
77 });
78
79 cx.add_action(|_: &mut Workspace, _: &Tab, cx| {
80 Vim::active_editor_input_ignored(" ".into(), cx)
81 });
82
83 cx.add_action(|_: &mut Workspace, _: &Enter, cx| {
84 Vim::active_editor_input_ignored("\n".into(), cx)
85 });
86
87 // Any time settings change, update vim mode to match. The Vim struct
88 // will be initialized as disabled by default, so we filter its commands
89 // out when starting up.
90 cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
91 filter.filtered_namespaces.insert("vim");
92 });
93 cx.update_default_global(|vim: &mut Vim, cx: &mut AppContext| {
94 vim.set_enabled(cx.global::<Settings>().vim_mode, cx)
95 });
96 cx.observe_global::<Settings, _>(|cx| {
97 cx.update_default_global(|vim: &mut Vim, cx: &mut AppContext| {
98 vim.set_enabled(cx.global::<Settings>().vim_mode, cx)
99 });
100 })
101 .detach();
102}
103
104pub fn observe_keystrokes(cx: &mut WindowContext) {
105 cx.observe_keystrokes(|_keystroke, _result, handled_by, cx| {
106 if let Some(handled_by) = handled_by {
107 // Keystroke is handled by the vim system, so continue forward
108 // Also short circuit if it is the special cancel action
109 if handled_by.namespace() == "vim"
110 || (handled_by.namespace() == "editor" && handled_by.name() == "Cancel")
111 {
112 return true;
113 }
114 }
115
116 Vim::update(cx, |vim, cx| match vim.active_operator() {
117 Some(
118 Operator::FindForward { .. } | Operator::FindBackward { .. } | Operator::Replace,
119 ) => {}
120 Some(_) => {
121 vim.clear_operator(cx);
122 }
123 _ => {}
124 });
125 true
126 })
127 .detach()
128}
129
130#[derive(Default)]
131pub struct Vim {
132 active_editor: Option<WeakViewHandle<Editor>>,
133 editor_subscription: Option<Subscription>,
134
135 enabled: bool,
136 state: VimState,
137}
138
139impl Vim {
140 fn read(cx: &mut AppContext) -> &Self {
141 cx.default_global()
142 }
143
144 fn update<F, S>(cx: &mut WindowContext, update: F) -> S
145 where
146 F: FnOnce(&mut Self, &mut WindowContext) -> S,
147 {
148 cx.update_default_global(update)
149 }
150
151 fn set_active_editor(&mut self, editor: ViewHandle<Editor>, cx: &mut WindowContext) {
152 self.active_editor = Some(editor.downgrade());
153 self.editor_subscription = Some(cx.subscribe(&editor, |editor, event, cx| match event {
154 Event::SelectionsChanged { local: true } => {
155 let editor = editor.read(cx);
156 if editor.leader_replica_id().is_none() {
157 let newest_empty = editor.selections.newest::<usize>(cx).is_empty();
158 local_selections_changed(newest_empty, cx);
159 }
160 }
161 Event::InputIgnored { text } => {
162 Vim::active_editor_input_ignored(text.clone(), cx);
163 }
164 _ => {}
165 }));
166
167 if self.enabled {
168 let editor = editor.read(cx);
169 let editor_mode = editor.mode();
170 let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
171
172 if editor_mode == EditorMode::Full && !newest_selection_empty {
173 self.switch_mode(Mode::Visual { line: false }, true, cx);
174 }
175 }
176
177 self.sync_vim_settings(cx);
178 }
179
180 fn update_active_editor<S>(
181 &self,
182 cx: &mut WindowContext,
183 update: impl FnOnce(&mut Editor, &mut ViewContext<Editor>) -> S,
184 ) -> Option<S> {
185 let editor = self.active_editor.clone()?.upgrade(cx)?;
186 Some(editor.update(cx, update))
187 }
188
189 fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut WindowContext) {
190 self.state.mode = mode;
191 self.state.operator_stack.clear();
192
193 // Sync editor settings like clip mode
194 self.sync_vim_settings(cx);
195
196 if leave_selections {
197 return;
198 }
199
200 // Adjust selections
201 self.update_active_editor(cx, |editor, cx| {
202 editor.change_selections(None, cx, |s| {
203 s.move_with(|map, selection| {
204 if self.state.empty_selections_only() {
205 let new_head = map.clip_point(selection.head(), Bias::Left);
206 selection.collapse_to(new_head, selection.goal)
207 } else {
208 selection
209 .set_head(map.clip_point(selection.head(), Bias::Left), selection.goal);
210 }
211 });
212 })
213 });
214 }
215
216 fn push_operator(&mut self, operator: Operator, cx: &mut WindowContext) {
217 self.state.operator_stack.push(operator);
218 self.sync_vim_settings(cx);
219 }
220
221 fn push_number(&mut self, Number(number): &Number, cx: &mut WindowContext) {
222 if let Some(Operator::Number(current_number)) = self.active_operator() {
223 self.pop_operator(cx);
224 self.push_operator(Operator::Number(current_number * 10 + *number as usize), cx);
225 } else {
226 self.push_operator(Operator::Number(*number as usize), cx);
227 }
228 }
229
230 fn pop_operator(&mut self, cx: &mut WindowContext) -> Operator {
231 let popped_operator = self.state.operator_stack.pop()
232 .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
233 self.sync_vim_settings(cx);
234 popped_operator
235 }
236
237 fn pop_number_operator(&mut self, cx: &mut WindowContext) -> usize {
238 let mut times = 1;
239 if let Some(Operator::Number(number)) = self.active_operator() {
240 times = number;
241 self.pop_operator(cx);
242 }
243 times
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 motion::motion(Motion::FindForward { before, text }, cx)
263 }
264 Some(Operator::FindBackward { after }) => {
265 motion::motion(Motion::FindBackward { after, text }, cx)
266 }
267 Some(Operator::Replace) => match Vim::read(cx).state.mode {
268 Mode::Normal => normal_replace(text, cx),
269 Mode::Visual { line } => visual_replace(text, line, cx),
270 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
271 },
272 _ => {}
273 }
274 }
275
276 fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
277 if self.enabled != enabled {
278 self.enabled = enabled;
279 self.state = Default::default();
280
281 cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
282 if self.enabled {
283 filter.filtered_namespaces.remove("vim");
284 } else {
285 filter.filtered_namespaces.insert("vim");
286 }
287 });
288
289 cx.update_active_window(|cx| {
290 if self.enabled {
291 let active_editor = cx
292 .root_view()
293 .downcast_ref::<Workspace>()
294 .and_then(|workspace| workspace.read(cx).active_item(cx))
295 .and_then(|item| item.downcast::<Editor>());
296 if let Some(active_editor) = active_editor {
297 self.set_active_editor(active_editor, cx);
298 }
299 self.switch_mode(Mode::Normal, false, cx);
300 }
301 self.sync_vim_settings(cx);
302 });
303 }
304 }
305
306 fn sync_vim_settings(&self, cx: &mut WindowContext) {
307 let state = &self.state;
308 let cursor_shape = state.cursor_shape();
309
310 self.update_active_editor(cx, |editor, cx| {
311 if self.enabled && editor.mode() == EditorMode::Full {
312 editor.set_cursor_shape(cursor_shape, cx);
313 editor.set_clip_at_line_ends(state.clip_at_line_end(), cx);
314 editor.set_input_enabled(!state.vim_controlled());
315 editor.selections.line_mode = matches!(state.mode, Mode::Visual { line: true });
316 let context_layer = state.keymap_context_layer();
317 editor.set_keymap_context_layer::<Self>(context_layer, cx);
318 } else {
319 Self::unhook_vim_settings(editor, cx);
320 }
321 });
322 }
323
324 fn unhook_vim_settings(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
325 editor.set_cursor_shape(CursorShape::Bar, cx);
326 editor.set_clip_at_line_ends(false, cx);
327 editor.set_input_enabled(true);
328 editor.selections.line_mode = false;
329 editor.remove_keymap_context_layer::<Self>(cx);
330 }
331}
332
333fn local_selections_changed(newest_empty: bool, cx: &mut WindowContext) {
334 Vim::update(cx, |vim, cx| {
335 if vim.enabled && vim.state.mode == Mode::Normal && !newest_empty {
336 vim.switch_mode(Mode::Visual { line: false }, false, cx)
337 }
338 })
339}