From 80ec81e3401affb70777a1a9a44b71c3391989b5 Mon Sep 17 00:00:00 2001 From: Marco Trevisan Date: Sat, 28 Nov 2026 01:19:24 +0100 Subject: [PATCH] feat(clipboard): add OSC 52 fallback (#14251) OSC 52 makes the terminal emulator set the clipboard of the machine the user is connected from, which is the only way to copy to it when running over SSH or inside a container with no access to the local display server. Use it when no other clipboard tool is available, or when ZSH_CLIPBOARD_OSC52 is set to "always"; set it to "never" to disable the fallback. OSC 52 is write-only in practice, so clippaste keeps failing unless a real clipboard tool is available. Closes #13459 --- lib/clipboard.zsh | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/lib/clipboard.zsh b/lib/clipboard.zsh index c9306b0f8..44e81e701 100644 --- a/lib/clipboard.zsh +++ b/lib/clipboard.zsh @@ -16,6 +16,10 @@ # - doitclient (for SSH) http://www.chiark.greenend.org.uk/~sgtatham/doit/ # - win32yank (Windows) # - tmux (if $TMUX is set) +# - OSC 52 (when no clipboard tool is available, e.g. over SSH or in a container) +# +# Set ZSH_CLIPBOARD_OSC52 to "always" to copy through OSC 52 even if a +# clipboard tool is available, or to "never" to disable the fallback. # # Defines two functions, clipcopy and clippaste, based on the detected platform. ## @@ -48,6 +52,22 @@ # # Paste to a file # clippaste > file.txt # +function _has_osc52_clipboard() { + [[ -n "${TTY:-}" ]] && [[ -w "${TTY}" ]] && (( ${+commands[base64]} )) +} + +function _clipcopy_osc52() { + emulate -L zsh + local content + content=$(cat "${1:-/dev/stdin}" | base64 | tr -d '\n') || return 1 + print -rn -- $'\e]52;c;'"${content}"$'\e\\' > /dev/tty +} + +function _clippaste_osc52() { + print 'clippaste: OSC 52 is write-only and no other clipboard tool was found' >&2 + return 1 +} + function detect-clipboard() { emulate -L zsh @@ -87,6 +107,9 @@ function detect-clipboard() { elif [ -n "${TMUX:-}" ] && (( ${+commands[tmux]} )); then function clipcopy() { tmux load-buffer -w "${1:--}"; } function clippaste() { tmux save-buffer -; } + elif [[ "${ZSH_CLIPBOARD_OSC52:-}" != never ]] && _has_osc52_clipboard; then + function clipcopy() { _clipcopy_osc52 "$@"; } + function clippaste() { _clippaste_osc52; } else function _retry_clipboard_detection_or_fail() { local clipcmd="${1}"; shift @@ -101,6 +124,10 @@ function detect-clipboard() { function clippaste() { _retry_clipboard_detection_or_fail clippaste "$@"; } return 1 fi + + if [[ "${ZSH_CLIPBOARD_OSC52:-}" == always ]] && _has_osc52_clipboard; then + function clipcopy() { _clipcopy_osc52 "$@"; } + fi } function clipcopy clippaste {