文件树如下:
- foo
- lorem
- ipsum <-
- baz <-
- bar
- baz
当前访问的文件是ipsum
. 现在我想找到第一个
baz
和它所在的目录。如何从
ipsum
elisp 中爬上树?
文件树如下:
- foo
- lorem
- ipsum <-
- baz <-
- bar
- baz
当前访问的文件是ipsum
. 现在我想找到第一个
baz
和它所在的目录。如何从
ipsum
elisp 中爬上树?
你想要locate-dominating-file
。
(defun parent-directory (dir)
(unless (equal "/" dir)
(file-name-directory (directory-file-name dir))))
(defun find-file-in-heirarchy (current-dir fname)
"Search for a file named FNAME upwards through the directory hierarchy, starting from CURRENT-DIR"
(let ((file (concat current-dir fname))
(parent (parent-directory (expand-file-name current-dir))))
(if (file-exists-p file)
file
(when parent
(find-file-in-heirarchy parent fname)))))
如果结果不是 nil,您可以使用 提取文件的目录file-name-directory
,如下所示:
(let ((file (find-file-in-heirarchy (buffer-file-name) "baz")))
(when file
(file-name-directory file)))