Emacs always copies killed/deleted content to the clipboard. I often need to copy and paste content into Emacs but when I delete existing content from Emacs before pasting, the content I would like to paste is lost.
The only solution I found is to use
(setq save-interprogram-paste-before-kill t)
in order to make sure content copied outside of Emacs stays available in the kill-ring, and people with similar problems seem to be satisfied with this solution. What bothers me about it is that I have to type C-y followed by one or more repetitions of M-y to get to the content I want to paste.
So my question is: How can I stop Emacs from copying content to the clipboard when I kill/delete it (excluding cases where I delete a region with C-w)?
First off: Emacs has its own internal "clipboard" called "kill ring" which is separate from the system clipboard.
To make sure the system clipboard always has the latest content you copied outside of Emacs, add
(setq x-select-enable-clipboard nil)
to your .emacs
file. According to the Emacs manual, this will
prevent kill and yank commands from accessing the clipboard [...].
Irrespective of whether you've killed text inside of Emacs after copying content outside of it, you can then use the command x-clipboard-yank
to insert the contents of the clipboard into the current buffer. If you want, you can set up a global key binding for this command via
(global-set-key (kbd "C-c y") 'x-clipboard-yank)
If necessary, replace C-c y
with a key binding of your choosing.
Use delete-region
. Commonly commands having delete
in their names don't store the stuff in kill-ring.
These two settings prevent X clipboard contamination. All kill rings stay intact inside Emacs.
(setq x-select-enable-clipboard nil)
(setq x-select-enable-primary nil)
To solve the specific problem of needing to delete something before pasting in the replacement text, just use delete-selection-mode
. This makes it so that the region is deleted when you paste.