Skip to content

Commit

Permalink
Merge pull request #1 from johnDeSilencio/bugfix/set-wsl-clipboard-po…
Browse files Browse the repository at this point in the history
…wershell

Use powershell.exe instead of clip.exe to copy to WSL clipboard
  • Loading branch information
rgwood committed Dec 24, 2023
2 parents e94fd0d + cfec3ea commit 6a1d0ff
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 10 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "clipboard-anywhere"
description = "Copy text to the clipboard, even in WSL and SSH sessions"
version = "0.2.2"
version = "0.2.3"
edition = "2021"
authors = ["Reilly Wood"]
repository = "https://github.com/rgwood/clipboard-anywhere"
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

A simple wrapper around [`arboard`](https://github.com/1Password/arboard) that works in a few more situations:

- In Linux under WSL, it can copy to and from the Windows clipboard (using `clip.exe` and `powershell get-clipboard`)
- In Linux under WSL, it can copy to and from the Windows clipboard (using `powershell set-clipboard` and `powershell get-clipboard`)
- In a remote SSH session, can copy to the local clipboard using the OSC 52 control sequence

## Usage
Expand Down
28 changes: 20 additions & 8 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::{
env,
io::Write,
process::{Command, Stdio},
};

Expand Down Expand Up @@ -54,15 +53,28 @@ fn set_clipboard_osc_52(text: &str) {
print!("\x1B]52;c;{}\x07", base64::encode(text));
}

/// Set the Windows clipboard using clip.exe in WSL
/// Set the Windows clipboard using powershell.exe in WSL
fn set_wsl_clipboard(s: &str) -> anyhow::Result<()> {
let mut clipboard = Command::new("clip.exe").stdin(Stdio::piped()).spawn()?;
let mut clipboard_stdin = clipboard
.stdin
.take()
.ok_or_else(|| anyhow::anyhow!("Could not get stdin handle for clip.exe"))?;
// In PowerShell, we can escape literal single-quotes
// in a single-quoted string by doubling them, e.g.
//
// 'hello ''world'''
//
// gets printed as
//
// hello 'world'
let escaped_s = s.replace("'", "''");

clipboard_stdin.write_all(s.as_bytes())?;
let mut powershell = Command::new("powershell.exe")
.arg("-NoProfile")
.arg("-Command")
.arg(&format!("Set-Clipboard -Value '{}'", escaped_s))
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()?;

// Wait until the powershell process is finished before returning
powershell.wait()?;

Ok(())
}

0 comments on commit 6a1d0ff

Please sign in to comment.