Skip to main content

uncurses/ansi/
clipboard.rs

1//! Clipboard and selection access through OSC 52.
2//!
3//! ## Category
4//!
5//! OSC 52 sets, requests, or clears named clipboards/selections. This module
6//! provides the common system clipboard (`c`) and primary selection (`p`) selector
7//! bytes plus writers for each operation.
8//!
9//! ## OSC framing
10//!
11//! The emitted sequences use 7-bit OSC with BEL termination:
12//!
13//! ```text
14//! ESC ] 52 ; c ; aGk= BEL
15//! ──┬── ┬─   ┬   ─┬─  ─┬─
16//!  OSC code  Pc  base64 terminator
17//! ```
18//!
19//! Clipboard data is base64-encoded by [`write_set_clipboard`]. Request and
20//! clear operations use `?` or an empty payload in the same field.
21//!
22//! ## Mode interaction
23//!
24//! OSC 52 is not gated by an ANSI/DEC mode. Terminals may still reject clipboard
25//! access by policy; this module only encodes the request bytes.
26
27use std::io::{self, Write};
28
29use base64::Engine as _;
30use base64::engine::general_purpose::STANDARD;
31
32/// OSC 52 selector byte `c` for the system clipboard.
33pub const SYSTEM_CLIPBOARD: u8 = b'c';
34
35/// OSC 52 selector byte `p` for the primary selection.
36pub const PRIMARY_CLIPBOARD: u8 = b'p';
37
38/// Set a clipboard or selection with `ESC ] 52 ; <pc> ; <base64-data> BEL`.
39///
40/// `pc` is a selector such as [`SYSTEM_CLIPBOARD`] or [`PRIMARY_CLIPBOARD`]. `data` is base64-encoded by this function before it is emitted.
41pub fn write_set_clipboard<W: Write>(w: &mut W, pc: u8, data: &[u8]) -> io::Result<()> {
42    let encoded = STANDARD.encode(data);
43    write!(w, "\x1b]52;{};{}\x07", pc as char, encoded)
44}
45
46/// Request clipboard contents with `ESC ] 52 ; <pc> ; ? BEL`.
47///
48/// `pc` is written as a single selector character. Replies, when allowed by terminal policy, arrive asynchronously as OSC 52 data.
49pub fn write_request_clipboard<W: Write>(w: &mut W, pc: u8) -> io::Result<()> {
50    write!(w, "\x1b]52;{};?\x07", pc as char)
51}
52
53/// Clear a clipboard or selection with `ESC ] 52 ; <pc> ; BEL`.
54///
55/// The payload field is intentionally empty; `pc` selects which clipboard or selection to clear.
56pub fn write_clear_clipboard<W: Write>(w: &mut W, pc: u8) -> io::Result<()> {
57    write!(w, "\x1b]52;{};\x07", pc as char)
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63
64    #[test]
65    fn test_set_clipboard() {
66        let mut buf = Vec::new();
67        write_set_clipboard(&mut buf, SYSTEM_CLIPBOARD, b"hi").unwrap();
68        assert_eq!(buf, b"\x1b]52;c;aGk=\x07");
69    }
70
71    #[test]
72    fn test_request_clipboard() {
73        let mut buf = Vec::new();
74        write_request_clipboard(&mut buf, PRIMARY_CLIPBOARD).unwrap();
75        assert_eq!(buf, b"\x1b]52;p;?\x07");
76    }
77}