Walk up the directory tree

后端 未结 2 383
刺人心
刺人心 2021-02-04 02:26

The file tree is as follwing:

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

The currently visited file is ipsum. Now

2条回答
  •  醉话见心
    2021-02-04 03:16

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

提交回复
热议问题