Search code examples
emacskillyank

Emacs: How to yank the last yanked text regardless of subsequent kills?


I often find myself repeatedly yanking something after doing some kills and it becomes a process like:

  1. C-y
  2. C-y M-y
  3. C-y M-y M-y
  4. C-y M-y M-y M-y

Each time I kill some text it pushes the first kill back in the kill ring so that I need to cycle through all the kills to return to text I want to yank. What I want to do is repeatedly yank the same text while killing text in-between yanks. Is this possible?


Solution

  • This is a strange hack, but may help.

    The first time you use M-y you normally get an error (no previous yank). So the idea is that this first time you get the last yank instead of the last kill.

    For storing that last yank I use the 'Y' register in this example.

    These 2 functions would wrap around yank and yank-pop. You expect bugs, I expect suggestions.

    (defun jp/yank (&optional arg)
      "Yank and save text to register Y"
      (interactive)
      (set-register ?Y (current-kill 0 t))
      (yank arg))
    
    (defun jp/yank-pop (&optional arg)
      "If yank-pop fails, then insert register Y"
      (interactive)
      (condition-case nil
          (yank-pop arg)
        (error (insert (get-register ?Y)))))
    
    (global-set-key (kbd "M-y") (quote jp/yank-pop))
    (global-set-key (kbd "C-y") (quote jp/yank))