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};
16use gpui::{impl_actions, MutableAppContext, Subscription, ViewContext, WeakViewHandle};
17use language::CursorShape;
18use serde::Deserialize;
19
20use settings::Settings;
21use state::{Mode, Operator, VimState};
22use workspace::{self, Workspace};
23
24#[derive(Clone, Deserialize, PartialEq)]
25pub struct SwitchMode(pub Mode);
26
27#[derive(Clone, Deserialize, PartialEq)]
28pub struct PushOperator(pub Operator);
29
30#[derive(Clone, Deserialize, PartialEq)]
31struct Number(u8);
32
33impl_actions!(vim, [Number, SwitchMode, PushOperator]);
34
35pub fn init(cx: &mut MutableAppContext) {
36 editor_events::init(cx);
37 normal::init(cx);
38 visual::init(cx);
39 insert::init(cx);
40 object::init(cx);
41 motion::init(cx);
42
43 // Vim Actions
44 cx.add_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {
45 Vim::update(cx, |vim, cx| vim.switch_mode(mode, false, cx))
46 });
47 cx.add_action(
48 |_: &mut Workspace, &PushOperator(operator): &PushOperator, cx| {
49 Vim::update(cx, |vim, cx| vim.push_operator(operator, cx))
50 },
51 );
52 cx.add_action(|_: &mut Workspace, n: &Number, cx: _| {
53 Vim::update(cx, |vim, cx| vim.push_number(n, cx));
54 });
55
56 // Editor Actions
57 cx.add_action(|_: &mut Editor, _: &Cancel, cx| {
58 // If we are in a non normal mode or have an active operator, swap to normal mode
59 // Otherwise forward cancel on to the editor
60 let vim = Vim::read(cx);
61 if vim.state.mode != Mode::Normal || vim.active_operator().is_some() {
62 MutableAppContext::defer(cx, |cx| {
63 Vim::update(cx, |state, cx| {
64 state.switch_mode(Mode::Normal, false, cx);
65 });
66 });
67 } else {
68 cx.propagate_action();
69 }
70 });
71
72 // Sync initial settings with the rest of the app
73 Vim::update(cx, |state, cx| state.sync_vim_settings(cx));
74
75 // Any time settings change, update vim mode to match
76 cx.observe_global::<Settings, _>(|cx| {
77 Vim::update(cx, |state, cx| {
78 state.set_enabled(cx.global::<Settings>().vim_mode, cx)
79 })
80 })
81 .detach();
82}
83
84// Any keystrokes not mapped to vim should clear the active operator
85pub fn observe_keypresses(window_id: usize, cx: &mut MutableAppContext) {
86 cx.observe_keystrokes(window_id, |_keystroke, _result, handled_by, cx| {
87 if let Some(handled_by) = handled_by {
88 if handled_by.namespace() == "vim" {
89 return true;
90 }
91 }
92
93 Vim::update(cx, |vim, cx| {
94 if vim.active_operator().is_some() {
95 vim.clear_operator(cx);
96 }
97 });
98 true
99 })
100 .detach()
101}
102
103#[derive(Default)]
104pub struct Vim {
105 editors: HashMap<usize, WeakViewHandle<Editor>>,
106 active_editor: Option<WeakViewHandle<Editor>>,
107 selection_subscription: Option<Subscription>,
108
109 enabled: bool,
110 state: VimState,
111}
112
113impl Vim {
114 fn read(cx: &mut MutableAppContext) -> &Self {
115 cx.default_global()
116 }
117
118 fn update<F, S>(cx: &mut MutableAppContext, update: F) -> S
119 where
120 F: FnOnce(&mut Self, &mut MutableAppContext) -> S,
121 {
122 cx.update_default_global(update)
123 }
124
125 fn update_active_editor<S>(
126 &self,
127 cx: &mut MutableAppContext,
128 update: impl FnOnce(&mut Editor, &mut ViewContext<Editor>) -> S,
129 ) -> Option<S> {
130 self.active_editor
131 .clone()
132 .and_then(|ae| ae.upgrade(cx))
133 .map(|ae| ae.update(cx, update))
134 }
135
136 fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut MutableAppContext) {
137 self.state.mode = mode;
138 self.state.operator_stack.clear();
139
140 // Sync editor settings like clip mode
141 self.sync_vim_settings(cx);
142
143 if leave_selections {
144 return;
145 }
146
147 // Adjust selections
148 for editor in self.editors.values() {
149 if let Some(editor) = editor.upgrade(cx) {
150 editor.update(cx, |editor, cx| {
151 editor.change_selections(None, cx, |s| {
152 s.move_with(|map, selection| {
153 if self.state.empty_selections_only() {
154 let new_head = map.clip_point(selection.head(), Bias::Left);
155 selection.collapse_to(new_head, selection.goal)
156 } else {
157 selection.set_head(
158 map.clip_point(selection.head(), Bias::Left),
159 selection.goal,
160 );
161 }
162 });
163 })
164 })
165 }
166 }
167 }
168
169 fn push_operator(&mut self, operator: Operator, cx: &mut MutableAppContext) {
170 self.state.operator_stack.push(operator);
171 self.sync_vim_settings(cx);
172 }
173
174 fn push_number(&mut self, Number(number): &Number, cx: &mut MutableAppContext) {
175 if let Some(Operator::Number(current_number)) = self.active_operator() {
176 self.pop_operator(cx);
177 self.push_operator(Operator::Number(current_number * 10 + *number as usize), cx);
178 } else {
179 self.push_operator(Operator::Number(*number as usize), cx);
180 }
181 }
182
183 fn pop_operator(&mut self, cx: &mut MutableAppContext) -> Operator {
184 let popped_operator = self.state.operator_stack.pop()
185 .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
186 self.sync_vim_settings(cx);
187 popped_operator
188 }
189
190 fn pop_number_operator(&mut self, cx: &mut MutableAppContext) -> usize {
191 let mut times = 1;
192 if let Some(Operator::Number(number)) = self.active_operator() {
193 times = number;
194 self.pop_operator(cx);
195 }
196 times
197 }
198
199 fn clear_operator(&mut self, cx: &mut MutableAppContext) {
200 self.state.operator_stack.clear();
201 self.sync_vim_settings(cx);
202 }
203
204 fn active_operator(&self) -> Option<Operator> {
205 self.state.operator_stack.last().copied()
206 }
207
208 fn set_enabled(&mut self, enabled: bool, cx: &mut MutableAppContext) {
209 if self.enabled != enabled {
210 self.enabled = enabled;
211 self.state = Default::default();
212 if enabled {
213 self.switch_mode(Mode::Normal, false, cx);
214 }
215 self.sync_vim_settings(cx);
216 }
217 }
218
219 fn sync_vim_settings(&self, cx: &mut MutableAppContext) {
220 let state = &self.state;
221 let cursor_shape = state.cursor_shape();
222
223 cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
224 if self.enabled {
225 filter.filtered_namespaces.remove("vim");
226 } else {
227 filter.filtered_namespaces.insert("vim");
228 }
229 });
230
231 for editor in self.editors.values() {
232 if let Some(editor) = editor.upgrade(cx) {
233 editor.update(cx, |editor, cx| {
234 if self.enabled {
235 editor.set_cursor_shape(cursor_shape, cx);
236 editor.set_clip_at_line_ends(state.clip_at_line_end(), cx);
237 editor.set_input_enabled(!state.vim_controlled());
238 editor.selections.line_mode =
239 matches!(state.mode, Mode::Visual { line: true });
240 let context_layer = state.keymap_context_layer();
241 editor.set_keymap_context_layer::<Self>(context_layer);
242 } else {
243 editor.set_cursor_shape(CursorShape::Bar, cx);
244 editor.set_clip_at_line_ends(false, cx);
245 editor.set_input_enabled(true);
246 editor.selections.line_mode = false;
247 editor.remove_keymap_context_layer::<Self>();
248 }
249 });
250 }
251 }
252 }
253}