diff --git a/Cargo.lock b/Cargo.lock index aecf0d4758..43a00c8308 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -461,6 +461,7 @@ dependencies = [ "textwrap 0.12.1", "tui", "unicode-width", + "which", ] [[package]] @@ -1357,6 +1358,16 @@ version = "0.9.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" +[[package]] +name = "which" +version = "4.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87c14ef7e1b8b8ecfc75d5eca37949410046e66f15d185c01d70824f1f8111ef" +dependencies = [ + "libc", + "thiserror", +] + [[package]] name = "winapi" version = "0.3.9" diff --git a/Cargo.toml b/Cargo.toml index d346ca4010..5cc2a80101 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,6 +41,9 @@ anyhow = "1.0.33" unicode-width = "0.1" textwrap = "0.12" +[target.'cfg(target_os = "linux")'.dependencies] +which = "4.0.2" + [target.'cfg(not(windows))'.dependencies] pprof = { version = "0.3", features = ["flamegraph"], optional = true } diff --git a/src/clipboard.rs b/src/clipboard.rs index 6730ceb1ba..5f15e11f76 100644 --- a/src/clipboard.rs +++ b/src/clipboard.rs @@ -1,4 +1,5 @@ use anyhow::Result; +use std::ffi::OsStr; use std::io::Write; use std::process::{Command, Stdio}; @@ -27,10 +28,37 @@ fn execute_copy_command(command: Command, text: &str) -> Result<()> { Ok(()) } +fn gen_command( + path: impl AsRef<OsStr>, + xclip_syntax: bool, +) -> Command { + let mut c = Command::new(path); + if xclip_syntax { + c.arg("-selection"); + c.arg("clipboard"); + } else { + c.arg("--clipboard"); + } + c +} + #[cfg(target_os = "linux")] pub fn copy_string(string: &str) -> Result<()> { - let mut cmd = Command::new("xclip"); - cmd.arg("-selection").arg("clipboard"); + use std::path::PathBuf; + use which::which; + let (path, xclip_syntax) = which("xclip").ok().map_or_else( + || { + ( + which("xsel") + .ok() + .unwrap_or_else(|| PathBuf::from("xsel")), + false, + ) + }, + |path| (path, true), + ); + + let cmd = gen_command(path, xclip_syntax); execute_copy_command(cmd, string) }