Skip to main content

tui/
clipboard.rs

1//! Clipboard copy through the terminal's OSC 52 escape.
2
3use std::fmt;
4
5use base64::prelude::{BASE64_STANDARD, Engine};
6
7/// Largest base64 payload sent; terminals such as xterm drop longer OSC 52 sequences.
8pub const MAX_COPY_BASE64: usize = 100_000;
9
10/// The text was longer than [`MAX_COPY_BASE64`] once encoded.
11#[derive(Debug, PartialEq, Eq)]
12pub struct TooLarge(pub usize);
13
14impl fmt::Display for TooLarge {
15    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16        write!(
17            f,
18            "CSV too large to copy ({} bytes encoded, limit {MAX_COPY_BASE64})",
19            self.0
20        )
21    }
22}
23
24/// The OSC 52 sequence that puts `text` on the clipboard of the terminal reading it.
25///
26/// # Errors
27/// [`TooLarge`] when the encoded text exceeds [`MAX_COPY_BASE64`].
28pub fn osc52(text: &str) -> Result<Vec<u8>, TooLarge> {
29    let encoded = BASE64_STANDARD.encode(text);
30    if encoded.len() > MAX_COPY_BASE64 {
31        return Err(TooLarge(encoded.len()));
32    }
33    Ok(format!("\x1b]52;c;{encoded}\x07").into_bytes())
34}
35
36#[cfg(test)]
37mod tests;