Skip to content

Instantly share code, notes, and snippets.

@disco0
Forked from vor0nwe/clip
Last active March 27, 2021 19:50
Show Gist options
  • Save disco0/d9b7d600bd4b2f29b6f671b7ea81f902 to your computer and use it in GitHub Desktop.
Save disco0/d9b7d600bd4b2f29b6f671b7ea81f902 to your computer and use it in GitHub Desktop.
clip: WSL zsh script to both read and write to the Windows Clipboard
#!/usr/bin/env zsh
# Drop in xclip replacement for WSL
builtin emulate zsh -L
zparseopts -E -D -- {-help,h}=OPT_HELP {i,-in}=OPT_IN {o,-o}=OPT_OUT
local cmd=${0}
function xclip-help()
{
# Cribbed sytax from win32yank
local -a lines=(
"Usage:"
" ${cmd:t} [-o|--out]"
" ${cmd:t} | <command>"
""
" ${cmd:t} [-i|--in]"
" <command> | ${cmd:t}"
" ${cmd:t} < <command>"
)
builtin print -l -u2 -- "${(@)^lines}"
}
if (( $#OPT_HELP ))
then
xclip-help
return 0
fi
#section Paste
if (( $#OPT_OUT )) || [[ ! -t 1 ]]
then
# Resolve best paste command
local resolved
#section Paste - win32yank
resolved="${commands[(i)win32yank(|.exe)]}"
if [[ -n $resolved ]]
then
command =$resolved -o --lf 2>/dev/null
return $?
fi
#section Paste - PowerShell
# Parameter expansion gets best available powershell executable
resolved="${commands[(i)p(wsh|owershell).exe]}"
if [[ -n $resolved ]]
then
command =$resolved -No{Profile,nInteractive,Logo} -Command 'Get-Clipboard' 2>/dev/null
return $?
fi
builtin print -u2 "Failed to resolve paste command."
xclip-help
fi
#section Copy
if (( $#OPT_IN )) || [[ ! -t 0 ]]
then
# Resolve best copy command
local resolved
#section Copy - win32yank.exe
resolved="${commands[(i)win32yank(|.exe)]}"
if [[ -n $resolved ]]
then
command =$resolved -i < "${1:-/dev/stdin}"
return $?
fi
#section Copy - clip.exe
resolved="${commands[(i)clip(|.exe)]}"
if [[ -n $resolved ]]
then
command =$resolved < "${1:-/dev/stdin}"
return $?
fi
builtin print -u2 "Failed to resolve copy command."
xclip-help
fi
builtin print -l -u2 -- "Invalid Arguments.\n"
xclip-help
return 1
@disco0
Copy link
Author

disco0 commented Mar 27, 2021

pwsh.exe is noticeably faster:

local TIMEFMT="%mE"
local -a pwsh_args=( -No{Profile,nInteractive,Logo} -Command 'Get-Clipboard' )

foreach pwsh_cmd ( p{wsh,owershell}.exe )
    (( $+commands[${pwsh_cmd}] )) || continue

    builtin print -Pn -- "%F{green}${(r:20:):-$=pwsh_cmd}%f"
    time ${pwsh_cmd} ${(@)^pwsh_args} > /dev/null
end

# pwsh.exe            707ms
# powershell.exe      1952ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment