Yank with previous
Facts - Editor: emacs
Wednesday, 07 March 2007 21:15

The lisp programming language adds power to the emacs editor. You can write lisp functions and bind them to keys in your .emacs file. A very powerful function I wrote a couple of years ago is the function yank-with-previous.

This function replaces marked text with the latest kill. This function can be repeated since it does not affect the kill-ring.  I use this command every time I work with emacs.

Below is the lisp code for in your .emacs file. You can use the command as follows:

  1.  first select  the text you want to copy to somewhere else in your text, for example by typing CTRL-SPACE at the beginning of the text and CTRL-INSERT at the end.
  2. then select the text that you want to replace by pressing ALT-SPACE at the beginning and moving the cursor to the end of the bit you want to replace
  3.  then press ALT-y to replace the text with the text from the first step.

Lisp code: 

(defun yank-with-previous ()
  "Replaces text with latest kill: kills from mark to point. 
   Removes this kill from the kill-ring. Then inserts latest kill."
  (interactive)
  (kill-region (point) (mark))
  (pop kill-ring)
  (set-variable 'previous-kill (pop kill-ring))
  (insert previous-kill)
  (push previous-kill kill-ring)
)
(global-set-key [(meta y)] 'yank-with-previous)