Debian Codegraph @

debian/rust-vendor/crossterm/examples/copy-to-clipboard.rs

raw
1 //! Demonstrates copying a string to clipboard
2 //!
3 //! This example uses OSC control sequence `Pr = 5 2` (See
4 //! <https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands)>
5 //! to copy data to the terminal host clipboard.
6 //!
7 //! This only works if it is enabled on the respective terminal emulator. If a terminal multiplexer
8 //! is used, the multiplexer will likely need to support it, too.
9 //!
10 //! ```no_run
11 //! cargo run --example copy-to-clipboard -- --clipboard "Some String"
12 //! cargo run --example copy-to-clipboard -- --primary "Some String"
13 //! cargo run --example copy-to-clipboard -- "Some String"
14 //! ```
15
16 use std::io;
17
18 use crossterm::clipboard;
19 use crossterm::execute;
20
21 fn main() -> io::Result<()> {
22 let mut stdout = io::stdout();
23 let mut args = std::env::args();
24 args.next(); // Skip to first argument
25
26 let default_text = String::from("Example text");
27 let (text, dest) = match args.next().as_deref() {
28 Some("--clipboard") => (
29 args.next().unwrap_or(default_text),
30 clipboard::ClipboardType::Clipboard,
31 ),
32 Some("--primary") => (
33 args.next().unwrap_or(default_text),
34 clipboard::ClipboardType::Primary,
35 ),
36 Some(text) => (text.to_owned(), clipboard::ClipboardType::Clipboard),
37 None => (default_text, clipboard::ClipboardType::Clipboard),
38 };
39 execute!(
40 stdout,
41 clipboard::CopyToClipboard {
42 content: text,
43 destination: clipboard::ClipboardSelection(vec![dest])
44 }
45 )
46 }