Looking for a way how evaluate elisp code stored in an external file and pass its result as a function argument. Example demonstrating what I'd like to achieve follows:
;; content of my_template.el
'(this is a list)
;; content of .emacs where result of my_template.el has to be used
(define-auto-insert "\.ext$"
;; bellow is my attempt to retrieve resulting list object
;; but getting nil instead
(with-temp-buffer
(insert-file-contents ("my_template.el"))
(eval-buffer))))
Probably looking for an eval-like function which besides side-effect also returns result of the last expression.
Any idea ?
Using variable to share data is easier and more common, for example:
;; content of ~/my_template.el
(defvar my-template '(this is a list))
;; content of .emacs where result of my_template.el has to be used
(load-file "~/my_template.el")
(define-auto-insert "\.ext$"
my-template)
Update the function eval-file
should do what you want:
;; content of ~/my_template.el
'(this is a list)
(defun eval-file (file)
"Execute FILE and return the result of the last expression."
(load-file file)
(with-temp-buffer
(insert-file-contents file)
(emacs-lisp-mode)
(goto-char (point-max))
(backward-sexp)
(eval (sexp-at-point))))
(eval-file "~/my_template.el")
=> (this is a list)
Update two: without evaluate the last expression twice
(defun eval-file (file)
"Execute FILE and return the result of the last expression."
(eval
(ignore-errors
(read-from-whole-string
(with-temp-buffer
(insert-file-contents file)
(buffer-string))))))
(eval-file "~/my_template.el")
=> (this is a list)
Don't read from a string. Read from a buffer.
(defun load&return (file &optional msgp)
"Load FILE. Return the value of the last sexp read."
(interactive "fFile: \np")
(let* ((sexp (with-current-buffer (find-file-noselect file)
(goto-char (point-min))
(read (current-buffer))))
(val (ignore-errors (eval sexp))))
(prog1 val (when msgp (message "Value: %S" val)))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With