@@ -1,8 +1,13 @@
1use std::{borrow::Cow, collections::HashMap, iter};
1use std::{borrow::Cow, collections::HashMap, iter};
3use anyhow::Result;
3use anyhow::Result;
4+use helix_core::NATIVE_LINE_ENDING;
7+ clipboard::{get_clipboard_provider, ClipboardProvider, ClipboardType},
5−use crate::{document::SCRATCH_BUFFER_NAME, Editor};
8+ document::SCRATCH_BUFFER_NAME,
7/// A key-value store for saving sets of values.
12/// A key-value store for saving sets of values.
@@ -14,9 +19,21 @@ use crate::{document::SCRATCH_BUFFER_NAME, Editor};
14/// * Selection indices (`#`): index number of each selection starting at 1
19/// * Selection indices (`#`): index number of each selection starting at 1
15/// * Selection contents (`.`)
20/// * Selection contents (`.`)
16/// * Document path (`%`): filename of the current buffer
21/// * Document path (`%`): filename of the current buffer
22+/// * System clipboard (`*`)
23+/// * Primary clipboard (`+`)
17−#[derive(Debug, Default)]
24+#[derive(Debug)]
18pub struct Registers {
25pub struct Registers {
19 inner: HashMap<char, Vec<String>>,
26 inner: HashMap<char, Vec<String>>,
27+ clipboard_provider: Box<dyn ClipboardProvider>,
30+impl Default for Registers {
31+ fn default() -> Self {
33+ inner: Default::default(),
34+ clipboard_provider: get_clipboard_provider(),
22impl Registers {
39impl Registers {
@@ -48,6 +65,15 @@ impl Registers {
49 Some(RegisterValues::new(iter::once(path)))
66 Some(RegisterValues::new(iter::once(path)))
68+ '*' | '+' => Some(read_from_clipboard(
69+ self.clipboard_provider.as_ref(),
70+ self.inner.get(&name),
72+ '*' => ClipboardType::Clipboard,
73+ '+' => ClipboardType::Selection,
53 .get(&name)
79 .get(&name)
@@ -59,6 +85,18 @@ impl Registers {
59 match name {
85 match name {
60 '_' => Ok(()),
86 '_' => Ok(()),
61 '#' | '.' | '%' => Err(anyhow::anyhow!("Register {name} does not support writing")),
87 '#' | '.' | '%' => Err(anyhow::anyhow!("Register {name} does not support writing")),
89+ self.clipboard_provider.set_contents(
90+ values.join(NATIVE_LINE_ENDING.as_str()),
92+ '*' => ClipboardType::Clipboard,
93+ '+' => ClipboardType::Selection,
97+ self.inner.insert(name, values);
63 self.inner.insert(name, values);
101 self.inner.insert(name, values);
@@ -70,6 +108,27 @@ impl Registers {
70 match name {
108 match name {
71 '_' => Ok(()),
109 '_' => Ok(()),
72 '#' | '.' | '%' => Err(anyhow::anyhow!("Register {name} does not support pushing")),
110 '#' | '.' | '%' => Err(anyhow::anyhow!("Register {name} does not support pushing")),
112+ let clipboard_type = match name {
113+ '*' => ClipboardType::Clipboard,
114+ '+' => ClipboardType::Selection,
115+ _ => unreachable!(),
117+ let contents = self.clipboard_provider.get_contents(clipboard_type)?;
118+ let saved_values = self.inner.entry(name).or_insert_with(Vec::new);
120+ if !contents_are_saved(saved_values, &contents) {
121+ anyhow::bail!("Failed to push to register {name}: clipboard does not match register contents");
124+ saved_values.push(value);
125+ self.clipboard_provider.set_contents(
126+ saved_values.join(NATIVE_LINE_ENDING.as_str()),
74 self.inner.entry(name).or_insert_with(Vec::new).push(value);
133 self.inner.entry(name).or_insert_with(Vec::new).push(value);
@@ -88,6 +147,7 @@ impl Registers {
88 pub fn iter_preview(&self) -> impl Iterator<Item = (char, &str)> {
147 pub fn iter_preview(&self) -> impl Iterator<Item = (char, &str)> {
89 self.inner
148 self.inner
150+ .filter(|(name, _)| !matches!(name, '*' | '+'))
91 .map(|(name, values)| {
151 .map(|(name, values)| {
92 let preview = values
152 let preview = values
@@ -102,6 +162,8 @@ impl Registers {
102 ('#', "<selection indices>"),
162 ('#', "<selection indices>"),
103 ('.', "<selection contents>"),
163 ('.', "<selection contents>"),
104 ('%', "<document path>"),
164 ('%', "<document path>"),
165+ ('*', "<system clipboard>"),
166+ ('+', "<primary clipboard>"),
107 .copied(),
169 .copied(),
@@ -109,15 +171,97 @@ impl Registers {
111 pub fn clear(&mut self) {
173 pub fn clear(&mut self) {
174+ self.clear_clipboard(ClipboardType::Clipboard);
175+ self.clear_clipboard(ClipboardType::Selection);
112 self.inner.clear()
176 self.inner.clear()
115 pub fn remove(&mut self, name: char) -> bool {
179 pub fn remove(&mut self, name: char) -> bool {
116 match name {
180 match name {
182+ self.clear_clipboard(match name {
183+ '*' => ClipboardType::Clipboard,
184+ '+' => ClipboardType::Selection,
185+ _ => unreachable!(),
187+ self.inner.remove(&name);
117 '_' | '#' | '.' | '%' => false,
191 '_' | '#' | '.' | '%' => false,
118 _ => self.inner.remove(&name).is_some(),
192 _ => self.inner.remove(&name).is_some(),
196+ fn clear_clipboard(&mut self, clipboard_type: ClipboardType) {
197+ if let Err(err) = self
199+ .set_contents("".into(), clipboard_type)
202+ "Failed to clear {} clipboard: {err}",
203+ match clipboard_type {
204+ ClipboardType::Clipboard => "system",
205+ ClipboardType::Selection => "primary",
212+fn read_from_clipboard<'a>(
213+ provider: &dyn ClipboardProvider,
214+ saved_values: Option<&'a Vec<String>>,
215+ clipboard_type: ClipboardType,
216+) -> RegisterValues<'a> {
217+ match provider.get_contents(clipboard_type) {
219+ // If we're pasting the same values that we just yanked, re-use
220+ // the saved values. This allows pasting multiple selections
221+ // even when yanked to a clipboard.
222+ let Some(values) = saved_values else { return RegisterValues::new(iter::once(contents.into())) };
224+ if contents_are_saved(values, &contents) {
225+ RegisterValues::new(values.iter().map(Cow::from))
227+ RegisterValues::new(iter::once(contents.into()))
232+ "Failed to read {} clipboard: {err}",
233+ match clipboard_type {
234+ ClipboardType::Clipboard => "system",
235+ ClipboardType::Selection => "primary",
239+ RegisterValues::new(iter::empty())
244+fn contents_are_saved(saved_values: &[String], mut contents: &str) -> bool {
245+ let line_ending = NATIVE_LINE_ENDING.as_str();
246+ let mut values = saved_values.iter();
248+ match values.next() {
249+ Some(first) if contents.starts_with(first) => {
250+ contents = &contents[first.len()..];
252+ None if contents.is_empty() => return true,
256+ for value in values {
257+ if contents.starts_with(line_ending) && contents[line_ending.len()..].starts_with(value) {
258+ contents = &contents[line_ending.len() + value.len()..];
123// This is a wrapper of an iterator that is both double ended and exact size,
267// This is a wrapper of an iterator that is both double ended and exact size,