__dirname in elisp

想知道node里的__dirname在elisp中怎么实现,求助

补充一下,我搜到了load-file-name 但是这个是load-file的时候设置的入口文件,执行eval-buffer是拿不到这个值的。

(or load-file-name buffer-file-name)

这样?

1 个赞

楼上是正解,至少我也是这么用的:

(file-name-directory (or load-file-name buffer-file-name))

f.el 还提供了这样一个函数,还考虑到了 Byte Compilation:

(defun f-this-file ()
  "Return path to this file."
  (cond
   (load-in-progress load-file-name)
   ((and (boundp 'byte-compile-current-file) byte-compile-current-file)
    byte-compile-current-file)
   (:else (buffer-file-name))))
1 个赞

安装 Package 时生成的 Autoload 文件还有类似于:

(add-to-list 'load-path (directory-file-name
                         (or (file-name-directory #$) (car load-path))))

其中 #$ 代表当前文件名:

It also uses the `#$’ construct, which stands for the name of this file, as a string.

不过我们似乎不该用它:

Do not use these constructs in Lisp source files; they are not designed to be clear to humans reading the file.

参考 (elisp) Docs and Compilation

1 个赞

其实可以这样玩:

(setq path load-file-name)
(message path)