vim: Fix cursor placement after switching to Helix normal mode with a multi-key binding (#62080)

# Objective

Closes #41744

When a multi-key binding switches from Insert mode to Helix normal mode,
subsequent editing actions can place the cursor incorrectly.

While a printable multi-key binding is pending, Zed temporarily inserts
the pending keys into the buffer. Once the binding is matched, Zed
dispatches the associated action and then deletes the pending text.
Because the buffer uses a CRDT, the deleted text remains as tombstoned
fragments. The cursor can still resolve to the correct visible offset
while its selection anchor remains associated with one of those
fragments, affecting the ordering of subsequent edits.

Among the explicit Vim mode-switch actions, `SwitchToHelixNormalMode` is
the only one that preserves the existing selections:


https://github.com/zed-industries/zed/blob/377382e1966caee4bd829dea2b106c4ab2897045/crates/vim/src/vim.rs#L713-L719

As a result, the tombstone-associated anchor is carried into Helix
normal mode, where later actions such as `o` can place the cursor on the
wrong side of the inserted newline.

The affected path is narrow: a multi-key binding must invoke
`SwitchToHelixNormalMode` from Insert mode. This creates pending text
and then preserves the resulting selection anchors when entering Helix
normal mode.

There are two possible layers at which to address this. At the Editor
layer, selections could be refreshed whenever pending text is removed so
that they no longer reference deleted fragments. At the Vim layer, the
Helix mode transition can explicitly guard against preserving those
anchors.

PR #50918 attempted the broader Editor-layer solution by refreshing
selections after resolving a multi-key binding. However, as discussed in
this review comment:
https://github.com/zed-industries/zed/pull/50918#issuecomment-4411319469,
the more appropriate scope for this reported issue is the Vim
mode-switching layer.

## Solution

Based on PR #50918 and its review feedback, this PR limits the fix to
`SwitchToHelixNormalMode`.

When that action is triggered by pending Insert-mode keystrokes, Vim
refreshes the preserved selection anchors after the pending text is
removed. This keeps the fix scoped to the affected Helix transition
without changing other multi-key bindings.

## Testing

Added a GPUI regression test.

## Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content adheres to Zed's UI standards
([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
and
[icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md)
guidelines)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

---

Release Notes:

- Fixed incorrect cursor placement after using a multi-key binding to
leave insert mode in Vim or Helix mode.

---------

Co-authored-by: dino <dinojoaocosta@gmail.com>
This commit is contained in:
Xin Zhaoanddino authored and GitHub committed 2026-08-05 11:03:09 +00:00
1 parent 0be6469dd7
commit ffd8a6d0d4
4 files changed
+74 -2

No files matched your search

+19
View File
@@ -87,6 +87,25 @@ impl Editor {
result
}
/// Re-resolves selection anchors so they reference live buffer fragments.
///
/// Deleted CRDT fragments remain as tombstones. An anchor associated with a
/// tombstone can resolve to the correct visible offset while causing later
/// insertions to be ordered on the wrong side of the cursor. Round-tripping
/// selections through their offsets creates fresh anchors associated with
/// live fragments.
///
/// This does not emit selection effects, but it replaces pending selection
/// state with the resolved selections.
pub fn refresh_selection_anchors(&mut self, cx: &mut Context<Self>) {
let snapshot = self.display_snapshot(cx);
let selections = self.selections.all::<MultiBufferOffset>(&snapshot);
self.selections
.change_with(&snapshot, |selection_collection| {
selection_collection.select(selections);
});
}
/// Defers the effects of selection change, so that the effects of multiple calls to
/// `change_selections` are applied at the end. This way these intermediate states aren't added
/// to selection history and the state of popovers based on selection position aren't
+21 -1
View File
@@ -1882,7 +1882,7 @@ mod test {
use super::{HELIX_JUMP_LABEL_LIMIT, HelixJumpToWord};
use crate::{
HELIX_JUMP_OVERLAY_KEY, Vim, VimAddon,
HELIX_JUMP_OVERLAY_KEY, SwitchToHelixNormalMode, Vim, VimAddon,
state::{Mode, Operator},
test::VimTestContext,
};
@@ -4671,4 +4671,24 @@ mod test {
cx.simulate_keystrokes("x");
cx.assert_state("« aa \nˇ»bbb\nccc\n", Mode::HelixNormal);
}
#[gpui::test]
async fn test_insert_line_with_multi_keybinding_to_helix_normal(cx: &mut gpui::TestAppContext) {
let mut cx = VimTestContext::new(cx, true).await;
cx.enable_helix();
cx.update(|_, cx| {
cx.bind_keys([KeyBinding::new(
"j j",
SwitchToHelixNormalMode,
Some("vim_mode == insert"),
)]);
});
cx.set_state("hello worldˇ\n", Mode::Insert);
cx.simulate_keystrokes("j j");
cx.assert_state("hello worldˇ\n", Mode::HelixNormal);
cx.simulate_keystrokes("o");
cx.assert_state("hello world\nˇ\n", Mode::Insert);
}
}
+23 -1
View File
@@ -35,7 +35,10 @@ use serde_json::json;
use workspace::notifications::{NotificationId, simple_message_notification::MessageNotification};
use workspace::{DeploySearch, MultiWorkspace};
use crate::{PushSneak, PushSneakBackward, VimAddon, insert::NormalBefore, motion, state::Mode};
use crate::{
PushSneak, PushSneakBackward, SwitchToNormalMode, VimAddon, insert::NormalBefore, motion,
state::Mode,
};
use util_macros::perf;
@@ -387,6 +390,25 @@ async fn test_escape_cancels(cx: &mut gpui::TestAppContext) {
cx.assert_state("aˇbc", Mode::Normal);
}
#[gpui::test]
async fn test_insert_line_with_multi_keybinding_to_normal(cx: &mut gpui::TestAppContext) {
let mut cx = VimTestContext::new(cx, true).await;
cx.update(|_, cx| {
cx.bind_keys([KeyBinding::new(
"j j",
SwitchToNormalMode,
Some("vim_mode == insert"),
)]);
});
cx.set_state("hello worldˇ\n", Mode::Insert);
cx.simulate_keystrokes("j j");
cx.assert_state("hello worldˇ\n", Mode::Normal);
cx.simulate_keystrokes("o");
cx.assert_state("hello world\nˇ\n", Mode::Insert);
}
#[cfg(target_os = "windows")]
#[gpui::test]
async fn test_escape_dismisses_workspace_notification_in_normal_modes(
+11
View File
@@ -1266,6 +1266,17 @@ impl Vim {
}
}
// Multi-key bindings in Insert mode temporarily insert their pending keys
// and remove them only after the action runs. Refresh the selection anchors
// afterward so they re-attach to the remaining text.
if last_mode == Mode::Insert && matches!(self.mode, Mode::Normal | Mode::HelixNormal) {
cx.defer_in(window, |vim, _window, cx| {
vim.update_editor(cx, |_, editor, cx| {
editor.refresh_selection_anchors(cx);
});
})
}
if leave_selections {
return;
}