Search code examples
emacselispemacs24dot-emacs

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 ?


Solution

  • 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)