tags:

views:

97

answers:

3

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?

+3  A: 

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.

Jérôme Radix
Thanks. I'm looking at a way to do it without having to do `M-x kill-region` each time, and I'd rather not add a new keybinding. Is there no way to do this with standard keybindings?
Skilldrick
You could do a query-replace ( M-% ) by yanking in the minibuffer the thing you want to use to replace other things : M-% thestringtoreplace RET C-y RET !
Jérôme Radix
@Jérôme Yes, I think you're right. The only problem with that is that the replaced string must be the same each time, whereas I'd like to be able to manually replace a load of different things with the same string. I think this is one thing that's much easier to do with standard text editors (i.e. using Ctrl-C then Ctrl-V) than with Emacs.
Skilldrick
I'll leave the question open for a day just in case, but mark this as completed if I don't get any other answers.
Skilldrick
I added a word on delete-rectangle which could be used like delete-region on a single line, and delete-rectangle has a key binding by default.
Jérôme Radix
Thanks - that's exactly what I wanted!
Skilldrick
+1  A: 

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.

scottfrazer
Thanks - that's a handy little thing to have.
Skilldrick
+3  A: 

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-%).
huaiyuan
Nice - thanks. Is there ever a point where you can stop learning Emacs?!
Skilldrick