How to preserve clipboard content in Emacs on Windows

elispemacs

This is scenario that I ran into a few times:

I copy some text from other program. Go to Emacs and did some editing before I paste/yank the text in. C-y to yank and voila … not the text I intended to paste in. Then I realize that while I am moving things around, I used commands like kill-line and backward-kill-word, and those killed lines and words now occupied the kill-ring. But typing M-y does not bring the original copied text back, so I need to go back to my original program to copy the text again. And even worst if the original program is closed, then I lost the copied text completely.

Kill-line, etc. are such basic commands (like hitting the delete key, almost), and while I don't mind that the kill-ring gets a bit cluttered by using those command, I expect that my original text stays somewhere in the kill-ring so that I can eventually find it by typing M-y a few times. How can I make Emacs to automatically preserve the current clipboard content into the kill-ring before overriding the clipboard content?

Best Answer

This code should automatically put the selection (from outside Emacs) onto the kill-ring any time you do a kill in Emacs. It's been tested on Linux, but shouldn't be restricted to Linux.

(defadvice kill-new (before kill-new-push-xselection-on-kill-ring activate)
  "Before putting new kill onto the kill-ring, add the clipboard/external selection to the kill ring"
  (let ((have-paste (and interprogram-paste-function
                         (funcall interprogram-paste-function))))
    (when have-paste (push have-paste kill-ring))))

If you find yourself doing this a lot, it may be useful to take a look at the package browse-kill-ring, which gives you a nice view of the kill ring (as opposed to repeatedly typing M-y).

Related Topic