WSL's Emacs and windows clipboard 2nd solution

I recently wrote a function to update the windows 11 clipboard whenever the kill ring of emacs running WSL2 is updated (see WSL’s Emacs and windows clipboard). This solution involves copying the kill ring to a tmp files and removing it at the end.

Found a great answer on stackoverflow that suggests a more elegant solution using buffers (see https://stackoverflow.com/a/15694531/4292890).

This is what I’m currently using:

(defun shell-command-on-str (cmd &optional str)
  "Insert result of calling CMD with STR as input.

STR is current-kill if unspecified.
"
  (interactive (list (read-shell-command "Shell command on region: ")))
  (setq str (or str
                (current-kill 0)))
  (insert (with-temp-buffer
            (insert str)
            (shell-command-on-region (point-min) (point-max) cmd nil 'replace)
            (buffer-string))))


(defun wsl-update-clip (&rest _args)
  (interactive)
  (shell-command-on-str "clip.exe"))


(advice-add 'kill-new :after #'wsl-update-clip)
Fred Gruber
Fred Gruber
Senior Principal Scientist

My research interests include causal inference, Bayesian networks, causal discovery, machine learning.