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 { before, text };
299                Vim::update(cx, |vim, _| {
300                    vim.workspace_state.last_find = Some(find.clone())
301                });
302                motion::motion(find, cx)
303            }
304            Some(Operator::FindBackward { after }) => {
305                let find = Motion::FindBackward { after, text };
306                Vim::update(cx, |vim, _| {
307                    vim.workspace_state.last_find = Some(find.clone())
308                });
309                motion::motion(find, cx)
310            }
311            Some(Operator::Replace) => match Vim::read(cx).state().mode {
312                Mode::Normal => normal_replace(text, cx),
313                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => visual_replace(text, cx),
314                _ => Vim::update(cx, |vim, cx| vim.clear_operator(cx)),
315            },
316            _ => {}
317        }
318    }
319
320    fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
321        if self.enabled != enabled {
322            self.enabled = enabled;
323
324            cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
325                if self.enabled {
326                    filter.filtered_namespaces.remove("vim");
327                } else {
328                    filter.filtered_namespaces.insert("vim");
329                }
330            });
331
332            cx.update_active_window(|cx| {
333                if self.enabled {
334                    let active_editor = cx
335                        .root_view()
336                        .downcast_ref::<Workspace>()
337                        .and_then(|workspace| workspace.read(cx).active_item(cx))
338                        .and_then(|item| item.downcast::<Editor>());
339                    if let Some(active_editor) = active_editor {
340                        self.set_active_editor(active_editor, cx);
341                    }
342                    self.switch_mode(Mode::Normal, false, cx);
343                }
344                self.sync_vim_settings(cx);
345            });
346        }
347    }
348
349    pub fn state(&self) -> &EditorState {
350        if let Some(active_editor) = self.active_editor.as_ref() {
351            if let Some(state) = self.editor_states.get(&active_editor.id()) {
352                return state;
353            }
354        }
355
356        &self.default_state
357    }
358
359    pub fn update_state<T>(&mut self, func: impl FnOnce(&mut EditorState) -> T) -> T {
360        let mut state = self.state().clone();
361        let ret = func(&mut state);
362
363        if let Some(active_editor) = self.active_editor.as_ref() {
364            self.editor_states.insert(active_editor.id(), state);
365        }
366
367        ret
368    }
369
370    fn sync_vim_settings(&self, cx: &mut WindowContext) {
371        let state = self.state();
372        let cursor_shape = state.cursor_shape();
373
374        self.update_active_editor(cx, |editor, cx| {
375            if self.enabled && editor.mode() == EditorMode::Full {
376                editor.set_cursor_shape(cursor_shape, cx);
377                editor.set_clip_at_line_ends(state.clip_at_line_ends(), cx);
378                editor.set_collapse_matches(true);
379                editor.set_input_enabled(!state.vim_controlled());
380                editor.set_autoindent(state.should_autoindent());
381                editor.selections.line_mode = matches!(state.mode, Mode::VisualLine);
382                let context_layer = state.keymap_context_layer();
383                editor.set_keymap_context_layer::<Self>(context_layer, cx);
384            } else {
385                // Note: set_collapse_matches is not in unhook_vim_settings, as that method is called on blur,
386                // but we need collapse_matches to persist when the search bar is focused.
387                editor.set_collapse_matches(false);
388                self.unhook_vim_settings(editor, cx);
389            }
390        });
391    }
392
393    fn unhook_vim_settings(&self, editor: &mut Editor, cx: &mut ViewContext<Editor>) {
394        editor.set_cursor_shape(CursorShape::Bar, cx);
395        editor.set_clip_at_line_ends(false, cx);
396        editor.set_input_enabled(true);
397        editor.set_autoindent(true);
398        editor.selections.line_mode = false;
399
400        // we set the VimEnabled context on all editors so that we
401        // can distinguish between vim mode and non-vim mode in the BufferSearchBar.
402        // This is a bit of a hack, but currently the search crate does not depend on vim,
403        // and it seems nice to keep it that way.
404        if self.enabled {
405            let mut context = KeymapContext::default();
406            context.add_identifier("VimEnabled");
407            editor.set_keymap_context_layer::<Self>(context, cx)
408        } else {
409            editor.remove_keymap_context_layer::<Self>(cx);
410        }
411    }
412}
413
414impl Setting for VimModeSetting {
415    const KEY: Option<&'static str> = Some("vim_mode");
416
417    type FileContent = Option<bool>;
418
419    fn load(
420        default_value: &Self::FileContent,
421        user_values: &[&Self::FileContent],
422        _: &AppContext,
423    ) -> Result<Self> {
424        Ok(Self(user_values.iter().rev().find_map(|v| **v).unwrap_or(
425            default_value.ok_or_else(Self::missing_default)?,
426        )))
427    }
428}
429
430fn local_selections_changed(newest: Selection<usize>, cx: &mut WindowContext) {
431    Vim::update(cx, |vim, cx| {
432        if vim.enabled && vim.state().mode == Mode::Normal && !newest.is_empty() {
433            if matches!(newest.goal, SelectionGoal::ColumnRange { .. }) {
434                vim.switch_mode(Mode::VisualBlock, false, cx);
435            } else {
436                vim.switch_mode(Mode::Visual, false, cx)
437            }
438        }
439    })
440}