Convenient general way to “grab” the echoed result of a command in Emacs (of M-: or M-!)

copy/pasteemacs

Sometimes, I want to insert the result of an Emacs command (that has been echoed in the echo area) to another buffer or another running X program. So, I'd like to put it to the kill-ring. What would be a convenient way to do this?

For example: I could run a query with a shell command while in dired mode, say: !rpm -qf (to find out which package owns the selected file in the directory listing), and then want to insert the result somewhere else.

Or, another example: if I needed the filename of the current buffer (as in Is there a user interface in Emacs allowing one to "grab" the buffer's filename conveniently?), and there was not yet any predefined command for this, I could at least do M-:(buffer-file-name) and then use this general-purpose way to copy the shown result to the kill-ring in order to paste it later. (Of course, I could eval (kill-new (buffer-file-name)), but this example here is to illustrate what kind of general-purpose way to do the grabbing of the echoed result I'm looking for.)

Best Answer

Type C-u before either M-: or M-! to get the result inserted instead of sent to the echo area.

To get things directly into the kill ring, you need to dabble in Elisp. Something like this (untested):

;;; kill ring version of M-!
(defun shell-command-to-kill-ring (command)
    (interactive
      (list
        (read-shell-command "Shell command: " nil nil
                (let ((filename
                       (cond
                    (buffer-file-name)
                    ((eq major-mode 'dired-mode)
                     (dired-get-filename nil t)))))
                  (and filename (file-relative-name filename))))
        current-prefix-arg
        shell-command-default-error-buffer))
    (kill-new (shell-command-to-string command)))

;;; kill-ring version of M-:
(defun eval-expression-to-kill-ring ()
    (interactive)
    (call-interactively 'eval-expression)
    (kill-new (car values)))
Related Question