Skip to repository content

tenant.openagents/omega

No repository description is available.

OpenAgents Git authority 2026-07-28T03:29:05.569Z Public web read
NIP-34 coordinate30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omega
MaintainersHidden in public view
References2 branches · 1 tag
Read-only clonegit clone https://openagents.com/git/tenant.openagents/omega.git
Browse files

vim.rs

2398 lines · 90.7 KB · rust
1//! Vim support for Omega.
2
3#[cfg(test)]
4mod test;
5
6mod change_list;
7mod command;
8mod digraph;
9mod helix;
10mod indent;
11mod insert;
12mod mode_indicator;
13mod motion;
14mod normal;
15mod object;
16mod replace;
17mod rewrap;
18mod state;
19mod surrounds;
20mod visual;
21
22use crate::normal::paste::Paste as VimPaste;
23use collections::HashMap;
24use editor::{
25    Anchor, Bias, Editor, EditorEvent, EditorSettings, MultiBufferOffset, NavigationOverlayKey,
26    NavigationTargetOverlay, SelectionEffects,
27    actions::Paste,
28    display_map::ToDisplayPoint,
29    movement::{self, FindRange},
30};
31use gpui::{
32    Action, App, AppContext, Axis, Context, Entity, EventEmitter, Focusable, KeyContext,
33    KeystrokeEvent, Render, Subscription, Task, WeakEntity, Window, actions,
34};
35use insert::{NormalBefore, TemporaryNormal};
36use language::{CursorShape, Point, Selection, SelectionGoal, TransactionId};
37pub use mode_indicator::ModeIndicator;
38use motion::Motion;
39use multi_buffer::ToPoint as _;
40use normal::search::SearchSubmit;
41use object::Object;
42use schemars::JsonSchema;
43use search::BufferSearchBar;
44use serde::Deserialize;
45use settings::RegisterSetting;
46pub use settings::{
47    ModeContent, Settings, SettingsStore, UseSystemClipboard, update_settings_file,
48};
49use state::{
50    HelixJumpBehaviour, HelixJumpLabel, Mode, Operator, RecordedSelection, SearchState, VimGlobals,
51};
52use std::{mem, ops::Range, sync::Arc};
53use surrounds::SurroundsType;
54use theme_settings::ThemeSettings;
55use ui::{IntoElement, SharedString, px};
56use vim_mode_setting::HelixModeSetting;
57use vim_mode_setting::VimModeSetting;
58use workspace::{self, Pane, Workspace};
59
60use crate::{
61    normal::{GoToPreviousTab, GoToTab},
62    state::ReplayableAction,
63};
64
65enum HelixJumpNavigationOverlay {}
66
67pub(crate) const HELIX_JUMP_OVERLAY_KEY: NavigationOverlayKey =
68    NavigationOverlayKey::unique::<HelixJumpNavigationOverlay>();
69
70/// Number is used to manage vim's count. Pushing a digit
71/// multiplies the current value by 10 and adds the digit.
72#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
73#[action(namespace = vim)]
74struct Number(usize);
75
76#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
77#[action(namespace = vim)]
78struct SelectRegister(String);
79
80#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
81#[action(namespace = vim)]
82#[serde(deny_unknown_fields)]
83struct PushObject {
84    around: bool,
85}
86
87#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
88#[action(namespace = vim)]
89#[serde(deny_unknown_fields)]
90struct PushFindForward {
91    before: bool,
92    multiline: bool,
93}
94
95#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
96#[action(namespace = vim)]
97#[serde(deny_unknown_fields)]
98struct PushFindBackward {
99    after: bool,
100    multiline: bool,
101}
102
103#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
104#[action(namespace = vim)]
105#[serde(deny_unknown_fields)]
106/// Selects the next object.
107struct PushHelixNext {
108    around: bool,
109}
110
111#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
112#[action(namespace = vim)]
113#[serde(deny_unknown_fields)]
114/// Selects the previous object.
115struct PushHelixPrevious {
116    around: bool,
117}
118
119#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
120#[action(namespace = vim)]
121#[serde(deny_unknown_fields)]
122struct PushSneak {
123    first_char: Option<char>,
124}
125
126#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
127#[action(namespace = vim)]
128#[serde(deny_unknown_fields)]
129struct PushSneakBackward {
130    first_char: Option<char>,
131}
132
133#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
134#[action(namespace = vim)]
135#[serde(deny_unknown_fields)]
136struct PushAddSurrounds;
137
138#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
139#[action(namespace = vim)]
140#[serde(deny_unknown_fields)]
141struct PushChangeSurrounds {
142    target: Option<Object>,
143}
144
145#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
146#[action(namespace = vim)]
147#[serde(deny_unknown_fields)]
148struct PushJump {
149    line: bool,
150}
151
152#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
153#[action(namespace = vim)]
154#[serde(deny_unknown_fields)]
155struct PushDigraph {
156    first_char: Option<char>,
157}
158
159#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
160#[action(namespace = vim)]
161#[serde(deny_unknown_fields)]
162struct PushLiteral {
163    prefix: Option<String>,
164}
165
166actions!(
167    vim,
168    [
169        /// Switches to normal mode.
170        SwitchToNormalMode,
171        /// Switches to insert mode.
172        SwitchToInsertMode,
173        /// Switches to replace mode.
174        SwitchToReplaceMode,
175        /// Switches to visual mode.
176        SwitchToVisualMode,
177        /// Switches to visual line mode.
178        SwitchToVisualLineMode,
179        /// Switches to visual block mode.
180        SwitchToVisualBlockMode,
181        /// Switches to Helix-style normal mode.
182        SwitchToHelixNormalMode,
183        /// Clears any pending operators.
184        ClearOperators,
185        /// Clears the exchange register.
186        ClearExchange,
187        /// Inserts a tab character.
188        Tab,
189        /// Inserts a newline.
190        Enter,
191        /// Selects inner text object.
192        InnerObject,
193        /// Maximizes the current pane.
194        MaximizePane,
195        /// Resets all pane sizes to default.
196        ResetPaneSizes,
197        /// Resizes the pane to the right.
198        ResizePaneRight,
199        /// Resizes the pane to the left.
200        ResizePaneLeft,
201        /// Resizes the pane upward.
202        ResizePaneUp,
203        /// Resizes the pane downward.
204        ResizePaneDown,
205        /// Starts a change operation.
206        PushChange,
207        /// Starts a delete operation.
208        PushDelete,
209        /// Exchanges text regions.
210        Exchange,
211        /// Starts a yank operation.
212        PushYank,
213        /// Starts a replace operation.
214        PushReplace,
215        /// Deletes surrounding characters.
216        PushDeleteSurrounds,
217        /// Sets a mark at the current position.
218        PushMark,
219        /// Toggles the marks view.
220        ToggleMarksView,
221        /// Starts a forced motion.
222        PushForcedMotion,
223        /// Starts an indent operation.
224        PushIndent,
225        /// Starts an outdent operation.
226        PushOutdent,
227        /// Starts an auto-indent operation.
228        PushAutoIndent,
229        /// Starts a rewrap operation.
230        PushRewrap,
231        /// Starts a shell command operation.
232        PushShellCommand,
233        /// Converts to lowercase.
234        PushLowercase,
235        /// Converts to uppercase.
236        PushUppercase,
237        /// Toggles case.
238        PushOppositeCase,
239        /// Applies ROT13 encoding.
240        PushRot13,
241        /// Applies ROT47 encoding.
242        PushRot47,
243        /// Toggles the registers view.
244        ToggleRegistersView,
245        /// Selects a register.
246        PushRegister,
247        /// Starts recording to a register.
248        PushRecordRegister,
249        /// Replays a register.
250        PushReplayRegister,
251        /// Replaces with register contents.
252        PushReplaceWithRegister,
253        /// Toggles comments.
254        PushToggleComments,
255        /// Toggles block comments.
256        PushToggleBlockComments,
257        /// Selects (count) next menu item
258        MenuSelectNext,
259        /// Selects (count) previous menu item
260        MenuSelectPrevious,
261        /// Clears count or toggles project panel focus
262        ToggleProjectPanelFocus,
263        /// Starts a match operation.
264        PushHelixMatch,
265        /// Adds surrounding characters in Helix mode.
266        PushHelixSurroundAdd,
267        /// Replaces surrounding characters in Helix mode.
268        PushHelixSurroundReplace,
269        /// Deletes surrounding characters in Helix mode.
270        PushHelixSurroundDelete,
271    ]
272);
273
274// in the workspace namespace so it's not filtered out when vim is disabled.
275actions!(
276    workspace,
277    [
278        /// Toggles Vim mode on or off.
279        ToggleVimMode,
280        /// Toggles Helix mode on or off.
281        ToggleHelixMode,
282    ]
283);
284
285/// Initializes the `vim` crate.
286pub fn init(cx: &mut App) {
287    VimGlobals::register(cx);
288
289    cx.observe_new(Vim::register).detach();
290
291    cx.observe_new(|workspace: &mut Workspace, _, _| {
292        workspace.register_action(|workspace, _: &ToggleVimMode, _, cx| {
293            let fs = workspace.app_state().fs.clone();
294            let currently_enabled = VimModeSetting::get_global(cx).0;
295            update_settings_file(fs, cx, move |setting, _| {
296                setting.vim_mode = Some(!currently_enabled);
297                if let Some(helix_mode) = &mut setting.helix_mode {
298                    *helix_mode = false;
299                }
300            })
301        });
302
303        workspace.register_action(|workspace, _: &ToggleHelixMode, _, cx| {
304            let fs = workspace.app_state().fs.clone();
305            let currently_enabled = HelixModeSetting::get_global(cx).0;
306            update_settings_file(fs, cx, move |setting, _| {
307                setting.helix_mode = Some(!currently_enabled);
308                if let Some(vim_mode) = &mut setting.vim_mode {
309                    *vim_mode = false;
310                }
311            })
312        });
313
314        workspace.register_action(|_, _: &MenuSelectNext, window, cx| {
315            let count = Vim::take_count(cx).unwrap_or(1);
316
317            for _ in 0..count {
318                window.dispatch_action(menu::SelectNext.boxed_clone(), cx);
319            }
320        });
321
322        workspace.register_action(|_, _: &MenuSelectPrevious, window, cx| {
323            let count = Vim::take_count(cx).unwrap_or(1);
324
325            for _ in 0..count {
326                window.dispatch_action(menu::SelectPrevious.boxed_clone(), cx);
327            }
328        });
329
330        workspace.register_action(|_, _: &ToggleProjectPanelFocus, window, cx| {
331            if Vim::take_count(cx).is_none() {
332                window.dispatch_action(zed_actions::project_panel::ToggleFocus.boxed_clone(), cx);
333            }
334        });
335
336        workspace.register_action(|workspace, n: &Number, window, cx| {
337            let vim = workspace
338                .focused_pane(window, cx)
339                .read(cx)
340                .active_item()
341                .and_then(|item| item.act_as::<Editor>(cx))
342                .and_then(|editor| editor.read(cx).addon::<VimAddon>().cloned());
343            if let Some(vim) = vim {
344                let digit = n.0;
345                vim.entity.update(cx, |_, cx| {
346                    cx.defer_in(window, move |vim, window, cx| {
347                        vim.push_count_digit(digit, window, cx)
348                    })
349                });
350            } else {
351                let count = Vim::globals(cx).pre_count.unwrap_or(0);
352                Vim::globals(cx).pre_count = Some(
353                    count
354                        .checked_mul(10)
355                        .and_then(|c| c.checked_add(n.0))
356                        .unwrap_or(count),
357                );
358            };
359        });
360
361        workspace.register_action(|_, _: &zed_actions::vim::OpenDefaultKeymap, _, cx| {
362            cx.emit(workspace::Event::OpenBundledFile {
363                text: settings::vim_keymap(),
364                title: "Default Vim Bindings",
365                language: "JSON",
366            });
367        });
368
369        workspace.register_action(|workspace, _: &ResetPaneSizes, _, cx| {
370            workspace.reset_pane_sizes(cx);
371        });
372
373        workspace.register_action(|workspace, _: &MaximizePane, window, cx| {
374            let pane = workspace.active_pane();
375            let Some(size) = workspace.bounding_box_for_pane(pane) else {
376                return;
377            };
378
379            let theme = ThemeSettings::get_global(cx);
380            let height = theme.buffer_font_size(cx) * theme.buffer_line_height.value();
381
382            let desired_size = if let Some(count) = Vim::take_count(cx) {
383                height * count
384            } else {
385                px(10000.)
386            };
387            workspace.resize_pane(Axis::Vertical, desired_size - size.size.height, window, cx)
388        });
389
390        workspace.register_action(|workspace, _: &ResizePaneRight, window, cx| {
391            let count = Vim::take_count(cx).unwrap_or(1) as f32;
392            Vim::take_forced_motion(cx);
393            let theme = ThemeSettings::get_global(cx);
394            let font_id = window.text_system().resolve_font(&theme.buffer_font);
395            let Ok(width) = window
396                .text_system()
397                .advance(font_id, theme.buffer_font_size(cx), 'm')
398            else {
399                return;
400            };
401            workspace.resize_pane(Axis::Horizontal, width.width * count, window, cx);
402        });
403
404        workspace.register_action(|workspace, _: &ResizePaneLeft, window, cx| {
405            let count = Vim::take_count(cx).unwrap_or(1) as f32;
406            Vim::take_forced_motion(cx);
407            let theme = ThemeSettings::get_global(cx);
408            let font_id = window.text_system().resolve_font(&theme.buffer_font);
409            let Ok(width) = window
410                .text_system()
411                .advance(font_id, theme.buffer_font_size(cx), 'm')
412            else {
413                return;
414            };
415            workspace.resize_pane(Axis::Horizontal, -width.width * count, window, cx);
416        });
417
418        workspace.register_action(|workspace, _: &ResizePaneUp, window, cx| {
419            let count = Vim::take_count(cx).unwrap_or(1) as f32;
420            Vim::take_forced_motion(cx);
421            let theme = ThemeSettings::get_global(cx);
422            let height = theme.buffer_font_size(cx) * theme.buffer_line_height.value();
423            workspace.resize_pane(Axis::Vertical, height * count, window, cx);
424        });
425
426        workspace.register_action(|workspace, _: &ResizePaneDown, window, cx| {
427            let count = Vim::take_count(cx).unwrap_or(1) as f32;
428            Vim::take_forced_motion(cx);
429            let theme = ThemeSettings::get_global(cx);
430            let height = theme.buffer_font_size(cx) * theme.buffer_line_height.value();
431            workspace.resize_pane(Axis::Vertical, -height * count, window, cx);
432        });
433
434        workspace.register_action(|workspace, _: &SearchSubmit, window, cx| {
435            let vim = workspace
436                .focused_pane(window, cx)
437                .read(cx)
438                .active_item()
439                .and_then(|item| item.act_as::<Editor>(cx))
440                .and_then(|editor| editor.read(cx).addon::<VimAddon>().cloned());
441            let Some(vim) = vim else { return };
442            vim.entity.update(cx, |vim, cx| {
443                if !vim.search.cmd_f_search {
444                    cx.defer_in(window, |vim, window, cx| vim.search_submit(window, cx))
445                } else {
446                    cx.propagate()
447                }
448            })
449        });
450        workspace.register_action(|_, _: &GoToTab, window, cx| {
451            let count = Vim::take_count(cx);
452            Vim::take_forced_motion(cx);
453
454            if let Some(tab_index) = count {
455                // <count>gt goes to tab <count> (1-based).
456                let zero_based_index = tab_index.saturating_sub(1);
457                window.dispatch_action(
458                    workspace::pane::ActivateItem(zero_based_index).boxed_clone(),
459                    cx,
460                );
461            } else {
462                // If no count is provided, go to the next tab.
463                window.dispatch_action(
464                    workspace::pane::ActivateNextItem::default().boxed_clone(),
465                    cx,
466                );
467            }
468        });
469
470        workspace.register_action(|workspace, _: &GoToPreviousTab, window, cx| {
471            let count = Vim::take_count(cx);
472            Vim::take_forced_motion(cx);
473
474            if let Some(count) = count {
475                // gT with count goes back that many tabs with wraparound (not the same as gt!).
476                let pane = workspace.active_pane().read(cx);
477                let item_count = pane.items().count();
478                if item_count > 0 {
479                    let current_index = pane.active_item_index();
480                    let target_index = (current_index as isize - count as isize)
481                        .rem_euclid(item_count as isize)
482                        as usize;
483                    window.dispatch_action(
484                        workspace::pane::ActivateItem(target_index).boxed_clone(),
485                        cx,
486                    );
487                }
488            } else {
489                // No count provided, go to the previous tab.
490                window.dispatch_action(
491                    workspace::pane::ActivatePreviousItem::default().boxed_clone(),
492                    cx,
493                );
494            }
495        });
496    })
497    .detach();
498}
499
500#[derive(Clone)]
501pub(crate) struct VimAddon {
502    pub(crate) entity: Entity<Vim>,
503}
504
505impl editor::Addon for VimAddon {
506    fn extend_key_context(&self, key_context: &mut KeyContext, cx: &App) {
507        self.entity.read(cx).extend_key_context(key_context, cx)
508    }
509
510    fn to_any(&self) -> &dyn std::any::Any {
511        self
512    }
513}
514
515/// The state pertaining to Vim mode.
516pub(crate) struct Vim {
517    pub(crate) mode: Mode,
518    pub last_mode: Mode,
519    pub temp_mode: bool,
520    pub status_label: Option<SharedString>,
521    pub exit_temporary_mode: bool,
522
523    operator_stack: Vec<Operator>,
524    pub(crate) replacements: Vec<(Range<editor::Anchor>, String)>,
525
526    pub(crate) stored_visual_mode: Option<(Mode, Vec<bool>)>,
527
528    pub(crate) current_tx: Option<TransactionId>,
529    pub(crate) current_anchor: Option<Selection<Anchor>>,
530    pub(crate) undo_modes: HashMap<TransactionId, Mode>,
531    pub(crate) undo_last_line_tx: Option<TransactionId>,
532    extended_pending_selection_id: Option<usize>,
533
534    selected_register: Option<char>,
535    pub search: SearchState,
536
537    editor: WeakEntity<Editor>,
538
539    last_command: Option<String>,
540    running_command: Option<Task<()>>,
541    _subscriptions: Vec<Subscription>,
542}
543
544// Hack: Vim intercepts events dispatched to a window and updates the view in response.
545// This means it needs a VisualContext. The easiest way to satisfy that constraint is
546// to make Vim a "View" that is just never actually rendered.
547impl Render for Vim {
548    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
549        gpui::Empty
550    }
551}
552
553enum VimEvent {
554    Focused,
555}
556impl EventEmitter<VimEvent> for Vim {}
557
558impl Vim {
559    /// The namespace for Vim actions.
560    const NAMESPACE: &'static str = "vim";
561
562    pub fn new(window: &mut Window, cx: &mut Context<Editor>) -> Entity<Self> {
563        let editor = cx.entity();
564
565        let initial_vim_mode = VimSettings::get_global(cx).default_mode;
566        let (mode, last_mode) = if HelixModeSetting::get_global(cx).0 {
567            let initial_helix_mode = match initial_vim_mode {
568                Mode::Normal => Mode::HelixNormal,
569                Mode::Insert => Mode::Insert,
570                // Otherwise, we panic with a note that we should never get there due to the
571                // possible values of VimSettings::get_global(cx).default_mode being either Mode::Normal or Mode::Insert.
572                _ => unreachable!("Invalid default mode"),
573            };
574            (initial_helix_mode, Mode::HelixNormal)
575        } else {
576            (initial_vim_mode, Mode::Normal)
577        };
578
579        cx.new(|cx| Vim {
580            mode,
581            last_mode,
582            temp_mode: false,
583            exit_temporary_mode: false,
584            operator_stack: Vec::new(),
585            replacements: Vec::new(),
586
587            stored_visual_mode: None,
588            current_tx: None,
589            undo_last_line_tx: None,
590            current_anchor: None,
591            extended_pending_selection_id: None,
592            undo_modes: HashMap::default(),
593
594            status_label: None,
595            selected_register: None,
596            search: SearchState::default(),
597
598            last_command: None,
599            running_command: None,
600
601            editor: editor.downgrade(),
602            _subscriptions: vec![
603                cx.observe_keystrokes(Self::observe_keystrokes),
604                cx.subscribe_in(&editor, window, |this, _, event, window, cx| {
605                    this.handle_editor_event(event, window, cx)
606                }),
607            ],
608        })
609    }
610
611    fn register(editor: &mut Editor, window: Option<&mut Window>, cx: &mut Context<Editor>) {
612        let Some(window) = window else {
613            return;
614        };
615
616        if !editor.use_modal_editing() {
617            return;
618        }
619
620        let mut was_enabled = Vim::enabled(cx);
621        let mut was_helix_enabled = HelixModeSetting::get_global(cx).0;
622        let mut was_toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;
623        cx.observe_global_in::<SettingsStore>(window, move |editor, window, cx| {
624            let enabled = Vim::enabled(cx);
625            let helix_enabled = HelixModeSetting::get_global(cx).0;
626            let toggle = VimSettings::get_global(cx).toggle_relative_line_numbers;
627            if enabled && was_enabled && (toggle != was_toggle) {
628                if toggle {
629                    let is_relative = editor
630                        .addon::<VimAddon>()
631                        .map(|vim| vim.entity.read(cx).mode != Mode::Insert);
632                    editor.set_relative_line_number(is_relative, cx)
633                } else {
634                    editor.set_relative_line_number(None, cx)
635                }
636            }
637            let helix_changed = was_helix_enabled != helix_enabled;
638            was_toggle = toggle;
639            was_helix_enabled = helix_enabled;
640
641            let state_changed = (was_enabled != enabled) || (was_enabled && helix_changed);
642            if !state_changed {
643                return;
644            }
645            if was_enabled {
646                Self::deactivate(editor, cx);
647            }
648            was_enabled = enabled;
649            if enabled {
650                Self::activate(editor, window, cx);
651            }
652        })
653        .detach();
654        if was_enabled {
655            Self::activate(editor, window, cx)
656        }
657    }
658
659    fn activate(editor: &mut Editor, window: &mut Window, cx: &mut Context<Editor>) {
660        let vim = Vim::new(window, cx);
661        let state = vim.update(cx, |vim, cx| {
662            if !editor.use_modal_editing() {
663                vim.mode = Mode::Insert;
664            }
665
666            vim.state_for_editor_settings(cx)
667        });
668
669        Vim::sync_vim_settings_to_editor(&state, editor, window, cx);
670
671        editor.register_addon(VimAddon {
672            entity: vim.clone(),
673        });
674
675        vim.update(cx, |_, cx| {
676            Vim::action(editor, cx, |vim, _: &SwitchToNormalMode, window, cx| {
677                vim.switch_mode(Mode::Normal, false, window, cx)
678            });
679
680            Vim::action(editor, cx, |vim, _: &SwitchToInsertMode, window, cx| {
681                vim.switch_mode(Mode::Insert, false, window, cx)
682            });
683
684            Vim::action(editor, cx, |vim, _: &SwitchToReplaceMode, window, cx| {
685                vim.switch_mode(Mode::Replace, false, window, cx)
686            });
687
688            Vim::action(editor, cx, |vim, _: &SwitchToVisualMode, window, cx| {
689                vim.switch_mode(Mode::Visual, false, window, cx)
690            });
691
692            Vim::action(editor, cx, |vim, _: &SwitchToVisualLineMode, window, cx| {
693                vim.switch_mode(Mode::VisualLine, false, window, cx)
694            });
695
696            Vim::action(
697                editor,
698                cx,
699                |vim, _: &SwitchToVisualBlockMode, window, cx| {
700                    vim.switch_mode(Mode::VisualBlock, false, window, cx)
701                },
702            );
703
704            Vim::action(
705                editor,
706                cx,
707                |vim, _: &SwitchToHelixNormalMode, window, cx| {
708                    vim.switch_mode(Mode::HelixNormal, true, window, cx)
709                },
710            );
711            Vim::action(editor, cx, |_, _: &PushForcedMotion, _, cx| {
712                Vim::globals(cx).forced_motion = true;
713            });
714            Vim::action(editor, cx, |vim, action: &PushObject, window, cx| {
715                vim.push_operator(
716                    Operator::Object {
717                        around: action.around,
718                    },
719                    window,
720                    cx,
721                )
722            });
723
724            Vim::action(editor, cx, |vim, action: &PushFindForward, window, cx| {
725                vim.push_operator(
726                    Operator::FindForward {
727                        before: action.before,
728                        multiline: action.multiline,
729                    },
730                    window,
731                    cx,
732                )
733            });
734
735            Vim::action(editor, cx, |vim, action: &PushFindBackward, window, cx| {
736                vim.push_operator(
737                    Operator::FindBackward {
738                        after: action.after,
739                        multiline: action.multiline,
740                    },
741                    window,
742                    cx,
743                )
744            });
745
746            Vim::action(editor, cx, |vim, action: &PushSneak, window, cx| {
747                vim.push_operator(
748                    Operator::Sneak {
749                        first_char: action.first_char,
750                    },
751                    window,
752                    cx,
753                )
754            });
755
756            Vim::action(editor, cx, |vim, action: &PushSneakBackward, window, cx| {
757                vim.push_operator(
758                    Operator::SneakBackward {
759                        first_char: action.first_char,
760                    },
761                    window,
762                    cx,
763                )
764            });
765
766            Vim::action(editor, cx, |vim, _: &PushAddSurrounds, window, cx| {
767                vim.push_operator(Operator::AddSurrounds { target: None }, window, cx)
768            });
769
770            Vim::action(
771                editor,
772                cx,
773                |vim, action: &PushChangeSurrounds, window, cx| {
774                    vim.push_operator(
775                        Operator::ChangeSurrounds {
776                            target: action.target,
777                            opening: false,
778                            bracket_anchors: Vec::new(),
779                        },
780                        window,
781                        cx,
782                    )
783                },
784            );
785
786            Vim::action(editor, cx, |vim, action: &PushJump, window, cx| {
787                vim.push_operator(Operator::Jump { line: action.line }, window, cx)
788            });
789
790            Vim::action(editor, cx, |vim, action: &PushDigraph, window, cx| {
791                vim.push_operator(
792                    Operator::Digraph {
793                        first_char: action.first_char,
794                    },
795                    window,
796                    cx,
797                )
798            });
799
800            Vim::action(editor, cx, |vim, action: &PushLiteral, window, cx| {
801                vim.push_operator(
802                    Operator::Literal {
803                        prefix: action.prefix.clone(),
804                    },
805                    window,
806                    cx,
807                )
808            });
809
810            Vim::action(editor, cx, |vim, _: &PushChange, window, cx| {
811                vim.push_operator(Operator::Change, window, cx)
812            });
813
814            Vim::action(editor, cx, |vim, _: &PushDelete, window, cx| {
815                vim.push_operator(Operator::Delete, window, cx)
816            });
817
818            Vim::action(editor, cx, |vim, _: &PushYank, window, cx| {
819                vim.push_operator(Operator::Yank, window, cx)
820            });
821
822            Vim::action(editor, cx, |vim, _: &PushReplace, window, cx| {
823                vim.push_operator(Operator::Replace, window, cx)
824            });
825
826            Vim::action(editor, cx, |vim, _: &PushDeleteSurrounds, window, cx| {
827                vim.push_operator(Operator::DeleteSurrounds, window, cx)
828            });
829
830            Vim::action(editor, cx, |vim, _: &PushMark, window, cx| {
831                vim.push_operator(Operator::Mark, window, cx)
832            });
833
834            Vim::action(editor, cx, |vim, _: &PushIndent, window, cx| {
835                vim.push_operator(Operator::Indent, window, cx)
836            });
837
838            Vim::action(editor, cx, |vim, _: &PushOutdent, window, cx| {
839                vim.push_operator(Operator::Outdent, window, cx)
840            });
841
842            Vim::action(editor, cx, |vim, _: &PushAutoIndent, window, cx| {
843                vim.push_operator(Operator::AutoIndent, window, cx)
844            });
845
846            Vim::action(editor, cx, |vim, _: &PushRewrap, window, cx| {
847                vim.push_operator(Operator::Rewrap, window, cx)
848            });
849
850            Vim::action(editor, cx, |vim, _: &PushShellCommand, window, cx| {
851                vim.push_operator(Operator::ShellCommand, window, cx)
852            });
853
854            Vim::action(editor, cx, |vim, _: &PushLowercase, window, cx| {
855                vim.push_operator(Operator::Lowercase, window, cx)
856            });
857
858            Vim::action(editor, cx, |vim, _: &PushUppercase, window, cx| {
859                vim.push_operator(Operator::Uppercase, window, cx)
860            });
861
862            Vim::action(editor, cx, |vim, _: &PushOppositeCase, window, cx| {
863                vim.push_operator(Operator::OppositeCase, window, cx)
864            });
865
866            Vim::action(editor, cx, |vim, _: &PushRot13, window, cx| {
867                vim.push_operator(Operator::Rot13, window, cx)
868            });
869
870            Vim::action(editor, cx, |vim, _: &PushRot47, window, cx| {
871                vim.push_operator(Operator::Rot47, window, cx)
872            });
873
874            Vim::action(editor, cx, |vim, _: &PushRegister, window, cx| {
875                vim.push_operator(Operator::Register, window, cx)
876            });
877
878            Vim::action(editor, cx, |vim, _: &PushRecordRegister, window, cx| {
879                vim.push_operator(Operator::RecordRegister, window, cx)
880            });
881
882            Vim::action(editor, cx, |vim, _: &PushReplayRegister, window, cx| {
883                vim.push_operator(Operator::ReplayRegister, window, cx)
884            });
885
886            Vim::action(
887                editor,
888                cx,
889                |vim, _: &PushReplaceWithRegister, window, cx| {
890                    vim.push_operator(Operator::ReplaceWithRegister, window, cx)
891                },
892            );
893
894            Vim::action(editor, cx, |vim, _: &Exchange, window, cx| {
895                if vim.mode.is_visual() {
896                    vim.exchange_visual(window, cx)
897                } else {
898                    vim.push_operator(Operator::Exchange, window, cx)
899                }
900            });
901
902            Vim::action(editor, cx, |vim, _: &ClearExchange, window, cx| {
903                vim.clear_exchange(window, cx)
904            });
905
906            Vim::action(editor, cx, |vim, _: &PushToggleComments, window, cx| {
907                vim.push_operator(Operator::ToggleComments, window, cx)
908            });
909
910            Vim::action(
911                editor,
912                cx,
913                |vim, _: &PushToggleBlockComments, window, cx| {
914                    vim.push_operator(Operator::ToggleBlockComments, window, cx)
915                },
916            );
917
918            Vim::action(editor, cx, |vim, _: &ClearOperators, window, cx| {
919                vim.clear_operator(window, cx)
920            });
921            Vim::action(editor, cx, |vim, n: &Number, window, cx| {
922                vim.push_count_digit(n.0, window, cx);
923            });
924            Vim::action(editor, cx, |vim, _: &Tab, window, cx| {
925                vim.input_ignored(" ".into(), window, cx)
926            });
927            Vim::action(
928                editor,
929                cx,
930                |vim, action: &editor::actions::AcceptEditPrediction, window, cx| {
931                    vim.update_editor(cx, |_, editor, cx| {
932                        editor.accept_edit_prediction(action, window, cx);
933                    });
934                    // In non-insertion modes, predictions will be hidden and instead a jump will be
935                    // displayed (and performed by `accept_edit_prediction`). This switches to
936                    // insert mode so that the prediction is displayed after the jump.
937                    match vim.mode {
938                        Mode::Replace => {}
939                        _ => vim.switch_mode(Mode::Insert, true, window, cx),
940                    };
941                },
942            );
943            Vim::action(editor, cx, |vim, _: &Enter, window, cx| {
944                vim.input_ignored("\n".into(), window, cx)
945            });
946            Vim::action(editor, cx, |vim, _: &PushHelixMatch, window, cx| {
947                vim.push_operator(Operator::HelixMatch, window, cx)
948            });
949            Vim::action(editor, cx, |vim, action: &PushHelixNext, window, cx| {
950                vim.push_operator(
951                    Operator::HelixNext {
952                        around: action.around,
953                    },
954                    window,
955                    cx,
956                );
957            });
958            Vim::action(editor, cx, |vim, action: &PushHelixPrevious, window, cx| {
959                vim.push_operator(
960                    Operator::HelixPrevious {
961                        around: action.around,
962                    },
963                    window,
964                    cx,
965                );
966            });
967
968            Vim::action(
969                editor,
970                cx,
971                |vim, _: &editor::actions::Paste, window, cx| match vim.mode {
972                    Mode::Replace => vim.paste_replace(window, cx),
973                    Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
974                        vim.selected_register.replace('+');
975                        let mut action = VimPaste::default();
976                        action.preserve_clipboard = true;
977                        vim.paste(&action, window, cx);
978                    }
979                    _ => {
980                        vim.update_editor(cx, |_, editor, cx| editor.paste(&Paste, window, cx));
981                    }
982                },
983            );
984
985            normal::register(editor, cx);
986            insert::register(editor, cx);
987            helix::register(editor, cx);
988            motion::register(editor, cx);
989            command::register(editor, cx);
990            replace::register(editor, cx);
991            indent::register(editor, cx);
992            rewrap::register(editor, cx);
993            object::register(editor, cx);
994            visual::register(editor, cx);
995            change_list::register(editor, cx);
996            digraph::register(editor, cx);
997
998            if editor.is_focused(window) {
999                cx.defer_in(window, |vim, window, cx| {
1000                    vim.focused(false, window, cx);
1001                })
1002            }
1003        })
1004    }
1005
1006    fn deactivate(editor: &mut Editor, cx: &mut Context<Editor>) {
1007        editor.set_cursor_shape(
1008            EditorSettings::get_global(cx)
1009                .cursor_shape
1010                .unwrap_or_default(),
1011            cx,
1012        );
1013        editor.set_clip_at_line_ends(false, cx);
1014        editor.set_collapse_matches(false);
1015        editor.set_input_enabled(true);
1016        editor.set_expects_character_input(true);
1017        editor.set_autoindent(true);
1018        editor.selections.set_line_mode(false);
1019        editor.unregister_addon::<VimAddon>();
1020        editor.set_relative_line_number(None, cx);
1021        if let Some(vim) = Vim::globals(cx).focused_vim()
1022            && vim.entity_id() == cx.entity().entity_id()
1023        {
1024            Vim::globals(cx).focused_vim = None;
1025        }
1026    }
1027
1028    /// Register an action on the editor.
1029    pub fn action<A: Action>(
1030        editor: &mut Editor,
1031        cx: &mut Context<Vim>,
1032        f: impl Fn(&mut Vim, &A, &mut Window, &mut Context<Vim>) + 'static,
1033    ) {
1034        let subscription = editor.register_action(cx.listener(move |vim, action, window, cx| {
1035            if !Vim::globals(cx).dot_replaying {
1036                if vim.status_label.take().is_some() {
1037                    cx.notify();
1038                }
1039            }
1040            f(vim, action, window, cx);
1041        }));
1042        cx.on_release(|_, _| drop(subscription)).detach();
1043    }
1044
1045    pub fn editor(&self) -> Option<Entity<Editor>> {
1046        self.editor.upgrade()
1047    }
1048
1049    pub fn workspace(&self, window: &Window, cx: &App) -> Option<Entity<Workspace>> {
1050        Workspace::for_window(window, cx)
1051    }
1052
1053    pub fn pane(&self, window: &Window, cx: &Context<Self>) -> Option<Entity<Pane>> {
1054        let pane = self
1055            .workspace(window, cx)
1056            .map(|workspace| workspace.read(cx).focused_pane(window, cx))?;
1057        // `focused_pane` falls back to the center pane when a dock panel
1058        // without its own pane (e.g. the Agent panel) has focus. Guard
1059        // against that so vim search/match commands don't steal focus.
1060        if pane.read(cx).focus_handle(cx).contains_focused(window, cx) {
1061            Some(pane)
1062        } else {
1063            None
1064        }
1065    }
1066
1067    pub fn enabled(cx: &mut App) -> bool {
1068        VimModeSetting::get_global(cx).0 || HelixModeSetting::get_global(cx).0
1069    }
1070
1071    /// Called whenever an keystroke is typed so vim can observe all actions
1072    /// and keystrokes accordingly.
1073    fn observe_keystrokes(
1074        &mut self,
1075        keystroke_event: &KeystrokeEvent,
1076        window: &mut Window,
1077        cx: &mut Context<Self>,
1078    ) {
1079        if self.exit_temporary_mode {
1080            self.exit_temporary_mode = false;
1081            // Don't switch to insert mode if the action is temporary_normal.
1082            if let Some(action) = keystroke_event.action.as_ref()
1083                && action.as_any().downcast_ref::<TemporaryNormal>().is_some()
1084            {
1085                return;
1086            }
1087            self.switch_mode(Mode::Insert, false, window, cx)
1088        }
1089        if let Some(action) = keystroke_event.action.as_ref() {
1090            // Keystroke is handled by the vim system, so continue forward
1091            if action.name().starts_with("vim::") {
1092                return;
1093            }
1094        } else if window.has_pending_keystrokes() || keystroke_event.keystroke.is_ime_in_progress()
1095        {
1096            return;
1097        }
1098
1099        if let Some(operator) = self.active_operator() {
1100            match operator {
1101                Operator::Literal { prefix } => {
1102                    self.handle_literal_keystroke(
1103                        keystroke_event,
1104                        prefix.unwrap_or_default(),
1105                        window,
1106                        cx,
1107                    );
1108                }
1109                _ if !operator.is_waiting(self.mode) => {
1110                    self.clear_operator(window, cx);
1111                    self.stop_recording_immediately(Box::new(ClearOperators), cx)
1112                }
1113                _ => {}
1114            }
1115        }
1116    }
1117
1118    fn handle_editor_event(
1119        &mut self,
1120        event: &EditorEvent,
1121        window: &mut Window,
1122        cx: &mut Context<Self>,
1123    ) {
1124        match event {
1125            EditorEvent::Focused => self.focused(true, window, cx),
1126            EditorEvent::Blurred => self.blurred(window, cx),
1127            EditorEvent::SelectionsChanged { local: true } => {
1128                self.local_selections_changed(window, cx);
1129            }
1130            EditorEvent::InputIgnored { text } => {
1131                self.input_ignored(text.clone(), window, cx);
1132                Vim::globals(cx).observe_insertion(text, None)
1133            }
1134            EditorEvent::InputHandled {
1135                text,
1136                utf16_range_to_replace: range_to_replace,
1137            } => Vim::globals(cx).observe_insertion(text, range_to_replace.clone()),
1138            EditorEvent::TransactionBegun { transaction_id } => {
1139                self.transaction_begun(*transaction_id, window, cx)
1140            }
1141            EditorEvent::TransactionUndone { transaction_id } => {
1142                self.transaction_undone(transaction_id, window, cx)
1143            }
1144            EditorEvent::Edited { .. } => self.push_to_change_list(window, cx),
1145            EditorEvent::FocusedIn => self.sync_vim_settings(window, cx),
1146            EditorEvent::CursorShapeChanged => self.cursor_shape_changed(window, cx),
1147            EditorEvent::PushedToNavHistory {
1148                anchor,
1149                is_deactivate,
1150            } => {
1151                self.update_editor(cx, |vim, editor, cx| {
1152                    let mark = if *is_deactivate {
1153                        "\"".to_string()
1154                    } else {
1155                        "'".to_string()
1156                    };
1157                    vim.set_mark(mark, vec![*anchor], editor.buffer(), window, cx);
1158                });
1159            }
1160            _ => {}
1161        }
1162    }
1163
1164    fn push_operator(&mut self, operator: Operator, window: &mut Window, cx: &mut Context<Self>) {
1165        if operator.starts_dot_recording() {
1166            self.start_recording(cx);
1167        }
1168        // Since these operations can only be entered with pre-operators,
1169        // we need to clear the previous operators when pushing,
1170        // so that the current stack is the most correct
1171        if matches!(
1172            operator,
1173            Operator::AddSurrounds { .. }
1174                | Operator::ChangeSurrounds { .. }
1175                | Operator::DeleteSurrounds
1176                | Operator::Exchange
1177        ) {
1178            self.operator_stack.clear();
1179        };
1180        self.operator_stack.push(operator);
1181        self.sync_vim_settings(window, cx);
1182    }
1183
1184    pub fn switch_mode(
1185        &mut self,
1186        mode: Mode,
1187        leave_selections: bool,
1188        window: &mut Window,
1189        cx: &mut Context<Self>,
1190    ) {
1191        if self.temp_mode && mode == Mode::Normal {
1192            self.temp_mode = false;
1193            self.switch_mode(Mode::Normal, leave_selections, window, cx);
1194            self.switch_mode(Mode::Insert, false, window, cx);
1195            return;
1196        } else if self.temp_mode
1197            && !matches!(mode, Mode::Visual | Mode::VisualLine | Mode::VisualBlock)
1198        {
1199            self.temp_mode = false;
1200        }
1201
1202        let last_mode = self.mode;
1203        let prior_mode = self.last_mode;
1204        let prior_tx = self.current_tx;
1205        self.last_mode = last_mode;
1206        self.mode = mode;
1207        self.operator_stack.clear();
1208        self.selected_register.take();
1209        self.cancel_running_command(window, cx);
1210        if mode == Mode::Normal || mode != last_mode {
1211            self.current_tx.take();
1212            self.current_anchor.take();
1213            self.update_editor(cx, |_, editor, _| {
1214                editor.clear_selection_drag_state();
1215            });
1216        }
1217        Vim::take_forced_motion(cx);
1218        if mode != Mode::Insert && mode != Mode::Replace {
1219            Vim::take_count(cx);
1220        }
1221
1222        // Sync editor settings like clip mode
1223        self.sync_vim_settings(window, cx);
1224
1225        if VimSettings::get_global(cx).toggle_relative_line_numbers
1226            && self.mode != self.last_mode
1227            && (self.mode == Mode::Insert || self.last_mode == Mode::Insert)
1228        {
1229            self.update_editor(cx, |vim, editor, cx| {
1230                let is_relative = vim.mode != Mode::Insert;
1231                editor.set_relative_line_number(Some(is_relative), cx)
1232            });
1233        }
1234        if HelixModeSetting::get_global(cx).0 {
1235            if self.mode == Mode::Normal {
1236                self.mode = Mode::HelixNormal
1237            } else if self.mode == Mode::Visual {
1238                self.mode = Mode::HelixSelect
1239            }
1240        }
1241
1242        if leave_selections {
1243            return;
1244        }
1245
1246        if !mode.is_visual() && last_mode.is_visual() && !last_mode.is_helix() {
1247            self.create_visual_marks(last_mode, window, cx);
1248        }
1249
1250        // Adjust selections
1251        self.update_editor(cx, |vim, editor, cx| {
1252            if last_mode != Mode::VisualBlock && last_mode.is_visual() && mode == Mode::VisualBlock
1253            {
1254                vim.visual_block_motion(true, editor, window, cx, &mut |_, point, goal| {
1255                    Some((point, goal))
1256                })
1257            }
1258            if (last_mode == Mode::Insert || last_mode == Mode::Replace)
1259                && let Some(prior_tx) = prior_tx
1260            {
1261                editor.group_until_transaction(prior_tx, cx)
1262            }
1263
1264            editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1265                // we cheat with visual block mode and use multiple cursors.
1266                // the cost of this cheat is we need to convert back to a single
1267                // cursor whenever vim would.
1268                if last_mode == Mode::VisualBlock
1269                    && (mode != Mode::VisualBlock && mode != Mode::Insert)
1270                {
1271                    let tail = s.oldest_anchor().tail();
1272                    let head = s.newest_anchor().head();
1273                    s.select_anchor_ranges(vec![tail..head]);
1274                } else if last_mode == Mode::Insert
1275                    && prior_mode == Mode::VisualBlock
1276                    && mode != Mode::VisualBlock
1277                {
1278                    let pos = s.first_anchor().head();
1279                    s.select_anchor_ranges(vec![pos..pos])
1280                }
1281
1282                let mut should_extend_pending = false;
1283                if !last_mode.is_visual()
1284                    && mode.is_visual()
1285                    && let Some(pending) = s.pending_anchor()
1286                {
1287                    let snapshot = s.display_snapshot();
1288                    let is_empty = pending
1289                        .start
1290                        .cmp(&pending.end, &snapshot.buffer_snapshot())
1291                        .is_eq();
1292                    should_extend_pending = pending.reversed
1293                        && !is_empty
1294                        && vim.extended_pending_selection_id != Some(pending.id);
1295                };
1296
1297                if should_extend_pending {
1298                    let snapshot = s.display_snapshot();
1299                    s.change_with(&snapshot, |map| {
1300                        if let Some(pending) = map.pending_anchor_mut() {
1301                            let end = pending.end.to_point(&snapshot.buffer_snapshot());
1302                            let end = end.to_display_point(&snapshot);
1303                            let new_end = movement::right(&snapshot, end);
1304                            pending.end = snapshot
1305                                .buffer_snapshot()
1306                                .anchor_before(new_end.to_point(&snapshot));
1307                        }
1308                    });
1309                    vim.extended_pending_selection_id = s.pending_anchor().map(|p| p.id)
1310                }
1311
1312                s.move_with(&mut |map, selection| {
1313                    if last_mode.is_visual() && !last_mode.is_helix() && !mode.is_visual() {
1314                        let mut point = selection.head();
1315                        if !selection.reversed && !selection.is_empty() {
1316                            point = movement::left(map, selection.head());
1317                        } else if selection.is_empty() {
1318                            point = map.clip_point(point, Bias::Left);
1319                        }
1320                        selection.collapse_to(point, selection.goal)
1321                    } else if !last_mode.is_visual() && mode.is_visual() {
1322                        if selection.is_empty() {
1323                            selection.end = movement::right(map, selection.start);
1324                        }
1325                    }
1326                });
1327            })
1328        });
1329    }
1330
1331    pub fn take_count(cx: &mut App) -> Option<usize> {
1332        let global_state = cx.global_mut::<VimGlobals>();
1333        if global_state.dot_replaying {
1334            return global_state.recorded_count;
1335        }
1336
1337        let count = if global_state.post_count.is_none() && global_state.pre_count.is_none() {
1338            return None;
1339        } else {
1340            Some(
1341                global_state.post_count.take().unwrap_or(1)
1342                    * global_state.pre_count.take().unwrap_or(1),
1343            )
1344        };
1345
1346        if global_state.dot_recording {
1347            global_state.recording_count = count;
1348        }
1349        count
1350    }
1351
1352    pub fn take_forced_motion(cx: &mut App) -> bool {
1353        let global_state = cx.global_mut::<VimGlobals>();
1354        let forced_motion = global_state.forced_motion;
1355        global_state.forced_motion = false;
1356        forced_motion
1357    }
1358
1359    pub fn cursor_shape(&self, cx: &App) -> CursorShape {
1360        let cursor_shape = VimSettings::get_global(cx).cursor_shape;
1361        match self.mode {
1362            Mode::Normal => {
1363                if let Some(operator) = self.operator_stack.last() {
1364                    match operator {
1365                        // Vim jump labels are transient navigation, so keep the
1366                        // user's normal cursor shape while waiting for the label.
1367                        Operator::HelixJump { .. } => cursor_shape.normal,
1368
1369                        // Navigation operators -> Block cursor
1370                        Operator::FindForward { .. }
1371                        | Operator::FindBackward { .. }
1372                        | Operator::Mark
1373                        | Operator::Jump { .. }
1374                        | Operator::Register
1375                        | Operator::RecordRegister
1376                        | Operator::ReplayRegister => CursorShape::Block,
1377
1378                        // All other operators -> Underline cursor
1379                        _ => CursorShape::Underline,
1380                    }
1381                } else {
1382                    cursor_shape.normal
1383                }
1384            }
1385            Mode::HelixNormal => cursor_shape.normal,
1386            Mode::Replace => cursor_shape.replace,
1387            Mode::Visual | Mode::VisualLine | Mode::VisualBlock | Mode::HelixSelect => {
1388                cursor_shape.visual
1389            }
1390            Mode::Insert => match cursor_shape.insert {
1391                InsertModeCursorShape::Explicit(shape) => shape,
1392                InsertModeCursorShape::Inherit => {
1393                    let editor_settings = EditorSettings::get_global(cx);
1394                    editor_settings.cursor_shape.unwrap_or_default()
1395                }
1396            },
1397        }
1398    }
1399
1400    fn expects_character_input(&self) -> bool {
1401        if let Some(operator) = self.operator_stack.last() {
1402            if operator.is_waiting(self.mode) {
1403                return true;
1404            }
1405        }
1406        self.editor_input_enabled()
1407    }
1408
1409    pub fn editor_input_enabled(&self) -> bool {
1410        match self.mode {
1411            Mode::Insert => {
1412                if let Some(operator) = self.operator_stack.last() {
1413                    !operator.is_waiting(self.mode)
1414                } else {
1415                    true
1416                }
1417            }
1418            Mode::Normal
1419            | Mode::HelixNormal
1420            | Mode::Replace
1421            | Mode::Visual
1422            | Mode::VisualLine
1423            | Mode::VisualBlock
1424            | Mode::HelixSelect => false,
1425        }
1426    }
1427
1428    pub fn should_autoindent(&self) -> bool {
1429        !(self.mode == Mode::Insert && self.last_mode == Mode::VisualBlock)
1430    }
1431
1432    pub fn clip_at_line_ends(&self) -> bool {
1433        match self.mode {
1434            Mode::Insert
1435            | Mode::Visual
1436            | Mode::VisualLine
1437            | Mode::VisualBlock
1438            | Mode::Replace
1439            | Mode::HelixNormal
1440            | Mode::HelixSelect => false,
1441            Mode::Normal => true,
1442        }
1443    }
1444
1445    pub fn extend_key_context(&self, context: &mut KeyContext, cx: &App) {
1446        let mut mode = match self.mode {
1447            Mode::Normal => "normal",
1448            Mode::Visual | Mode::VisualLine | Mode::VisualBlock => "visual",
1449            Mode::Insert => "insert",
1450            Mode::Replace => "replace",
1451            Mode::HelixNormal => "helix_normal",
1452            Mode::HelixSelect => "helix_select",
1453        }
1454        .to_string();
1455
1456        let mut operator_id = "none";
1457
1458        let active_operator = self.active_operator();
1459        if active_operator.is_none() && cx.global::<VimGlobals>().pre_count.is_some()
1460            || active_operator.is_some() && cx.global::<VimGlobals>().post_count.is_some()
1461        {
1462            context.add("VimCount");
1463        }
1464
1465        if let Some(active_operator) = active_operator {
1466            if active_operator.is_waiting(self.mode) {
1467                if matches!(active_operator, Operator::Literal { .. }) {
1468                    mode = "literal".to_string();
1469                } else {
1470                    mode = "waiting".to_string();
1471                }
1472            } else if matches!(
1473                active_operator,
1474                Operator::HelixNext { .. } | Operator::HelixPrevious { .. }
1475            ) {
1476                // Helix `[`/`]` take a curated, keymap-dispatched selector key
1477                // rather than a motion over a range, so they keep `operator_id`
1478                // set (so `vim_operator == helix_next/previous` context must
1479                // resolve) but must not use the `operator` mode, as that adds
1480                // `VimControl` and the `vim_mode == operator` context, whose `g
1481                // ...` bindings would make a single-key follow-up like `g` a
1482                // multi-key prefix and leave `] g` waiting for more input.
1483                // Setting the mode to `waiting` carries none of those
1484                // conflicting bindings and still provides bindings for
1485                // `escape`/`ctrl-c` to `ClearOperators`.
1486                operator_id = active_operator.id();
1487                mode = "waiting".to_string();
1488            } else {
1489                operator_id = active_operator.id();
1490                mode = "operator".to_string();
1491            }
1492        }
1493
1494        if mode == "normal"
1495            || mode == "visual"
1496            || mode == "operator"
1497            || mode == "helix_normal"
1498            || mode == "helix_select"
1499        {
1500            context.add("VimControl");
1501        }
1502        context.set("vim_mode", mode);
1503        context.set("vim_operator", operator_id);
1504    }
1505
1506    fn focused(&mut self, preserve_selection: bool, window: &mut Window, cx: &mut Context<Self>) {
1507        // If editor gains focus while search bar is still open (not dismissed),
1508        // the user has explicitly navigated away - clear prior_selections so we
1509        // don't restore to the old position if they later dismiss the search.
1510        if !self.search.prior_selections.is_empty() {
1511            if let Some(pane) = self.pane(window, cx) {
1512                let search_still_open = pane
1513                    .read(cx)
1514                    .toolbar()
1515                    .read(cx)
1516                    .item_of_type::<BufferSearchBar>()
1517                    .is_some_and(|bar| !bar.read(cx).is_dismissed());
1518                if search_still_open {
1519                    self.search.prior_selections.clear();
1520                }
1521            }
1522        }
1523
1524        let Some(editor) = self.editor() else {
1525            return;
1526        };
1527        let newest_selection_empty = editor.update(cx, |editor, cx| {
1528            editor
1529                .selections
1530                .newest::<MultiBufferOffset>(&editor.display_snapshot(cx))
1531                .is_empty()
1532        });
1533        let editor = editor.read(cx);
1534        let editor_mode = editor.mode();
1535
1536        if editor_mode.is_full()
1537            && !newest_selection_empty
1538            && self.mode == Mode::Normal
1539            // When following someone, don't switch vim mode.
1540            && editor.leader_id().is_none()
1541        {
1542            if preserve_selection {
1543                self.switch_mode(Mode::Visual, true, window, cx);
1544            } else {
1545                self.update_editor(cx, |_, editor, cx| {
1546                    editor.set_clip_at_line_ends(false, cx);
1547                    editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1548                        s.move_with(&mut |_, selection| {
1549                            selection.collapse_to(selection.start, selection.goal)
1550                        })
1551                    });
1552                });
1553            }
1554        }
1555
1556        cx.emit(VimEvent::Focused);
1557        self.sync_vim_settings(window, cx);
1558
1559        if VimSettings::get_global(cx).toggle_relative_line_numbers {
1560            if let Some(old_vim) = Vim::globals(cx).focused_vim() {
1561                if old_vim.entity_id() != cx.entity().entity_id() {
1562                    old_vim.update(cx, |vim, cx| {
1563                        vim.update_editor(cx, |_, editor, cx| {
1564                            editor.set_relative_line_number(None, cx)
1565                        });
1566                    });
1567
1568                    self.update_editor(cx, |vim, editor, cx| {
1569                        let is_relative = vim.mode != Mode::Insert;
1570                        editor.set_relative_line_number(Some(is_relative), cx)
1571                    });
1572                }
1573            } else {
1574                self.update_editor(cx, |vim, editor, cx| {
1575                    let is_relative = vim.mode != Mode::Insert;
1576                    editor.set_relative_line_number(Some(is_relative), cx)
1577                });
1578            }
1579        }
1580        Vim::globals(cx).focused_vim = Some(cx.entity().downgrade());
1581    }
1582
1583    fn blurred(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1584        self.stop_recording_immediately(NormalBefore.boxed_clone(), cx);
1585        self.store_visual_marks(window, cx);
1586        self.clear_operator(window, cx);
1587        self.update_editor(cx, |vim, editor, cx| {
1588            if vim.cursor_shape(cx) == CursorShape::Block {
1589                editor.set_cursor_shape(CursorShape::Hollow, cx);
1590            }
1591        });
1592    }
1593
1594    fn cursor_shape_changed(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1595        self.update_editor(cx, |vim, editor, cx| {
1596            editor.set_cursor_shape(vim.cursor_shape(cx), cx);
1597        });
1598    }
1599
1600    fn update_editor<S>(
1601        &mut self,
1602        cx: &mut Context<Self>,
1603        update: impl FnOnce(&mut Self, &mut Editor, &mut Context<Editor>) -> S,
1604    ) -> Option<S> {
1605        let editor = self.editor.upgrade()?;
1606        Some(editor.update(cx, |editor, cx| update(self, editor, cx)))
1607    }
1608
1609    fn editor_selections(&mut self, _: &mut Window, cx: &mut Context<Self>) -> Vec<Range<Anchor>> {
1610        self.update_editor(cx, |_, editor, _| {
1611            editor
1612                .selections
1613                .disjoint_anchors_arc()
1614                .iter()
1615                .map(|selection| selection.tail()..selection.head())
1616                .collect()
1617        })
1618        .unwrap_or_default()
1619    }
1620
1621    /// When doing an action that modifies the buffer, we start recording so that `.`
1622    /// will replay the action.
1623    pub fn start_recording(&mut self, cx: &mut Context<Self>) {
1624        Vim::update_globals(cx, |globals, cx| {
1625            if !globals.dot_replaying {
1626                globals.dot_recording = true;
1627                globals.recording_actions = Default::default();
1628                globals.recording_count = None;
1629                globals.recording_register_for_dot = self.selected_register;
1630
1631                let selections = self.editor().map(|editor| {
1632                    editor.update(cx, |editor, cx| {
1633                        let snapshot = editor.display_snapshot(cx);
1634
1635                        (
1636                            editor.selections.oldest::<Point>(&snapshot),
1637                            editor.selections.newest::<Point>(&snapshot),
1638                        )
1639                    })
1640                });
1641
1642                if let Some((oldest, newest)) = selections {
1643                    globals.recorded_selection = match self.mode {
1644                        Mode::Visual if newest.end.row == newest.start.row => {
1645                            RecordedSelection::SingleLine {
1646                                cols: newest.end.column - newest.start.column,
1647                            }
1648                        }
1649                        Mode::Visual => RecordedSelection::Visual {
1650                            rows: newest.end.row - newest.start.row,
1651                            cols: newest.end.column,
1652                        },
1653                        Mode::VisualLine => RecordedSelection::VisualLine {
1654                            rows: newest.end.row - newest.start.row,
1655                        },
1656                        Mode::VisualBlock => RecordedSelection::VisualBlock {
1657                            rows: newest.end.row.abs_diff(oldest.start.row),
1658                            cols: newest.end.column.abs_diff(oldest.start.column),
1659                        },
1660                        _ => RecordedSelection::None,
1661                    }
1662                } else {
1663                    globals.recorded_selection = RecordedSelection::None;
1664                }
1665            }
1666        })
1667    }
1668
1669    pub fn stop_replaying(&mut self, cx: &mut Context<Self>) {
1670        let globals = Vim::globals(cx);
1671        globals.dot_replaying = false;
1672        if let Some(replayer) = globals.replayer.take() {
1673            replayer.stop();
1674        }
1675    }
1676
1677    /// When finishing an action that modifies the buffer, stop recording.
1678    /// as you usually call this within a keystroke handler we also ensure that
1679    /// the current action is recorded.
1680    pub fn stop_recording(&mut self, cx: &mut Context<Self>) {
1681        let globals = Vim::globals(cx);
1682        if globals.dot_recording {
1683            globals.stop_recording_after_next_action = true;
1684        }
1685        self.exit_temporary_mode = self.temp_mode;
1686    }
1687
1688    /// Stops recording actions immediately rather than waiting until after the
1689    /// next action to stop recording.
1690    ///
1691    /// This doesn't include the current action.
1692    pub fn stop_recording_immediately(&mut self, action: Box<dyn Action>, cx: &mut Context<Self>) {
1693        let globals = Vim::globals(cx);
1694        if globals.dot_recording {
1695            globals
1696                .recording_actions
1697                .push(ReplayableAction::Action(action.boxed_clone()));
1698            globals.recorded_actions = mem::take(&mut globals.recording_actions);
1699            globals.recorded_count = globals.recording_count.take();
1700            globals.dot_recording = false;
1701            globals.stop_recording_after_next_action = false;
1702        }
1703        self.exit_temporary_mode = self.temp_mode;
1704    }
1705
1706    /// Explicitly record one action (equivalents to start_recording and stop_recording)
1707    pub fn record_current_action(&mut self, cx: &mut Context<Self>) {
1708        self.start_recording(cx);
1709        self.stop_recording(cx);
1710    }
1711
1712    fn push_count_digit(&mut self, number: usize, window: &mut Window, cx: &mut Context<Self>) {
1713        if self.active_operator().is_some() {
1714            let post_count = Vim::globals(cx).post_count.unwrap_or(0);
1715
1716            Vim::globals(cx).post_count = Some(
1717                post_count
1718                    .checked_mul(10)
1719                    .and_then(|post_count| post_count.checked_add(number))
1720                    .filter(|post_count| *post_count < isize::MAX as usize)
1721                    .unwrap_or(post_count),
1722            )
1723        } else {
1724            let pre_count = Vim::globals(cx).pre_count.unwrap_or(0);
1725
1726            Vim::globals(cx).pre_count = Some(
1727                pre_count
1728                    .checked_mul(10)
1729                    .and_then(|pre_count| pre_count.checked_add(number))
1730                    .filter(|pre_count| *pre_count < isize::MAX as usize)
1731                    .unwrap_or(pre_count),
1732            )
1733        }
1734        // update the keymap so that 0 works
1735        self.sync_vim_settings(window, cx)
1736    }
1737
1738    fn select_register(&mut self, register: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
1739        if register.chars().count() == 1 {
1740            self.selected_register
1741                .replace(register.chars().next().unwrap());
1742        }
1743        self.operator_stack.clear();
1744        self.sync_vim_settings(window, cx);
1745    }
1746
1747    fn maybe_pop_operator(&mut self) -> Option<Operator> {
1748        self.operator_stack.pop()
1749    }
1750
1751    fn pop_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Operator {
1752        let popped_operator = self.operator_stack.pop()
1753            .expect("Operator popped when no operator was on the stack. This likely means there is an invalid keymap config");
1754        self.sync_vim_settings(window, cx);
1755        popped_operator
1756    }
1757
1758    fn clear_operator(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1759        if matches!(self.active_operator(), Some(Operator::HelixJump { .. })) {
1760            self.clear_helix_jump_ui(window, cx);
1761        }
1762        Vim::take_count(cx);
1763        Vim::take_forced_motion(cx);
1764        self.selected_register.take();
1765        self.operator_stack.clear();
1766        self.sync_vim_settings(window, cx);
1767    }
1768
1769    fn clear_helix_jump_ui(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1770        self.update_editor(cx, move |_, editor, cx| {
1771            editor.clear_navigation_overlays(HELIX_JUMP_OVERLAY_KEY, cx);
1772        });
1773    }
1774
1775    fn apply_helix_jump_ui(
1776        &mut self,
1777        overlays: Vec<NavigationTargetOverlay>,
1778        window: &mut Window,
1779        cx: &mut Context<Self>,
1780    ) -> bool {
1781        self.clear_helix_jump_ui(window, cx);
1782        self.update_editor(cx, |_, editor, cx| {
1783            editor.set_navigation_overlays(HELIX_JUMP_OVERLAY_KEY, overlays, cx);
1784        })
1785        .is_some()
1786    }
1787
1788    fn handle_helix_jump_input(
1789        &mut self,
1790        operator: Operator,
1791        input_char: char,
1792        window: &mut Window,
1793        cx: &mut Context<Self>,
1794    ) {
1795        let Operator::HelixJump {
1796            behaviour,
1797            first_char,
1798            labels,
1799        } = operator
1800        else {
1801            return;
1802        };
1803
1804        let input = input_char.to_ascii_lowercase();
1805        self.pop_operator(window, cx);
1806
1807        if let Some(first) = first_char {
1808            let first = first.to_ascii_lowercase();
1809            if let Some(candidate) = labels.into_iter().find(|label| {
1810                label.label[0].eq_ignore_ascii_case(&first)
1811                    && label.label[1].eq_ignore_ascii_case(&input)
1812            }) {
1813                self.finish_helix_jump(candidate, behaviour, window, cx);
1814            } else {
1815                self.clear_helix_jump_ui(window, cx);
1816            }
1817        } else {
1818            if !labels
1819                .iter()
1820                .any(|label| label.label[0].eq_ignore_ascii_case(&input))
1821            {
1822                self.clear_helix_jump_ui(window, cx);
1823                return;
1824            }
1825
1826            self.push_operator(
1827                Operator::HelixJump {
1828                    behaviour,
1829                    first_char: Some(input),
1830                    labels,
1831                },
1832                window,
1833                cx,
1834            );
1835        }
1836    }
1837
1838    fn finish_helix_jump(
1839        &mut self,
1840        candidate: HelixJumpLabel,
1841        behaviour: HelixJumpBehaviour,
1842        window: &mut Window,
1843        cx: &mut Context<Self>,
1844    ) {
1845        self.update_editor(cx, |_, editor, cx| match behaviour {
1846            HelixJumpBehaviour::Move => {
1847                editor.change_selections(Default::default(), window, cx, |s| {
1848                    s.select_anchor_ranges([candidate.range.clone()])
1849                });
1850            }
1851            HelixJumpBehaviour::MoveToWordStart => {
1852                editor.change_selections(Default::default(), window, cx, |s| {
1853                    // Vim users expect jump labels to behave like motions, leaving
1854                    // normal mode at the label instead of selecting the word.
1855                    s.select_anchor_ranges([candidate.range.start..candidate.range.start])
1856                });
1857            }
1858            HelixJumpBehaviour::ExtendToWordStart => {
1859                editor.change_selections(Default::default(), window, cx, |s| {
1860                    s.move_with(&mut |map, selection| {
1861                        let word_start = candidate.range.start.to_display_point(map);
1862                        let tail = selection.tail();
1863
1864                        if word_start >= tail {
1865                            selection
1866                                .set_head(motion::right(map, word_start, 1), SelectionGoal::None);
1867                        } else {
1868                            selection.set_head_tail(word_start, selection.end, SelectionGoal::None);
1869                        }
1870                    });
1871                });
1872            }
1873            HelixJumpBehaviour::Extend => {
1874                editor.change_selections(Default::default(), window, cx, |s| {
1875                    s.move_with(&mut |map, selection| {
1876                        let word_start = candidate.range.start.to_display_point(map);
1877                        let word_end = candidate.range.end.to_display_point(map);
1878                        let tail = selection.tail();
1879
1880                        if word_start >= tail {
1881                            // Jumping forward: extend head to end of target word
1882                            selection.set_head(word_end, SelectionGoal::None);
1883                        } else {
1884                            // Jumping backward: extend backward while keeping current extent
1885                            // Use current end as tail to preserve the selection
1886                            selection.set_head_tail(word_start, selection.end, SelectionGoal::None);
1887                        }
1888                    });
1889                });
1890            }
1891        });
1892        self.clear_helix_jump_ui(window, cx);
1893    }
1894
1895    fn active_operator(&self) -> Option<Operator> {
1896        self.operator_stack.last().cloned()
1897    }
1898
1899    fn transaction_begun(
1900        &mut self,
1901        transaction_id: TransactionId,
1902        _window: &mut Window,
1903        _: &mut Context<Self>,
1904    ) {
1905        let mode = if (self.mode == Mode::Insert
1906            || self.mode == Mode::Replace
1907            || self.mode == Mode::Normal)
1908            && self.current_tx.is_none()
1909        {
1910            self.current_tx = Some(transaction_id);
1911            self.last_mode
1912        } else {
1913            self.mode
1914        };
1915        if mode == Mode::VisualLine || mode == Mode::VisualBlock {
1916            self.undo_modes.insert(transaction_id, mode);
1917        }
1918    }
1919
1920    fn transaction_undone(
1921        &mut self,
1922        transaction_id: &TransactionId,
1923        window: &mut Window,
1924        cx: &mut Context<Self>,
1925    ) {
1926        match self.mode {
1927            Mode::VisualLine | Mode::VisualBlock | Mode::Visual | Mode::HelixSelect => {
1928                self.update_editor(cx, |vim, editor, cx| {
1929                    let original_mode = vim.undo_modes.get(transaction_id);
1930                    editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1931                        match original_mode {
1932                            Some(Mode::VisualLine) => {
1933                                s.move_with(&mut |map, selection| {
1934                                    selection.collapse_to(
1935                                        map.prev_line_boundary(selection.start.to_point(map)).1,
1936                                        SelectionGoal::None,
1937                                    )
1938                                });
1939                            }
1940                            Some(Mode::VisualBlock) => {
1941                                let mut first = s.first_anchor();
1942                                first.collapse_to(first.start, first.goal);
1943                                s.select_anchors(vec![first]);
1944                            }
1945                            _ => {
1946                                s.move_with(&mut |map, selection| {
1947                                    selection.collapse_to(
1948                                        map.clip_at_line_end(selection.start),
1949                                        selection.goal,
1950                                    );
1951                                });
1952                            }
1953                        }
1954                    });
1955                });
1956                self.switch_mode(Mode::Normal, true, window, cx)
1957            }
1958            Mode::Normal => {
1959                self.update_editor(cx, |_, editor, cx| {
1960                    editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1961                        s.move_with(&mut |map, selection| {
1962                            selection
1963                                .collapse_to(map.clip_at_line_end(selection.end), selection.goal)
1964                        })
1965                    })
1966                });
1967            }
1968            Mode::Insert | Mode::Replace | Mode::HelixNormal => {}
1969        }
1970    }
1971
1972    fn local_selections_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1973        let Some(editor) = self.editor() else { return };
1974
1975        if editor.read(cx).leader_id().is_some() {
1976            return;
1977        }
1978
1979        let newest = editor.read(cx).selections.newest_anchor().clone();
1980        let is_multicursor = editor.read(cx).selections.count() > 1;
1981        if self.mode == Mode::Insert && self.current_tx.is_some() {
1982            if let Some(current_anchor) = &self.current_anchor {
1983                if current_anchor != &newest
1984                    && let Some(tx_id) = self.current_tx.take()
1985                {
1986                    self.update_editor(cx, |_, editor, cx| {
1987                        editor.group_until_transaction(tx_id, cx)
1988                    });
1989                }
1990            } else {
1991                self.current_anchor = Some(newest);
1992            }
1993        } else if self.mode == Mode::Normal && newest.start != newest.end {
1994            if matches!(newest.goal, SelectionGoal::HorizontalRange { .. }) {
1995                self.switch_mode(Mode::VisualBlock, false, window, cx);
1996            } else {
1997                self.switch_mode(Mode::Visual, false, window, cx)
1998            }
1999        } else if newest.start == newest.end
2000            && !is_multicursor
2001            && [Mode::Visual, Mode::VisualLine, Mode::VisualBlock].contains(&self.mode)
2002        {
2003            self.switch_mode(Mode::Normal, false, window, cx);
2004        }
2005    }
2006
2007    fn input_ignored(&mut self, text: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
2008        if text.is_empty() {
2009            return;
2010        }
2011
2012        match self.active_operator() {
2013            Some(Operator::FindForward { before, multiline }) => {
2014                let find = Motion::FindForward {
2015                    before,
2016                    char: text.chars().next().unwrap(),
2017                    mode: if multiline {
2018                        FindRange::MultiLine
2019                    } else {
2020                        FindRange::SingleLine
2021                    },
2022                    smartcase: VimSettings::get_global(cx).use_smartcase_find,
2023                };
2024                Vim::globals(cx).last_find = Some(find.clone());
2025                self.motion(find, window, cx)
2026            }
2027            Some(Operator::FindBackward { after, multiline }) => {
2028                let find = Motion::FindBackward {
2029                    after,
2030                    char: text.chars().next().unwrap(),
2031                    mode: if multiline {
2032                        FindRange::MultiLine
2033                    } else {
2034                        FindRange::SingleLine
2035                    },
2036                    smartcase: VimSettings::get_global(cx).use_smartcase_find,
2037                };
2038                Vim::globals(cx).last_find = Some(find.clone());
2039                self.motion(find, window, cx)
2040            }
2041            Some(Operator::Sneak { first_char }) => {
2042                if let Some(first_char) = first_char {
2043                    if let Some(second_char) = text.chars().next() {
2044                        let sneak = Motion::Sneak {
2045                            first_char,
2046                            second_char,
2047                            smartcase: VimSettings::get_global(cx).use_smartcase_find,
2048                        };
2049                        Vim::globals(cx).last_find = Some(sneak.clone());
2050                        self.motion(sneak, window, cx)
2051                    }
2052                } else {
2053                    let first_char = text.chars().next();
2054                    self.pop_operator(window, cx);
2055                    self.push_operator(Operator::Sneak { first_char }, window, cx);
2056                }
2057            }
2058            Some(Operator::SneakBackward { first_char }) => {
2059                if let Some(first_char) = first_char {
2060                    if let Some(second_char) = text.chars().next() {
2061                        let sneak = Motion::SneakBackward {
2062                            first_char,
2063                            second_char,
2064                            smartcase: VimSettings::get_global(cx).use_smartcase_find,
2065                        };
2066                        Vim::globals(cx).last_find = Some(sneak.clone());
2067                        self.motion(sneak, window, cx)
2068                    }
2069                } else {
2070                    let first_char = text.chars().next();
2071                    self.pop_operator(window, cx);
2072                    self.push_operator(Operator::SneakBackward { first_char }, window, cx);
2073                }
2074            }
2075            Some(operator @ Operator::HelixJump { .. }) => {
2076                if let Some(input_char) = text.chars().next() {
2077                    self.handle_helix_jump_input(operator, input_char, window, cx);
2078                }
2079            }
2080            Some(Operator::Replace) => match self.mode {
2081                Mode::Normal => self.normal_replace(text, window, cx),
2082                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
2083                    self.visual_replace(text, window, cx)
2084                }
2085                Mode::HelixNormal | Mode::HelixSelect => self.helix_replace(&text, window, cx),
2086                _ => self.clear_operator(window, cx),
2087            },
2088            Some(Operator::Digraph { first_char }) => {
2089                if let Some(first_char) = first_char {
2090                    if let Some(second_char) = text.chars().next() {
2091                        self.insert_digraph(first_char, second_char, window, cx);
2092                    }
2093                } else {
2094                    let first_char = text.chars().next();
2095                    self.pop_operator(window, cx);
2096                    self.push_operator(Operator::Digraph { first_char }, window, cx);
2097                }
2098            }
2099            Some(Operator::Literal { prefix }) => {
2100                self.handle_literal_input(prefix.unwrap_or_default(), &text, window, cx)
2101            }
2102            Some(Operator::AddSurrounds { target }) => match self.mode {
2103                Mode::Normal => {
2104                    if let Some(target) = target {
2105                        self.add_surrounds(text, target, window, cx);
2106                        self.clear_operator(window, cx);
2107                    }
2108                }
2109                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
2110                    self.add_surrounds(text, SurroundsType::Selection, window, cx);
2111                    self.clear_operator(window, cx);
2112                }
2113                _ => self.clear_operator(window, cx),
2114            },
2115            Some(Operator::ChangeSurrounds {
2116                target,
2117                opening,
2118                bracket_anchors,
2119            }) => match self.mode {
2120                Mode::Normal => {
2121                    if let Some(target) = target {
2122                        self.change_surrounds(text, target, opening, bracket_anchors, window, cx);
2123                        self.clear_operator(window, cx);
2124                    }
2125                }
2126                _ => self.clear_operator(window, cx),
2127            },
2128            Some(Operator::DeleteSurrounds) => match self.mode {
2129                Mode::Normal => {
2130                    self.delete_surrounds(text, window, cx);
2131                    self.clear_operator(window, cx);
2132                }
2133                _ => self.clear_operator(window, cx),
2134            },
2135            Some(Operator::HelixSurroundAdd) => match self.mode {
2136                Mode::HelixNormal | Mode::HelixSelect => {
2137                    self.update_editor(cx, |_, editor, cx| {
2138                        editor.change_selections(Default::default(), window, cx, |s| {
2139                            s.move_with(&mut |map, selection| {
2140                                if selection.is_empty() {
2141                                    selection.end = movement::right(map, selection.start);
2142                                }
2143                            });
2144                        });
2145                    });
2146                    self.helix_surround_add(&text, window, cx);
2147                    self.switch_mode(Mode::HelixNormal, false, window, cx);
2148                    self.clear_operator(window, cx);
2149                }
2150                _ => self.clear_operator(window, cx),
2151            },
2152            Some(Operator::HelixSurroundReplace {
2153                replaced_char: Some(old),
2154            }) => match self.mode {
2155                Mode::HelixNormal | Mode::HelixSelect => {
2156                    if let Some(new_char) = text.chars().next() {
2157                        self.helix_surround_replace(old, new_char, window, cx);
2158                    }
2159                    self.clear_operator(window, cx);
2160                }
2161                _ => self.clear_operator(window, cx),
2162            },
2163            Some(Operator::HelixSurroundReplace {
2164                replaced_char: None,
2165            }) => match self.mode {
2166                Mode::HelixNormal | Mode::HelixSelect => {
2167                    if let Some(ch) = text.chars().next() {
2168                        self.pop_operator(window, cx);
2169                        self.push_operator(
2170                            Operator::HelixSurroundReplace {
2171                                replaced_char: Some(ch),
2172                            },
2173                            window,
2174                            cx,
2175                        );
2176                    }
2177                }
2178                _ => self.clear_operator(window, cx),
2179            },
2180            Some(Operator::HelixSurroundDelete) => match self.mode {
2181                Mode::HelixNormal | Mode::HelixSelect => {
2182                    if let Some(ch) = text.chars().next() {
2183                        self.helix_surround_delete(ch, window, cx);
2184                    }
2185                    self.clear_operator(window, cx);
2186                }
2187                _ => self.clear_operator(window, cx),
2188            },
2189            Some(Operator::Mark) => self.create_mark(text, window, cx),
2190            Some(Operator::RecordRegister) => {
2191                self.record_register(text.chars().next().unwrap(), window, cx)
2192            }
2193            Some(Operator::ReplayRegister) => {
2194                self.replay_register(text.chars().next().unwrap(), window, cx)
2195            }
2196            Some(Operator::Register) => match self.mode {
2197                Mode::Insert => {
2198                    self.update_editor(cx, |_, editor, cx| {
2199                        if let Some(register) = Vim::update_globals(cx, |globals, cx| {
2200                            globals.read_register(text.chars().next(), Some(editor), cx)
2201                        }) {
2202                            editor.do_paste(
2203                                &register.text.to_string(),
2204                                register.clipboard_selections,
2205                                false,
2206                                window,
2207                                cx,
2208                            )
2209                        }
2210                    });
2211                    self.clear_operator(window, cx);
2212                }
2213                _ => {
2214                    self.select_register(text, window, cx);
2215                }
2216            },
2217            Some(Operator::Jump { line }) => self.jump(text, line, true, window, cx),
2218            _ => {
2219                if self.mode == Mode::Replace {
2220                    self.multi_replace(text, window, cx)
2221                }
2222
2223                if self.mode == Mode::Normal {
2224                    self.update_editor(cx, |_, editor, cx| {
2225                        editor.accept_edit_prediction(
2226                            &editor::actions::AcceptEditPrediction {},
2227                            window,
2228                            cx,
2229                        );
2230                    });
2231                }
2232            }
2233        }
2234    }
2235
2236    fn sync_vim_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2237        let state = self.state_for_editor_settings(cx);
2238        self.update_editor(cx, |_, editor, cx| {
2239            Vim::sync_vim_settings_to_editor(&state, editor, window, cx);
2240        });
2241        cx.notify()
2242    }
2243
2244    fn state_for_editor_settings(&self, cx: &App) -> VimEditorSettingsState {
2245        VimEditorSettingsState {
2246            cursor_shape: self.cursor_shape(cx),
2247            clip_at_line_ends: self.clip_at_line_ends(),
2248            collapse_matches: !HelixModeSetting::get_global(cx).0 && !self.search.cmd_f_search,
2249            input_enabled: self.editor_input_enabled(),
2250            expects_character_input: self.expects_character_input(),
2251            autoindent: self.should_autoindent(),
2252            cursor_offset_on_selection: self.mode.has_selection(),
2253            line_mode: matches!(self.mode, Mode::VisualLine),
2254            hide_edit_predictions: !matches!(self.mode, Mode::Insert | Mode::Replace)
2255                && !(self.mode.is_normal()
2256                    && VimSettings::get_global(cx).show_edit_predictions_in_normal_mode),
2257        }
2258    }
2259
2260    fn sync_vim_settings_to_editor(
2261        state: &VimEditorSettingsState,
2262        editor: &mut Editor,
2263        window: &mut Window,
2264        cx: &mut Context<Editor>,
2265    ) {
2266        editor.set_cursor_shape(state.cursor_shape, cx);
2267        editor.set_clip_at_line_ends(state.clip_at_line_ends, cx);
2268        editor.set_collapse_matches(state.collapse_matches);
2269        editor.set_input_enabled(state.input_enabled);
2270        editor.set_expects_character_input(state.expects_character_input);
2271        editor.set_autoindent(state.autoindent);
2272        editor.set_cursor_offset_on_selection(state.cursor_offset_on_selection);
2273        editor.selections.set_line_mode(state.line_mode);
2274        editor.set_edit_predictions_hidden_for_vim_mode(state.hide_edit_predictions, window, cx);
2275    }
2276
2277    fn set_status_label(&mut self, label: impl Into<SharedString>, cx: &mut Context<Editor>) {
2278        self.status_label = Some(label.into());
2279        cx.notify();
2280    }
2281}
2282
2283struct VimEditorSettingsState {
2284    cursor_shape: CursorShape,
2285    clip_at_line_ends: bool,
2286    collapse_matches: bool,
2287    input_enabled: bool,
2288    expects_character_input: bool,
2289    autoindent: bool,
2290    cursor_offset_on_selection: bool,
2291    line_mode: bool,
2292    hide_edit_predictions: bool,
2293}
2294
2295#[derive(Clone, RegisterSetting)]
2296struct VimSettings {
2297    pub default_mode: Mode,
2298    pub toggle_relative_line_numbers: bool,
2299    pub use_system_clipboard: settings::UseSystemClipboard,
2300    pub use_smartcase_find: bool,
2301    pub use_regex_search: bool,
2302    pub gdefault: bool,
2303    pub custom_digraphs: HashMap<String, Arc<str>>,
2304    pub highlight_on_yank_duration: u64,
2305    pub cursor_shape: CursorShapeSettings,
2306    pub show_edit_predictions_in_normal_mode: bool,
2307}
2308
2309/// Cursor shape configuration for insert mode.
2310#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2311pub enum InsertModeCursorShape {
2312    /// Inherit cursor shape from the editor's base cursor_shape setting.
2313    /// This allows users to set their preferred editor cursor and have
2314    /// it automatically apply to vim insert mode.
2315    Inherit,
2316    /// Use an explicit cursor shape for insert mode.
2317    Explicit(CursorShape),
2318}
2319
2320/// The settings for cursor shape.
2321#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2322pub struct CursorShapeSettings {
2323    /// Cursor shape for the normal mode.
2324    ///
2325    /// Default: block
2326    pub normal: CursorShape,
2327    /// Cursor shape for the replace mode.
2328    ///
2329    /// Default: underline
2330    pub replace: CursorShape,
2331    /// Cursor shape for the visual mode.
2332    ///
2333    /// Default: block
2334    pub visual: CursorShape,
2335    /// Cursor shape for the insert mode.
2336    ///
2337    /// Default: Inherit (follows editor.cursor_shape)
2338    pub insert: InsertModeCursorShape,
2339}
2340
2341impl From<settings::VimInsertModeCursorShape> for InsertModeCursorShape {
2342    fn from(shape: settings::VimInsertModeCursorShape) -> Self {
2343        match shape {
2344            settings::VimInsertModeCursorShape::Inherit => InsertModeCursorShape::Inherit,
2345            settings::VimInsertModeCursorShape::Bar => {
2346                InsertModeCursorShape::Explicit(CursorShape::Bar)
2347            }
2348            settings::VimInsertModeCursorShape::Block => {
2349                InsertModeCursorShape::Explicit(CursorShape::Block)
2350            }
2351            settings::VimInsertModeCursorShape::Underline => {
2352                InsertModeCursorShape::Explicit(CursorShape::Underline)
2353            }
2354            settings::VimInsertModeCursorShape::Hollow => {
2355                InsertModeCursorShape::Explicit(CursorShape::Hollow)
2356            }
2357        }
2358    }
2359}
2360
2361impl From<settings::CursorShapeSettings> for CursorShapeSettings {
2362    fn from(settings: settings::CursorShapeSettings) -> Self {
2363        Self {
2364            normal: settings.normal.unwrap().into(),
2365            replace: settings.replace.unwrap().into(),
2366            visual: settings.visual.unwrap().into(),
2367            insert: settings.insert.unwrap().into(),
2368        }
2369    }
2370}
2371
2372impl From<settings::ModeContent> for Mode {
2373    fn from(mode: ModeContent) -> Self {
2374        match mode {
2375            ModeContent::Normal => Self::Normal,
2376            ModeContent::Insert => Self::Insert,
2377        }
2378    }
2379}
2380
2381impl Settings for VimSettings {
2382    fn from_settings(content: &settings::SettingsContent) -> Self {
2383        let vim = content.vim.clone().unwrap();
2384        Self {
2385            default_mode: vim.default_mode.unwrap().into(),
2386            toggle_relative_line_numbers: vim.toggle_relative_line_numbers.unwrap(),
2387            use_system_clipboard: vim.use_system_clipboard.unwrap(),
2388            use_smartcase_find: vim.use_smartcase_find.unwrap(),
2389            use_regex_search: vim.use_regex_search.unwrap(),
2390            gdefault: vim.gdefault.unwrap(),
2391            custom_digraphs: vim.custom_digraphs.unwrap(),
2392            highlight_on_yank_duration: vim.highlight_on_yank_duration.unwrap(),
2393            cursor_shape: vim.cursor_shape.unwrap().into(),
2394            show_edit_predictions_in_normal_mode: vim.show_edit_predictions_in_normal_mode.unwrap(),
2395        }
2396    }
2397}
2398
Served at tenant.openagents/omega Member data and write actions are omitted.