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 collections::HashMap;
14use command_palette::CommandPaletteFilter;
15use editor::{Bias, Cancel, Editor, EditorMode};
16use gpui::{
17 impl_actions,
18 keymap_matcher::{KeyPressed, Keystroke},
19 MutableAppContext, Subscription, ViewContext, WeakViewHandle,
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
39impl_actions!(vim, [Number, SwitchMode, PushOperator]);
40
41pub fn init(cx: &mut MutableAppContext) {
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 cx.add_action(
62 |_: &mut Workspace, KeyPressed { keystroke }: &KeyPressed, cx| {
63 Vim::key_pressed(keystroke, cx);
64 },
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 MutableAppContext::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 // Sync initial settings with the rest of the app
84 Vim::update(cx, |state, cx| state.sync_vim_settings(cx));
85
86 // Any time settings change, update vim mode to match
87 cx.observe_global::<Settings, _>(|cx| {
88 Vim::update(cx, |state, cx| {
89 state.set_enabled(cx.global::<Settings>().vim_mode, cx)
90 })
91 })
92 .detach();
93}
94
95pub fn observe_keypresses(window_id: usize, cx: &mut MutableAppContext) {
96 cx.observe_keystrokes(window_id, |_keystroke, _result, handled_by, cx| {
97 if let Some(handled_by) = handled_by {
98 // Keystroke is handled by the vim system, so continue forward
99 // Also short circuit if it is the special cancel action
100 if handled_by.namespace() == "vim"
101 || (handled_by.namespace() == "editor" && handled_by.name() == "Cancel")
102 {
103 return true;
104 }
105 }
106
107 Vim::update(cx, |vim, cx| {
108 if vim.active_operator().is_some() {
109 // If the keystroke is not handled by vim, we should clear the operator
110 vim.clear_operator(cx);
111 }
112 });
113 true
114 })
115 .detach()
116}
117
118#[derive(Default)]
119pub struct Vim {
120 editors: HashMap<usize, WeakViewHandle<Editor>>,
121 active_editor: Option<WeakViewHandle<Editor>>,
122 selection_subscription: Option<Subscription>,
123
124 enabled: bool,
125 state: VimState,
126}
127
128impl Vim {
129 fn read(cx: &mut MutableAppContext) -> &Self {
130 cx.default_global()
131 }
132
133 fn update<F, S>(cx: &mut MutableAppContext, update: F) -> S
134 where
135 F: FnOnce(&mut Self, &mut MutableAppContext) -> S,
136 {
137 cx.update_default_global(update)
138 }
139
140 fn update_active_editor<S>(
141 &self,
142 cx: &mut MutableAppContext,
143 update: impl FnOnce(&mut Editor, &mut ViewContext<Editor>) -> S,
144 ) -> Option<S> {
145 self.active_editor
146 .clone()
147 .and_then(|ae| ae.upgrade(cx))
148 .map(|ae| ae.update(cx, update))
149 }
150
151 fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut MutableAppContext) {
152 self.state.mode = mode;
153 self.state.operator_stack.clear();
154
155 // Sync editor settings like clip mode
156 self.sync_vim_settings(cx);
157
158 if leave_selections {
159 return;
160 }
161
162 // Adjust selections
163 for editor in self.editors.values() {
164 if let Some(editor) = editor.upgrade(cx) {
165 editor.update(cx, |editor, cx| {
166 editor.change_selections(None, cx, |s| {
167 s.move_with(|map, selection| {
168 if self.state.empty_selections_only() {
169 let new_head = map.clip_point(selection.head(), Bias::Left);
170 selection.collapse_to(new_head, selection.goal)
171 } else {
172 selection.set_head(
173 map.clip_point(selection.head(), Bias::Left),
174 selection.goal,
175 );
176 }
177 });
178 })
179 })
180 }
181 }
182 }
183
184 fn push_operator(&mut self, operator: Operator, cx: &mut MutableAppContext) {
185 self.state.operator_stack.push(operator);
186 self.sync_vim_settings(cx);
187 }
188
189 fn push_number(&mut self, Number(number): &Number, cx: &mut MutableAppContext) {
190 if let Some(Operator::Number(current_number)) = self.active_operator() {
191 self.pop_operator(cx);
192 self.push_operator(Operator::Number(current_number * 10 + *number as usize), cx);
193 } else {
194 self.push_operator(Operator::Number(*number as usize), cx);
195 }
196 }
197
198 fn pop_operator(&mut self, cx: &mut MutableAppContext) -> Operator {
199 let popped_operator = self.state.operator_stack.pop()
200 .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
201 self.sync_vim_settings(cx);
202 popped_operator
203 }
204
205 fn pop_number_operator(&mut self, cx: &mut MutableAppContext) -> usize {
206 let mut times = 1;
207 if let Some(Operator::Number(number)) = self.active_operator() {
208 times = number;
209 self.pop_operator(cx);
210 }
211 times
212 }
213
214 fn clear_operator(&mut self, cx: &mut MutableAppContext) {
215 self.state.operator_stack.clear();
216 self.sync_vim_settings(cx);
217 }
218
219 fn active_operator(&self) -> Option<Operator> {
220 self.state.operator_stack.last().copied()
221 }
222
223 fn key_pressed(keystroke: &Keystroke, cx: &mut ViewContext<Workspace>) {
224 match Vim::read(cx).active_operator() {
225 Some(Operator::FindForward { before }) => {
226 if let Some(character) = keystroke.key.chars().next() {
227 motion::motion(Motion::FindForward { before, character }, cx)
228 }
229 }
230 Some(Operator::FindBackward { after }) => {
231 if let Some(character) = keystroke.key.chars().next() {
232 motion::motion(Motion::FindBackward { after, character }, cx)
233 }
234 }
235 Some(Operator::Replace) => match Vim::read(cx).state.mode {
236 Mode::Normal => normal_replace(&keystroke.key, cx),
237 Mode::Visual { line } => visual_replace(&keystroke.key, line, cx),
238 _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
239 },
240 _ => cx.propagate_action(),
241 }
242 }
243
244 fn set_enabled(&mut self, enabled: bool, cx: &mut MutableAppContext) {
245 if self.enabled != enabled {
246 self.enabled = enabled;
247 self.state = Default::default();
248 if enabled {
249 self.switch_mode(Mode::Normal, false, cx);
250 }
251 self.sync_vim_settings(cx);
252 }
253 }
254
255 fn sync_vim_settings(&self, cx: &mut MutableAppContext) {
256 let state = &self.state;
257 let cursor_shape = state.cursor_shape();
258
259 cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
260 if self.enabled {
261 filter.filtered_namespaces.remove("vim");
262 } else {
263 filter.filtered_namespaces.insert("vim");
264 }
265 });
266
267 for editor in self.editors.values() {
268 if let Some(editor) = editor.upgrade(cx) {
269 editor.update(cx, |editor, cx| {
270 if self.enabled && editor.mode() == EditorMode::Full {
271 editor.set_cursor_shape(cursor_shape, cx);
272 editor.set_clip_at_line_ends(state.clip_at_line_end(), cx);
273 editor.set_input_enabled(!state.vim_controlled());
274 editor.selections.line_mode =
275 matches!(state.mode, Mode::Visual { line: true });
276 let context_layer = state.keymap_context_layer();
277 editor.set_keymap_context_layer::<Self>(context_layer);
278 } else {
279 editor.set_cursor_shape(CursorShape::Bar, cx);
280 editor.set_clip_at_line_ends(false, cx);
281 editor.set_input_enabled(true);
282 editor.selections.line_mode = false;
283 editor.remove_keymap_context_layer::<Self>();
284 }
285 });
286 }
287 }
288 }
289}