vim.rs

  1#[cfg(test)]
  2mod test;
  3
  4mod editor_events;
  5mod insert;
  6mod mode_indicator;
  7mod motion;
  8mod normal;
  9mod object;
 10mod state;
 11mod utils;
 12mod visual;
 13
 14use anyhow::Result;
 15use collections::{CommandPaletteFilter, HashMap};
 16use editor::{movement, Editor, EditorMode, Event};
 17use gpui::{
 18    actions, impl_actions, keymap_matcher::KeymapContext, keymap_matcher::MatchResult, AppContext,
 19    Subscription, ViewContext, ViewHandle, WeakViewHandle, WindowContext,
 20};
 21use language::{CursorShape, Selection, SelectionGoal};
 22pub use mode_indicator::ModeIndicator;
 23use motion::Motion;
 24use normal::normal_replace;
 25use serde::Deserialize;
 26use settings::{Setting, SettingsStore};
 27use state::{EditorState, Mode, Operator, WorkspaceState};
 28use std::sync::Arc;
 29use visual::{visual_block_motion, visual_replace};
 30use workspace::{self, Workspace};
 31
 32struct VimModeSetting(bool);
 33
 34#[derive(Clone, Deserialize, PartialEq)]
 35pub struct SwitchMode(pub Mode);
 36
 37#[derive(Clone, Deserialize, PartialEq)]
 38pub struct PushOperator(pub Operator);
 39
 40#[derive(Clone, Deserialize, PartialEq)]
 41struct Number(u8);
 42
 43actions!(vim, [Tab, Enter]);
 44impl_actions!(vim, [Number, SwitchMode, PushOperator]);
 45
 46#[derive(Copy, Clone, Debug)]
 47enum VimEvent {
 48    ModeChanged { mode: Mode },
 49}
 50
 51pub fn init(cx: &mut AppContext) {
 52    settings::register::<VimModeSetting>(cx);
 53
 54    editor_events::init(cx);
 55    normal::init(cx);
 56    visual::init(cx);
 57    insert::init(cx);
 58    object::init(cx);
 59    motion::init(cx);
 60
 61    // Vim Actions
 62    cx.add_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {
 63        Vim::update(cx, |vim, cx| vim.switch_mode(mode, false, cx))
 64    });
 65    cx.add_action(
 66        |_: &mut Workspace, &PushOperator(operator): &PushOperator, cx| {
 67            Vim::update(cx, |vim, cx| vim.push_operator(operator, cx))
 68        },
 69    );
 70    cx.add_action(|_: &mut Workspace, n: &Number, cx: _| {
 71        Vim::update(cx, |vim, cx| vim.push_number(n, cx));
 72    });
 73
 74    cx.add_action(|_: &mut Workspace, _: &Tab, cx| {
 75        Vim::active_editor_input_ignored(" ".into(), cx)
 76    });
 77
 78    cx.add_action(|_: &mut Workspace, _: &Enter, cx| {
 79        Vim::active_editor_input_ignored("\n".into(), cx)
 80    });
 81
 82    // Any time settings change, update vim mode to match. The Vim struct
 83    // will be initialized as disabled by default, so we filter its commands
 84    // out when starting up.
 85    cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
 86        filter.filtered_namespaces.insert("vim");
 87    });
 88    cx.update_default_global(|vim: &mut Vim, cx: &mut AppContext| {
 89        vim.set_enabled(settings::get::<VimModeSetting>(cx).0, cx)
 90    });
 91    cx.observe_global::<SettingsStore, _>(|cx| {
 92        cx.update_default_global(|vim: &mut Vim, cx: &mut AppContext| {
 93            vim.set_enabled(settings::get::<VimModeSetting>(cx).0, cx)
 94        });
 95    })
 96    .detach();
 97}
 98
 99pub fn observe_keystrokes(cx: &mut WindowContext) {
100    cx.observe_keystrokes(|_keystroke, result, handled_by, cx| {
101        if result == &MatchResult::Pending {
102            return true;
103        }
104        if let Some(handled_by) = handled_by {
105            // Keystroke is handled by the vim system, so continue forward
106            if handled_by.namespace() == "vim" {
107                return true;
108            }
109        }
110
111        Vim::update(cx, |vim, cx| match vim.active_operator() {
112            Some(
113                Operator::FindForward { .. } | Operator::FindBackward { .. } | Operator::Replace,
114            ) => {}
115            Some(_) => {
116                vim.clear_operator(cx);
117            }
118            _ => {}
119        });
120        true
121    })
122    .detach()
123}
124
125#[derive(Default)]
126pub struct Vim {
127    active_editor: Option<WeakViewHandle<Editor>>,
128    editor_subscription: Option<Subscription>,
129    enabled: bool,
130    editor_states: HashMap<usize, EditorState>,
131    workspace_state: WorkspaceState,
132    default_state: EditorState,
133}
134
135impl Vim {
136    fn read(cx: &mut AppContext) -> &Self {
137        cx.default_global()
138    }
139
140    fn update<F, S>(cx: &mut WindowContext, update: F) -> S
141    where
142        F: FnOnce(&mut Self, &mut WindowContext) -> S,
143    {
144        cx.update_default_global(update)
145    }
146
147    fn set_active_editor(&mut self, editor: ViewHandle<Editor>, cx: &mut WindowContext) {
148        self.active_editor = Some(editor.clone().downgrade());
149        self.editor_subscription = Some(cx.subscribe(&editor, |editor, event, cx| match event {
150            Event::SelectionsChanged { local: true } => {
151                let editor = editor.read(cx);
152                if editor.leader_replica_id().is_none() {
153                    let newest = editor.selections.newest::<usize>(cx);
154                    local_selections_changed(newest, cx);
155                }
156            }
157            Event::InputIgnored { text } => {
158                Vim::active_editor_input_ignored(text.clone(), cx);
159            }
160            _ => {}
161        }));
162
163        if self.enabled {
164            let editor = editor.read(cx);
165            let editor_mode = editor.mode();
166            let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
167
168            if editor_mode == EditorMode::Full
169                && !newest_selection_empty
170                && self.state().mode == Mode::Normal
171            {
172                self.switch_mode(Mode::Visual, true, cx);
173            }
174        }
175
176        self.sync_vim_settings(cx);
177    }
178
179    fn update_active_editor<S>(
180        &self,
181        cx: &mut WindowContext,
182        update: impl FnOnce(&mut Editor, &mut ViewContext<Editor>) -> S,
183    ) -> Option<S> {
184        let editor = self.active_editor.clone()?.upgrade(cx)?;
185        Some(editor.update(cx, update))
186    }
187
188    fn switch_mode(&mut self, mode: Mode, leave_selections: bool, cx: &mut WindowContext) {
189        let state = self.state();
190        let last_mode = state.mode;
191        let prior_mode = state.last_mode;
192        self.update_state(|state| {
193            state.last_mode = last_mode;
194            state.mode = mode;
195            state.operator_stack.clear();
196        });
197
198        cx.emit_global(VimEvent::ModeChanged { mode });
199
200        // Sync editor settings like clip mode
201        self.sync_vim_settings(cx);
202
203        if leave_selections {
204            return;
205        }
206
207        // Adjust selections
208        self.update_active_editor(cx, |editor, cx| {
209            if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
210            {
211                visual_block_motion(true, editor, cx, |_, point, goal| Some((point, goal)))
212            }
213
214            editor.change_selections(None, cx, |s| {
215                // we cheat with visual block mode and use multiple cursors.
216                // the cost of this cheat is we need to convert back to a single
217                // cursor whenever vim would.
218                if last_mode == Mode::VisualBlock
219                    && (mode != Mode::VisualBlock && mode != Mode::Insert)
220                {
221                    let tail = s.oldest_anchor().tail();
222                    let head = s.newest_anchor().head();
223                    s.select_anchor_ranges(vec![tail..head]);
224                } else if last_mode == Mode::Insert
225                    && prior_mode == Mode::VisualBlock
226                    && mode != Mode::VisualBlock
227                {
228                    let pos = s.first_anchor().head();
229                    s.select_anchor_ranges(vec![pos..pos])
230                }
231
232                s.move_with(|map, selection| {
233                    if last_mode.is_visual() && !mode.is_visual() {
234                        let mut point = selection.head();
235                        if !selection.reversed && !selection.is_empty() {
236                            point = movement::left(map, selection.head());
237                        }
238                        selection.collapse_to(point, selection.goal)
239                    } else if !last_mode.is_visual() && mode.is_visual() {
240                        if selection.is_empty() {
241                            selection.end = movement::right(map, selection.start);
242                        }
243                    }
244                });
245            })
246        });
247    }
248
249    fn push_operator(&mut self, operator: Operator, cx: &mut WindowContext) {
250        self.update_state(|state| state.operator_stack.push(operator));
251        self.sync_vim_settings(cx);
252    }
253
254    fn push_number(&mut self, Number(number): &Number, cx: &mut WindowContext) {
255        if let Some(Operator::Number(current_number)) = self.active_operator() {
256            self.pop_operator(cx);
257            self.push_operator(Operator::Number(current_number * 10 + *number as usize), cx);
258        } else {
259            self.push_operator(Operator::Number(*number as usize), cx);
260        }
261    }
262
263    fn maybe_pop_operator(&mut self) -> Option<Operator> {
264        self.update_state(|state| state.operator_stack.pop())
265    }
266
267    fn pop_operator(&mut self, cx: &mut WindowContext) -> Operator {
268        let popped_operator = self.update_state( |state| state.operator_stack.pop()
269        )            .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
270        self.sync_vim_settings(cx);
271        popped_operator
272    }
273
274    fn pop_number_operator(&mut self, cx: &mut WindowContext) -> Option<usize> {
275        if let Some(Operator::Number(number)) = self.active_operator() {
276            self.pop_operator(cx);
277            return Some(number);
278        }
279        None
280    }
281
282    fn clear_operator(&mut self, cx: &mut WindowContext) {
283        self.update_state(|state| state.operator_stack.clear());
284        self.sync_vim_settings(cx);
285    }
286
287    fn active_operator(&self) -> Option<Operator> {
288        self.state().operator_stack.last().copied()
289    }
290
291    fn active_editor_input_ignored(text: Arc<str>, cx: &mut WindowContext) {
292        if text.is_empty() {
293            return;
294        }
295
296        match Vim::read(cx).active_operator() {
297            Some(Operator::FindForward { before }) => {
298                let find = Motion::FindForward {
299                    before,
300                    char: text.chars().next().unwrap(),
301                };
302                Vim::update(cx, |vim, _| {
303                    vim.workspace_state.last_find = Some(find.clone())
304                });
305                motion::motion(find, cx)
306            }
307            Some(Operator::FindBackward { after }) => {
308                let find = Motion::FindBackward {
309                    after,
310                    char: text.chars().next().unwrap(),
311                };
312                Vim::update(cx, |vim, _| {
313                    vim.workspace_state.last_find = Some(find.clone())
314                });
315                motion::motion(find, cx)
316            }
317            Some(Operator::Replace) => match Vim::read(cx).state().mode {
318                Mode::Normal => normal_replace(text, cx),
319                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => visual_replace(text, cx),
320                _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
321            },
322            _ => {}
323        }
324    }
325
326    fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
327        if self.enabled != enabled {
328            self.enabled = enabled;
329
330            cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
331                if self.enabled {
332                    filter.filtered_namespaces.remove("vim");
333                } else {
334                    filter.filtered_namespaces.insert("vim");
335                }
336            });
337
338            cx.update_active_window(|cx| {
339                if self.enabled {
340                    let active_editor = cx
341                        .root_view()
342                        .downcast_ref::<Workspace>()
343                        .and_then(|workspace| workspace.read(cx).active_item(cx))
344                        .and_then(|item| item.downcast::<Editor>());
345                    if let Some(active_editor) = active_editor {
346                        self.set_active_editor(active_editor, cx);
347                    }
348                    self.switch_mode(Mode::Normal, false, cx);
349                }
350                self.sync_vim_settings(cx);
351            });
352        }
353    }
354
355    pub fn state(&self) -> &EditorState {
356        if let Some(active_editor) = self.active_editor.as_ref() {
357            if let Some(state) = self.editor_states.get(&active_editor.id()) {
358                return state;
359            }
360        }
361
362        &self.default_state
363    }
364
365    pub fn update_state<T>(&mut self, func: impl FnOnce(&mut EditorState) -> T) -> T {
366        let mut state = self.state().clone();
367        let ret = func(&mut state);
368
369        if let Some(active_editor) = self.active_editor.as_ref() {
370            self.editor_states.insert(active_editor.id(), state);
371        }
372
373        ret
374    }
375
376    fn sync_vim_settings(&self, cx: &mut WindowContext) {
377        let state = self.state();
378        let cursor_shape = state.cursor_shape();
379
380        self.update_active_editor(cx, |editor, cx| {
381            if self.enabled && editor.mode() == EditorMode::Full {
382                editor.set_cursor_shape(cursor_shape, cx);
383                editor.set_clip_at_line_ends(state.clip_at_line_ends(), cx);
384                editor.set_collapse_matches(true);
385                editor.set_input_enabled(!state.vim_controlled());
386                editor.set_autoindent(state.should_autoindent());
387                editor.selections.line_mode = matches!(state.mode, Mode::VisualLine);
388                let context_layer = state.keymap_context_layer();
389                editor.set_keymap_context_layer::<Self>(context_layer, cx);
390            } else {
391                // Note: set_collapse_matches is not in unhook_vim_settings, as that method is called on blur,
392                // but we need collapse_matches to persist when the search bar is focused.
393                editor.set_collapse_matches(false);
394                self.unhook_vim_settings(editor, cx);
395            }
396        });
397    }
398
399    fn unhook_vim_settings(&self, editor: &mut Editor, cx: &mut ViewContext<Editor>) {
400        editor.set_cursor_shape(CursorShape::Bar, cx);
401        editor.set_clip_at_line_ends(false, cx);
402        editor.set_input_enabled(true);
403        editor.set_autoindent(true);
404        editor.selections.line_mode = false;
405
406        // we set the VimEnabled context on all editors so that we
407        // can distinguish between vim mode and non-vim mode in the BufferSearchBar.
408        // This is a bit of a hack, but currently the search crate does not depend on vim,
409        // and it seems nice to keep it that way.
410        if self.enabled {
411            let mut context = KeymapContext::default();
412            context.add_identifier("VimEnabled");
413            editor.set_keymap_context_layer::<Self>(context, cx)
414        } else {
415            editor.remove_keymap_context_layer::<Self>(cx);
416        }
417    }
418}
419
420impl Setting for VimModeSetting {
421    const KEY: Option<&'static str> = Some("vim_mode");
422
423    type FileContent = Option<bool>;
424
425    fn load(
426        default_value: &Self::FileContent,
427        user_values: &[&Self::FileContent],
428        _: &AppContext,
429    ) -> Result<Self> {
430        Ok(Self(user_values.iter().rev().find_map(|v| **v).unwrap_or(
431            default_value.ok_or_else(Self::missing_default)?,
432        )))
433    }
434}
435
436fn local_selections_changed(newest: Selection<usize>, cx: &mut WindowContext) {
437    Vim::update(cx, |vim, cx| {
438        if vim.enabled && vim.state().mode == Mode::Normal && !newest.is_empty() {
439            if matches!(newest.goal, SelectionGoal::ColumnRange { .. }) {
440                vim.switch_mode(Mode::VisualBlock, false, cx);
441            } else {
442                vim.switch_mode(Mode::Visual, false, cx)
443            }
444        }
445    })
446}