Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

helix: Fix system clipboard clobbering (#55455)

Gabriel28917a970d2c
diff --git a/assets/keymaps/vim.json b/assets/keymaps/vim.json
index 9c765b2aa92..d35f0fbc34b 100644
--- a/assets/keymaps/vim.json
+++ b/assets/keymaps/vim.json
@@ -474,7 +474,7 @@
"shift-g": "vim::HelixGotoLine",
// Changes
- "shift-r": "editor::Paste",
+ "shift-r": "vim::HelixReplaceWithYanked",
"`": "vim::ConvertToLowerCase",
"alt-`": "vim::ConvertToUpperCase",
"insert": "vim::InsertBefore", // not a helix default
diff --git a/crates/vim/src/helix.rs b/crates/vim/src/helix.rs
index eacc807a01d..545441677c0 100644
--- a/crates/vim/src/helix.rs
+++ b/crates/vim/src/helix.rs
@@ -5,7 +5,7 @@ mod paste;
mod select;
mod surround;
-use editor::display_map::{DisplayRow, DisplaySnapshot};
+use editor::display_map::{DisplayRow, DisplaySnapshot, ToDisplayPoint};
use editor::{
DisplayPoint, Editor, EditorSettings, MultiBufferOffset, NavigationOverlayLabel,
NavigationTargetOverlay, SelectionEffects, ToOffset, ToPoint, movement,
@@ -59,6 +59,8 @@ actions!(
HelixSubstitute,
/// Delete the selection and enter edit mode, without yanking the selection.
HelixSubstituteNoYank,
+ /// Replace the selection with the contents of the default register (`R`).
+ HelixReplaceWithYanked,
/// Activate Helix-style word jump labels.
HelixJumpToWord,
/// Select the next match for the current search query.
@@ -80,6 +82,7 @@ pub fn register(editor: &mut Editor, cx: &mut Context<Vim>) {
Vim::action(editor, cx, Vim::helix_goto_last_modification);
Vim::action(editor, cx, Vim::helix_goto_line);
Vim::action(editor, cx, Vim::helix_paste);
+ Vim::action(editor, cx, Vim::helix_replace_with_yanked);
Vim::action(editor, cx, Vim::helix_select_regex);
Vim::action(editor, cx, Vim::helix_keep_newest_selection);
Vim::action(editor, cx, |vim, _: &HelixDuplicateBelow, window, cx| {
@@ -787,6 +790,63 @@ impl Vim {
});
}
+ /// Replace each selection with the contents of the default
+ /// register (or an explicitly selected register)
+ pub fn helix_replace_with_yanked(
+ &mut self,
+ _: &HelixReplaceWithYanked,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.record_current_action(cx);
+ self.update_editor(cx, |vim, editor, cx| {
+ if editor.read_only(cx) {
+ return;
+ }
+ let selected_register = vim.selected_register.take();
+ let Some(register) = Vim::update_globals(cx, |globals, cx| {
+ globals.read_register(selected_register, Some(editor), cx)
+ })
+ .filter(|reg| !reg.text.is_empty()) else {
+ return;
+ };
+
+ editor.transact(window, cx, |editor, window, cx| {
+ editor.set_clip_at_line_ends(false, cx);
+ let display_map = editor.display_snapshot(cx);
+ let selections = editor.selections.all_adjusted(&display_map);
+ let replacement_texts = paste::replacement_texts(register, selections.len());
+
+ let snapshot = display_map.buffer_snapshot();
+ let mut edits = Vec::with_capacity(selections.len());
+ let mut new_anchors = Vec::with_capacity(selections.len());
+ for (selection, mut text) in selections.iter().zip(replacement_texts) {
+ LineEnding::normalize(&mut text);
+ let mut range = selection.start..selection.end;
+ if range.is_empty() {
+ range.end = movement::saturating_right(
+ &display_map,
+ range.end.to_display_point(&display_map),
+ )
+ .to_point(&display_map);
+ }
+ new_anchors.push((snapshot.anchor_before(range.start), text.len()));
+ edits.push((range, text));
+ }
+ editor.edit(edits, cx);
+
+ let snapshot = editor.buffer().read(cx).snapshot(cx);
+ editor.change_selections(Default::default(), window, cx, |s| {
+ s.select_ranges(new_anchors.into_iter().map(|(anchor, length)| {
+ let start = anchor.to_offset(&snapshot);
+ start..start + length
+ }));
+ });
+ });
+ });
+ self.switch_mode(Mode::HelixNormal, true, window, cx);
+ }
+
pub fn helix_replace(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
self.update_editor(cx, |_, editor, cx| {
editor.transact(window, cx, |editor, window, cx| {
@@ -2791,61 +2851,138 @@ mod test {
let mut cx = VimTestContext::new(cx, true).await;
cx.enable_helix();
- // Test yanking current character with no selection
+ cx.write_to_clipboard(gpui::ClipboardItem::new_string("external".into()));
+
+ // Test yanking a single character (no explicit selection) should not clobber the system clipboard
cx.set_state("hello ˇworld", Mode::HelixNormal);
cx.simulate_keystrokes("y");
-
- // Test cursor remains at the same position after yanking single character
cx.assert_state("hello ˇworld", Mode::HelixNormal);
- cx.shared_clipboard().assert_eq("w");
+ cx.shared_clipboard().assert_eq("external");
+ cx.simulate_keystrokes("l p");
+ cx.assert_state("hello wo«wˇ»rld", Mode::HelixNormal);
- // Move cursor and yank another character
- cx.simulate_keystrokes("l");
- cx.simulate_keystrokes("y");
- cx.shared_clipboard().assert_eq("o");
-
- // Test yanking with existing selection
+ // Test yanking a multi-char selection
cx.set_state("hello «worlˇ»d", Mode::HelixNormal);
cx.simulate_keystrokes("y");
- cx.shared_clipboard().assert_eq("worl");
+ cx.shared_clipboard().assert_eq("external");
cx.assert_state("hello «worlˇ»d", Mode::HelixNormal);
-
- // Test yanking in select mode character by character
- cx.set_state("hello ˇworld", Mode::HelixNormal);
- cx.simulate_keystroke("v");
- cx.assert_state("hello «wˇ»orld", Mode::HelixSelect);
- cx.simulate_keystroke("y");
- cx.assert_state("hello «wˇ»orld", Mode::HelixNormal);
- cx.shared_clipboard().assert_eq("w");
}
#[gpui::test]
- async fn test_shift_r_paste(cx: &mut gpui::TestAppContext) {
+ async fn test_shift_r_replace_with_yanked(cx: &mut gpui::TestAppContext) {
let mut cx = VimTestContext::new(cx, true).await;
cx.enable_helix();
- // First copy some text to clipboard
+ // External clipboard content is irrelevant
+ cx.write_to_clipboard(gpui::ClipboardItem::new_string("external".into()));
+
cx.set_state("«hello worldˇ»", Mode::HelixNormal);
cx.simulate_keystrokes("y");
- // Test paste with shift-r on single cursor
+ // Test bare cursor
cx.set_state("foo ˇbar", Mode::HelixNormal);
cx.simulate_keystrokes("shift-r");
-
- cx.assert_state("foo hello worldˇbar", Mode::HelixNormal);
+ cx.assert_state("foo «hello worldˇ»ar", Mode::HelixNormal);
// Test paste with shift-r on selection from Helix Normal Mode
cx.set_state("foo «barˇ» baz", Mode::HelixNormal);
cx.simulate_keystrokes("shift-r");
- cx.assert_state("foo hello worldˇ baz", Mode::HelixNormal);
+ cx.assert_state("foo «hello worldˇ» baz", Mode::HelixNormal);
// Test shift-r paste on selection from Helix Select Mode returns to Helix Normal Mode
cx.set_state("foo «barˇ» baz fizz", Mode::HelixSelect);
cx.simulate_keystrokes("e"); // if we're in Select Mode, the selection should be extended to include ` baz`
cx.simulate_keystrokes("shift-r");
- cx.assert_state("foo hello worldˇ fizz", Mode::HelixNormal);
+ cx.assert_state("foo «hello worldˇ» fizz", Mode::HelixNormal);
+
+ cx.set_state("«fooˇ» «barˇ»", Mode::HelixNormal);
+ cx.simulate_keystrokes("y");
+ for (before, after) in [
+ ("«oneˇ» «twoˇ» «threeˇ»", "«fooˇ» «barˇ» «barˇ»"),
+ ("«oneˇ»", "«fooˇ»"),
+ ] {
+ cx.set_state(before, Mode::HelixNormal);
+ cx.simulate_keystrokes("shift-r");
+ cx.assert_state(after, Mode::HelixNormal);
+ }
+ }
+
+ #[gpui::test]
+ async fn test_helix_delete_registers(cx: &mut gpui::TestAppContext) {
+ let mut cx = VimTestContext::new(cx, true).await;
+ cx.enable_helix();
+ cx.write_to_clipboard(gpui::ClipboardItem::new_string("external".into()));
+
+ cx.set_state("«yankedˇ»", Mode::HelixNormal);
+ cx.simulate_keystrokes("y");
+ for action in ["d", "c escape"] {
+ cx.set_state("«deletedˇ»", Mode::HelixNormal);
+ cx.simulate_keystrokes(action);
+ cx.shared_clipboard().assert_eq("external");
+
+ cx.set_state("ˇ", Mode::HelixNormal);
+ cx.simulate_keystrokes("\" 0 p");
+ cx.assert_state("«yankedˇ»", Mode::HelixNormal);
+ cx.set_state("ˇ", Mode::HelixNormal);
+ cx.simulate_keystrokes("\" - p");
+ cx.assert_state("«deletedˇ»", Mode::HelixNormal);
+ }
+
+ cx.set_state("«first\nˇ»second", Mode::HelixNormal);
+ cx.simulate_keystrokes("d");
+ cx.set_state("«second\nˇ»third", Mode::HelixNormal);
+ cx.simulate_keystrokes("d");
+ cx.set_state("ˇ", Mode::HelixNormal);
+ cx.simulate_keystrokes("\" 1 p");
+ cx.assert_state("«second\nˇ»", Mode::HelixNormal);
+ cx.set_state("ˇ", Mode::HelixNormal);
+ cx.simulate_keystrokes("\" 2 p");
+ cx.assert_state("«first\nˇ»", Mode::HelixNormal);
+ cx.shared_clipboard().assert_eq("external");
+
+ cx.set_state("ˇ\nsecond line", Mode::HelixNormal);
+ cx.simulate_keystrokes("d");
+ cx.shared_clipboard().assert_eq("external");
+ }
+
+ #[gpui::test]
+ async fn test_helix_explicit_registers(cx: &mut gpui::TestAppContext) {
+ let mut cx = VimTestContext::new(cx, true).await;
+ cx.enable_helix();
+ cx.write_to_clipboard(gpui::ClipboardItem::new_string("external".into()));
+ cx.set_state("«internalˇ»", Mode::HelixNormal);
+ cx.simulate_keystrokes("y");
+
+ for action in ["p", "\" \" p", "shift-r", "\" \" shift-r"] {
+ cx.set_state("ˇ", Mode::HelixNormal);
+ cx.simulate_keystrokes(action);
+ cx.assert_state("«internalˇ»", Mode::HelixNormal);
+ cx.shared_clipboard().assert_eq("external");
+ }
+ cx.set_state("«namedˇ»", Mode::HelixNormal);
+ cx.simulate_keystrokes("\" a y");
+ cx.set_state("ˇ", Mode::HelixNormal);
+ cx.simulate_keystrokes("\" a shift-r");
+ cx.assert_state("«namedˇ»", Mode::HelixNormal);
+ cx.shared_clipboard().assert_eq("external");
+
+ cx.set_state("«exportedˇ»", Mode::HelixNormal);
+ cx.simulate_keystrokes("\" + y");
+ cx.shared_clipboard().assert_eq("exported");
+
+ cx.write_to_clipboard(gpui::ClipboardItem::new_string("a\r\nb".into()));
+ for (before, action) in [("ˇz", "\" + shift-p"), ("«xˇ»z", "\" + shift-r")] {
+ cx.set_state(before, Mode::HelixNormal);
+ cx.simulate_keystrokes(action);
+ cx.assert_state("«a\nbˇ»z", Mode::HelixNormal);
+ }
+
+ cx.set_state("«xˇ»z", Mode::HelixNormal);
+ cx.update_editor(|editor, _window, _cx| editor.set_read_only(true));
+ cx.simulate_keystrokes("\" + shift-r");
+ cx.assert_state("«xˇ»z", Mode::HelixNormal);
}
#[gpui::test]
diff --git a/crates/vim/src/helix/paste.rs b/crates/vim/src/helix/paste.rs
index 17b325a4200..53545ac2d02 100644
--- a/crates/vim/src/helix/paste.rs
+++ b/crates/vim/src/helix/paste.rs
@@ -3,7 +3,10 @@ use gpui::{Action, Context, Window};
use schemars::JsonSchema;
use serde::Deserialize;
-use crate::{Vim, state::Mode};
+use crate::{
+ Vim,
+ state::{Mode, Register},
+};
/// Pastes text from the specified register at the cursor position.
#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
@@ -14,6 +17,36 @@ pub struct HelixPaste {
before: bool,
}
+pub(super) fn replacement_texts(register: Register, selection_count: usize) -> Vec<String> {
+ let text = register.text;
+ let clipboard_selections = register.clipboard_selections;
+ let mut replacement_texts: Vec<String> = Vec::with_capacity(selection_count);
+ let mut start_offset = 0;
+
+ for index in 0..selection_count {
+ let to_insert = if let Some(clipboard_selection) = clipboard_selections
+ .as_ref()
+ .and_then(|selections| selections.get(index))
+ {
+ let end_offset = start_offset + clipboard_selection.len;
+ let text = text[start_offset..end_offset].to_string();
+ start_offset = if clipboard_selection.is_entire_line {
+ end_offset
+ } else {
+ end_offset + 1
+ };
+ text
+ } else if let Some(last_text) = replacement_texts.last() {
+ last_text.to_owned()
+ } else {
+ text.to_string()
+ };
+ replacement_texts.push(to_insert);
+ }
+
+ replacement_texts
+}
+
impl Vim {
pub fn helix_paste(
&mut self,
@@ -43,8 +76,6 @@ impl Vim {
.filter(|reg| !reg.text.is_empty()) else {
return;
};
- let text = register.text;
- let clipboard_selections = register.clipboard_selections;
let display_map = editor.display_snapshot(cx);
let current_selections = editor.selections.all_adjusted_display(&display_map);
@@ -60,30 +91,7 @@ impl Vim {
let mut edits = Vec::new();
let mut new_selections = Vec::new();
- let mut start_offset = 0;
-
- let mut replacement_texts: Vec<String> = Vec::new();
-
- for ix in 0..current_selections.len() {
- let to_insert = if let Some(clip_sel) =
- clipboard_selections.as_ref().and_then(|s| s.get(ix))
- {
- let end_offset = start_offset + clip_sel.len;
- let text = text[start_offset..end_offset].to_string();
- start_offset = if clip_sel.is_entire_line {
- end_offset
- } else {
- end_offset + 1
- };
- text
- } else if let Some(last_text) = replacement_texts.last() {
- // We have more current selections than clipboard selections: repeat the last one.
- last_text.to_owned()
- } else {
- text.to_string()
- };
- replacement_texts.push(to_insert);
- }
+ let replacement_texts = replacement_texts(register, current_selections.len());
let line_mode = replacement_texts.iter().any(|text| text.ends_with('\n'));
@@ -147,7 +155,7 @@ mod test {
use crate::{state::Mode, test::VimTestContext};
#[gpui::test]
- async fn test_system_clipboard_paste(cx: &mut gpui::TestAppContext) {
+ async fn test_helix_paste_ignores_system_clipboard(cx: &mut gpui::TestAppContext) {
let mut cx = VimTestContext::new(cx, true).await;
cx.enable_helix();
cx.set_state(
@@ -162,36 +170,11 @@ mod test {
cx.simulate_keystrokes("p");
cx.assert_state(
indoc! {"
- The quic«clipboardˇ»k brown
+ The quiˇck brown
fox jumps over
the lazy dog."},
Mode::HelixNormal,
);
-
- // Multiple cursors with system clipboard (no metadata) pastes
- // the same text at each cursor.
- cx.set_state(
- indoc! {"
- ˇThe quick brown
- fox ˇjumps over
- the lazy dog."},
- Mode::HelixNormal,
- );
- cx.write_to_clipboard(ClipboardItem::new_string("hi".to_string()));
- cx.simulate_keystrokes("p");
- cx.assert_state(
- indoc! {"
- T«hiˇ»he quick brown
- fox j«hiˇ»umps over
- the lazy dog."},
- Mode::HelixNormal,
- );
-
- // Multiple cursors on empty lines should paste on those same lines.
- cx.set_state("ˇ\nˇ\nˇ\nend", Mode::HelixNormal);
- cx.write_to_clipboard(ClipboardItem::new_string("X".to_string()));
- cx.simulate_keystrokes("p");
- cx.assert_state("«Xˇ»\n«Xˇ»\n«Xˇ»\nend", Mode::HelixNormal);
}
#[gpui::test]
@@ -201,7 +184,7 @@ mod test {
cx.set_state("ˇ", Mode::HelixNormal);
cx.write_to_clipboard(ClipboardItem::new_string("a\r\nb".to_string()));
- cx.simulate_keystrokes("p");
+ cx.simulate_keystrokes("\" + p");
cx.assert_state("«a\nbˇ»", Mode::HelixNormal);
}
diff --git a/crates/vim/src/state.rs b/crates/vim/src/state.rs
index 45a08567adc..649aea5425b 100644
--- a/crates/vim/src/state.rs
+++ b/crates/vim/src/state.rs
@@ -37,6 +37,7 @@ use ui::{
};
use util::ResultExt;
use util::rel_path::RelPath;
+use vim_mode_setting::HelixModeSetting;
use workspace::searchable::Direction;
use workspace::{MultiWorkspace, Workspace, WorkspaceDb, WorkspaceId};
@@ -873,7 +874,7 @@ impl VimGlobals {
}
}
} else {
- let setting = VimSettings::get_global(cx).use_system_clipboard;
+ let setting = Self::default_register_clipboard_policy(cx);
if setting == UseSystemClipboard::Always
|| setting == UseSystemClipboard::OnYank && is_yank
{
@@ -906,6 +907,14 @@ impl VimGlobals {
}
}
+ fn default_register_clipboard_policy(cx: &App) -> UseSystemClipboard {
+ if HelixModeSetting::get_global(cx).0 {
+ UseSystemClipboard::Never
+ } else {
+ VimSettings::get_global(cx).use_system_clipboard
+ }
+ }
+
pub(crate) fn read_register(
&self,
register: Option<char>,
@@ -913,7 +922,7 @@ impl VimGlobals {
cx: &mut App,
) -> Option<Register> {
let Some(register) = register.filter(|reg| *reg != '"') else {
- let setting = VimSettings::get_global(cx).use_system_clipboard;
+ let setting = Self::default_register_clipboard_policy(cx);
return match setting {
UseSystemClipboard::Always => cx.read_from_clipboard().map(|item| item.into()),
UseSystemClipboard::OnYank if self.system_clipboard_is_newer(cx) => {