The file tree is as follwing:
- foo
- lorem
- ipsum <-
- baz <-
- bar
- baz
The currently visited file is ipsum
. Now
(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)))