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