Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save yanked text to string in Emacs

Tags:

emacs

elisp

I am trying to store yanked text to a variable in Emacs.

It seems like the following works:

(let ((str nil))
  (with-temp-buffer
    (yank)
    (setq str (buffer-string)))

I wondered, are there any simpler methods for achieving this? It seems like opening a temporary buffer just to get the yanked text is overkill.

like image 292
Håkon Hægland Avatar asked Apr 09 '14 10:04

Håkon Hægland


1 Answers

The value you are looking for in your function is available as

(car kill-ring)

This should work:

(defun was-yanked ()
  "When called after a yank, store last yanked value in let-bound yanked. "
  (interactive)
  (let (yanked)
    (and (eq last-command 'yank)
         (setq yanked (car kill-ring))))

Maybe message and also return it:

(defun was-yanked ()
  "When called after a yank, store last yanked value in let-bound yanked. "
  (interactive)
  (let (yanked)
    (and (eq last-command 'yank)
         (setq yanked (car kill-ring))))
  (when (interactive-p) (message "%s" yanked))
  yanked)
like image 197
Andreas Röhler Avatar answered Oct 02 '22 14:10

Andreas Röhler