Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Result value of elisp code stored in a file?

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 ?

like image 762
David Unric Avatar asked Sep 27 '22 18:09

David Unric


2 Answers

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)
like image 155
xuchunyang Avatar answered Nov 03 '22 18:11

xuchunyang


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)))))
like image 45
Drew Avatar answered Nov 03 '22 20:11

Drew