2

Is there a builtin mechanism that copies the result of C-x C-e rather than inserting it into the buffer with the non-negative prefix. I think this would have been more useful by default.

1 Answer 1

3

Try this:

(defun my-eval-last-sexp ()
  (interactive)
  (elisp--eval-last-sexp nil)
  (let (result)
    (with-current-buffer (get-buffer " *Echo Area 0*")
      (goto-char (point-min))
      (setq result (read (current-buffer))))
    (kill-new (format "%s" result))))

What's inserted into the echo area by elisp--eval-last-sexp is the resulting value (which is what you want copied to the kill-ring).

But in the case of a number, for example, what's inserted there also includes the number written in different ways (octal, hexadecimal, character).

That's why I used read, and then converted that to a string, instead of just picking up the text in the echo area directly. IOW, in that specific case more than just the value is inserted in the echo area - more than what we want copied to the kill-ring.

6
  • Is the result thrown by elisp--eval-last-sexp the same as what gets inserted into the echo area? If so, would it be possible to skip collecting the data from the echo area?
    – lawlist
    Mar 9, 2023 at 19:21
  • It sort of does and I get the idea. Although, it strips the double quotes from string outputs.
    – Arktik
    Mar 9, 2023 at 20:04
  • 1
    @lawlist: What's inserted into the echo area is the resulting value, yes, but in the case of, e.g., a number, what's inserted there also includes the number written in different ways. That's why I used read, and then converted that to a string, instead of just picking up the text in the echo area directly. IOW, in that specific case more than just the value is inserted in the echo area - more than what OP wants in the kill-ring.
    – Drew
    Mar 9, 2023 at 22:35
  • 1
    @lawlist: There may be a way to not bother with the echo area, or a way to prevent it from printing the extra stuff there. But I didn't find such a way, looking quickly; it looks like that behavior is pretty much hard-coded.
    – Drew
    Mar 9, 2023 at 22:37
  • 1
    @lawlist: I added that explanation to the answer. (Comments can be deleted at any time, and they're not searchable.)
    – Drew
    Mar 10, 2023 at 17:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.