当前位置: 动力学知识库 > 问答 > 编程问答 >

elisp - Walk up the directory tree

问题描述:

The file tree is as follwing:

- foo

- lorem

- ipsum <-

- baz <-

- bar

- baz

The currently visited file is ipsum. Now I want to find the first

baz and the directory it is in. How do I walk up the tree from

ipsum in elisp?

网友答案:

You want 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)))))

If the result is not nil, you can extract the file's directory using file-name-directory, like so:

(let ((file (find-file-in-heirarchy (buffer-file-name) "baz")))
  (when file
    (file-name-directory file)))
分享给朋友:
您可能感兴趣的文章:
随机阅读: