存储在文件中的elisp代码的结果值?

Dav*_*ric 5 emacs elisp dot-emacs emacs24

寻找一种方法来评估存储在外部文件中的elisp代码并将其结果作为函数参数传递.演示我想要实现的内容的示例如下:

;; 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))))
Run Code Online (Sandbox Code Playgroud)

可能正在寻找一个类似eval的函数,除了副作用之外还返回最后一个表达式的结果.

任何的想法 ?

xuc*_*ang 3

使用变量来共享数据更容易、更常见,例如:

;; 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)
Run Code Online (Sandbox Code Playgroud)

更新函数eval-file应该做你想要的:

;; 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)
Run Code Online (Sandbox Code Playgroud)

更新二:不计算最后一个表达式两次

(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)
Run Code Online (Sandbox Code Playgroud)