The Elisp code below introduces three functions designed to evaluate Emacs Lisp code, either under the cursor or within a selected text region. These functions can return the evaluation result, copy it to the clipboard, or display it in the minibuffer. The functions allow obtaining immediate feedback from the code evaluation.
;; License: MIT
;; Author: James Cherti
;; URL: https://www.jamescherti.com/emacs-evaluate-elisp-display-result-copy-clipboard/
;;
;; Description: The following source code snippet introduces three functions
;; designed to evaluate Emacs Lisp code, either under the cursor or within a
;; selected text region. These functions can return the evaluation result, copy
;; it to the clipboard, or display it in the minibuffer. The functions are
;; especially useful for obtaining immediate feedback from the code evaluation.
(defun my-eval-and-get-result ()
"Evaluate Elisp code under cursor or in the active region, then return the
result. If there is a syntax error or any other error during evaluation, an
error message is displayed."
(interactive)
(let* ((elisp-code (if (use-region-p)
(buffer-substring-no-properties (region-beginning)
(region-end))
(buffer-substring-no-properties (line-beginning-position)
(line-end-position)))))
(condition-case err
(let ((result (format "%S" (eval (read elisp-code)))))
result)
(error (message "Error: %s" (error-message-string err)))
nil)))
(defun my-eval-and-copy-result-to-clipboard (&optional display-result)
"Evaluate Elisp code under cursor or in the active region, copy the result to
the clipboard. With a prefix argument, also display the result using message."
(interactive)
(let ((result (my-eval-and-get-result)))
(when result
(kill-new result)
(when display-result
(message "%s" result)))))
(defun my-eval-and-copy-clipboard-and-print-result ()
"Evaluate Elisp code under cursor or in the active region, copy the result to
the clipboard, and display the result."
(interactive)
(my-eval-and-copy-result-to-clipboard t))
(defun my-eval-and-print ()
"Evaluate Elisp code under cursor or in the active region, display the
result."
(interactive)
(let ((result (my-eval-and-get-result)))
(when result
(message "%s" result))))
Code language: Lisp (lisp)