Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I keep the same item for yanks in Emacs?

Tags:

emacs

Something I do often in Emacs is to cut a bit of text, and then replace another bit with the cut text. So, say I've got the text I want to yank as the last item in my kill-ring. I yank it into the new place, then kill the text that was already there. But now the killed text is the latest item in the kill-ring. So next time I want to yank the first item, I have to do C-y M-y. Then the next time there are two more recent items in the kill-ring, so I have to do C-y M-y M-y, and so on.

I'm guessing there's a better way to do this. Can someone enlighten me please?

like image 410
Skilldrick Avatar asked Sep 24 '10 12:09

Skilldrick


4 Answers

Several alternatives:

  1. Turn on delete-selection-mode, and use C-d or delete to delete region without touching the kill-ring.
  2. Use C-x r s i to save text to register i, and later, C-x r i i to insert the saved text.
  3. If the pattern of texts to be replaced can be captured in a regular expression, use query-replace-regexp (C-M-%).
like image 197
huaiyuan Avatar answered Oct 16 '22 23:10

huaiyuan


You should use delete-region instead of kill-region.

delete-region deletes the region without putting it in the kill ring. It is bind to <menu-bar> <edit> <clear> by default.

If you only want to use default bindings without using the menu, you could use delete-rectangle with C-x r d but it works on rectangle. It could be fine to use it on a single line like delete-region.

like image 34
Jérôme Radix Avatar answered Oct 16 '22 21:10

Jérôme Radix


One of the oldest and best kept secrets in Emacs -- dunno why: Emacs has a secondary selection.

And this is exactly what it is good for. It saves another selection of text for you to use, over and over.

Select some text, then yank the secondary in to replace it. Repeat elsewhere. Often this is more convenient, flexible, and precise than something like query-replace.

Please take a look, for your own good -- maybe it will stop being such a little-known feature... http://www.emacswiki.org/emacs/SecondarySelection

like image 4
Drew Avatar answered Oct 16 '22 23:10

Drew


I wrote this function to pop the newest item off the kill-ring:

(defun my-kill-ring-pop ()
  "Pop the last kill off the ring."
  (interactive)
  (when kill-ring
    (setq kill-ring (cdr kill-ring)))
  (when kill-ring-yank-pointer
    (setq kill-ring-yank-pointer kill-ring))
  (message "Last kill popped off kill-ring."))

So after I kill something I don't want to keep, I hit a key that calls this.

like image 2
scottfrazer Avatar answered Oct 16 '22 23:10

scottfrazer