Copy the last Emacs message into the current buffer

emacs

Is there a function I could use to quickly copy the message in the echo area (if any) into my working buffer? Should I define the shortcut for that function with define-key or global-set-key or some other way?

Best Answer

The function current-message returns the message that is currently displayed in the echo area, if any. You can insert it with (insert (current-message)). However, anything that causes something else to occupy the echo area will cause current-message to return nil.

Messages from Emacs are archived in the *Messages* buffer. It would be more useful to grab the last line from there. This isn't perfectly reliable since it's possible to have a multi-line message, but that's rare: the message function is meant for short messages that fit in one line.

The following function inserts the last message (more precisely, the last line from the *Messages* buffer. With a prefix argument, it returns older messages: 1 for the latest message, 2 for the next-to-last one, etc. The argument 0 inserts (current-message) if any.

(defun last-message (&optional num)
  (or num (setq num 1))
  (if (= num 0)
      (current-message)
    (save-excursion
      (set-buffer "*Messages*")
      (save-excursion
    (forward-line (- 1 num))
    (backward-char)
    (let ((end (point)))
      (forward-line 0)
      (buffer-substring-no-properties (point) end))))))
(defun insert-last-message (&optional num)
  (interactive "*p")
  (insert (last-message num)))

Bind it to a key in the normal way. For example, if you want the command available on C-c m at all times:

(global-set-key "\C-cm" 'insert-last-message)

There may be easier ways than invoking two custom commands to insert the file name, see the Emacs wiki.

To insert the output from evaluating a Lisp snippet with C-x C-e, pass a prefix argument: C-u C-x C-e.