Walk up the directory tree

China☆狼群 提交于 2019-12-20 10:38:27

问题


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?


回答1:


You want locate-dominating-file.




回答2:


(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)))


来源:https://stackoverflow.com/questions/14095189/walk-up-the-directory-tree

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!