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.
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)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With