Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve clipboard content in Emacs on Windows?

Tags:

emacs

elisp

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?

like image 739
polyglot Avatar asked May 11 '09 16:05

polyglot


People also ask

How do I paste from clipboard to Emacs?

In the terminal window, hold down the left mouse button and sweep across the line starting from the letter c. The highlighted text shows what is copied. Go to the emacs window and click with the middle mouse button at the point where you want to insert the text. This retrieves the text from the paste buffer.

How do you yank in Emacs?

Ctrl-y - This command will yank back the text which was deleted most recently with the above command. The text will be placed at the current emacs cursor location. You can yank back the text as many times as you wish.

How do I select all in Emacs?

C-x h will select the entire buffer. You can search for help within Emacs using the built-in help system.


1 Answers

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).

like image 106
Trey Jackson Avatar answered Oct 06 '22 22:10

Trey Jackson