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

问题描述 投票:2回答:2

假设我正在编写一个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运行它,那么它的效果很好。如果我在编辑任何其他文件时调用该函数,则它不起作用,因为路径不正确。

无论函数在何处被调用,如何从./bin/executable中可靠地引用foo.el

emacs elisp relative-path
2个回答
2
投票

使用load-file-name变量。

(defconst directory-of-foo (file-name-directory load-file-name))

(defun foo ()
  (shell-command-to-string
   (format "echo '%s' | %s"
           (buffer-substring-no-properties
            (point-min)
            (point-max))
           (expand-file-name "./bin/executable" directory-of-foo))))

1
投票

你可以使用load-file-namedefault-directory的组合。如果您只检查前者,那么如果您明确加载它,该文件将起作用,但如果您在缓冲区中对其进行评估,则该文件将不起作用。

例如:

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

此外,使用expand-file-name将路径转换为绝对路径可能是个好主意。

© www.soinside.com 2019 - 2024. All rights reserved.