Domanda

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.

È stato utile?

Soluzione

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)

Altri suggerimenti

You may want to use (current-kill 0) instead of (car kill-ring).

See the doc string of kill-ring:

,----
| List of killed text sequences.
| Since the kill ring is supposed to interact nicely with cut-and-paste
| facilities offered by window systems, use of this variable should
| interact nicely with `interprogram-cut-function' and
| `interprogram-paste-function'.  The functions `kill-new',
| `kill-append', and `current-kill' are supposed to implement this
| interaction; you may want to use them instead of manipulating the kill
| ring directly.
,----

This also answers your second question, from your comment. See the doc for the functions mentioned in this doc string etc.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top