Emacs elisp-获取相对于脚本的文件路径

Emacs elisp-获取相对于脚本的文件路径,emacs,elisp,relative-path,Emacs,Elisp,Relative Path,假设我正在编写一个emacs lisp函数,该函数与一个相对于定义该函数的文件的文件进行交互 - bin/executable - foo.el foo.el: (defun foo () (shell-command-to-string (format "echo '%s' | ./bin/executable" (buffer-substring-no-properties (point-min) (point

假设我正在编写一个emacs lisp函数,该函数与一个相对于定义该函数的文件的文件进行交互

- bin/executable
- foo.el
foo.el

(defun foo ()
  (shell-command-to-string
   (format "echo '%s' | ./bin/executable"
           (buffer-substring-no-properties
            (point-min)
            (point-max)))))
如果我从
foo.el
运行它,那么它工作得很好。如果我在编辑任何其他文件时调用该函数,它将不起作用,因为路径不正确


如何从
foo.el
中可靠地引用
/bin/executable
,而不管调用函数的位置如何?

使用
加载文件名
变量

(foo的defconst目录(文件名目录加载文件名))
(德文福)
(将shell命令转换为字符串
(格式为“回显'%s'|%s”
(缓冲区子字符串没有属性
(最低分)
(最高点))
(展开文件名“/bin/executable”foo目录)))

您可以使用
加载文件名
默认目录
的组合。如果只检查前者,则如果显式加载该文件,它将工作,但如果在缓冲区中对其求值,它将不工作

例如:

(defvar my-directory (if load-file-name
                         ;; File is being loaded.
                         (file-name-directory load-file-name)
                       ;; File is being evaluated using, for example, `eval-buffer'.
                       default-directory))

此外,使用
扩展文件名

将路径转换为绝对路径可能是一个好主意,这样做有效。虽然我选择了
(defconstpath of foo(file name directory(或load file name buffer file name))
而不是.FWIW,但GNU项目中的约定是使用“path”仅表示“要搜索的目录列表”(如“$path”)所以我们将调用上述变量“directory of foo”。