WSL's Emacs and windows clipboard
Windows 11 now supports built-in linux GUI applications so I started using emacs thru WSL2 (see emacs installation). While it works quite well (there is even GPU support now) there are some issues with the windows clipboard. Specifically, while I can copy things from the windows clipboard to emacs (most of the time, more about this at the end) I could not copy things from emacs to window.
Most of the solutions online I have seen involve creating a new function for sending marked text to the windows clipboard using the “clip.exe” program (see, for example, wsl copy and paste). However, I wanted to automatically updated the windows clipboard whenever the kill-ring is updated. So I came up with the following solution
(defun wsl-copy-clip(&rest _args) (setq mytemp (make-temp-file "winclip")) (write-region (current-kill 0 t) nil mytemp ) (shell-command (concat "clip.exe<" mytemp )) (delete-file mytemp) ) (advice-add 'kill-new :after #'wsl-copy-clip)
The wsl-copy-clip function copies the latest entry on the kill ring to the windows clipboard. I add this function as an advice (see advice) to the kill-new function which appears to be called by most kill-ring related functions (M-w,C-w, C-d, M-d, etc). Now anytime the kill-ring gets updated in emacs the windows clipboards get updated as well.
There are a couple of things that I would like to mention:
- I’m creating a tmp file with the top of the kill-ring so I can pass it to clip.exe and then removing.
- There could be functions that update the kill-ring without the kill-new function. If that is the case the windows clipboard will not get updated. If anyone knows of any other way to run a function whenever the kill-ring gets updated I would love to know.
- Finally, while most of the time I can copy text from windows to emacs, I noticed that sometimes it stops working. Not sure exactly when this happens so it is difficult to replicate and fix.