I\'m having a hard time making this emacs -nw work effectively under the terminal mode (emacs -nw). Some setup information: The working server is connected via SSH, and emacs i
You can accomplish this by using a terminal escape code!
There is a unique category of terminal escape codes called "Operating System Controls" (OSC) and one of these sequences (\033]52
) is meant for interacting with the system clipboard. The great thing is that your terminal doesn't care where the code came from so it will work in remote sessions as well.
Most terminal emulators support it (iTerm2, OS X Terminal, and I think all Linux terminals besides GNOME). You can test if your terminal supports this sequence by simply running:
$ printf "\033]52;c;$(printf "Hello, world" | base64)\a"
Then paste from your system clipboard. If it pastes "Hello, world" then your terminal supports it!
I have this function in my init.el
so when I call yank-to-clipboard
Emacs will yank the value from my kill ring into the system clipboard:
(defun yank-to-clipboard ()
"Use ANSI OSC 52 escape sequence to attempt clipboard copy"
(interactive)
(send-string-to-terminal
(format "\033]52;c;%s\a"
(base64-encode-string
(encode-coding-string
(substring-no-properties
(nth 0 kill-ring)) 'utf-8) t))))
As I type this, I stumbled upon an almost-identical script supported by Chromium community: https://chromium.googlesource.com/apps/libapps/+/master/hterm/etc/osc52.el
For those running Emacs inside Tmux: Tmux consumes the sequence, so you'll need to pipe the sequence to the Tmux active tty for this to work. For more information on how this might work, see: https://sunaku.github.io/tmux-yank-osc52.html