www.delorie.com/gnu/docs/emacs-lisp-intro/emacs-lisp-intro_269.html   search  
Buy the book!

Programming in Emacs Lisp

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

B.3 yank-pop

After understanding yank, the yank-pop function is easy. Leaving out the documentation to save space, it looks like this:

(defun yank-pop (arg)
  (interactive "*p")
  (if (not (eq last-command 'yank))
      (error "Previous command was not a yank"))
  (setq this-command 'yank)
  (let ((before (< (point) (mark))))
    (delete-region (point) (mark))
    (rotate-yank-pointer arg)
    (set-mark (point))
    (insert (car kill-ring-yank-pointer))
    (if before (exchange-point-and-mark))))

The function is interactive with a small `p' so the prefix argument is processed and passed to the function. The command can only be used after a previous yank; otherwise an error message is sent. This check uses the variable last-command which is discussed elsewhere. (See section 8.5 copy-region-as-kill.)

The let clause sets the variable before to true or false depending whether point is before or after mark and then the region between point and mark is deleted. This is the region that was just inserted by the previous yank and it is this text that will be replaced. Next the kill-ring-yank-pointer is rotated so that the previously inserted text is not reinserted yet again. Mark is set at the beginning of the place the new text will be inserted and then the first element to which kill-ring-yank-pointer points is inserted. This leaves point after the new text. If in the previous yank, point was left before the inserted text, point and mark are now exchanged so point is again left in front of the newly inserted text. That is all there is to it!

  webmaster     delorie software   privacy  
  Copyright 2003   by The Free Software Foundation     Updated Jun 2003