【问题标题】:elisp - Get path to file relative to scriptelisp - 获取相对于脚本的文件路径
【发布时间】:2019-03-28 10:58:30
【问题描述】:

假设我正在编写一个 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

【问题讨论】:

    标签: emacs elisp relative-path


    【解决方案1】:

    使用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))))
    

    【讨论】:

    • 这行得通。虽然我选择了(defconst path-of-foo (file-name-directory (or load-file-name buffer-file-name)))
    • FWIW,GNU 项目中的约定是仅使用“路径”来表示“要搜索的目录列表”(如“$PATH”),因此我们将上述变量称为"directory-of-foo" 代替。
    【解决方案2】:

    您可以使用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 将路径转换为绝对路径可能是个好主意。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-25
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多