Lines
100 %
Functions
50 %
Branches
//! Clipboard copy through the terminal's OSC 52 escape.
use std::fmt;
use base64::prelude::{BASE64_STANDARD, Engine};
/// Largest base64 payload sent; terminals such as xterm drop longer OSC 52 sequences.
pub const MAX_COPY_BASE64: usize = 100_000;
/// The text was longer than [`MAX_COPY_BASE64`] once encoded.
#[derive(Debug, PartialEq, Eq)]
pub struct TooLarge(pub usize);
impl fmt::Display for TooLarge {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"CSV too large to copy ({} bytes encoded, limit {MAX_COPY_BASE64})",
self.0
)
}
/// The OSC 52 sequence that puts `text` on the clipboard of the terminal reading it.
///
/// # Errors
/// [`TooLarge`] when the encoded text exceeds [`MAX_COPY_BASE64`].
pub fn osc52(text: &str) -> Result<Vec<u8>, TooLarge> {
let encoded = BASE64_STANDARD.encode(text);
if encoded.len() > MAX_COPY_BASE64 {
return Err(TooLarge(encoded.len()));
Ok(format!("\x1b]52;c;{encoded}\x07").into_bytes())
#[cfg(test)]
mod tests;