20

文件树如下:

- foo
  - lorem
    - ipsum <-
  - baz <-
- bar
- baz

当前访问的文件是ipsum. 现在我想找到第一个 baz和它所在的目录。如何从 ipsumelisp 中爬上树?

4

2 回答 2

32

你想要locate-dominating-file

于 2013-01-07T14:00:12.477 回答
18
(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)))
于 2012-12-31T02:08:36.533 回答