You can use the findfile()
function, together with the file-searching features in order to try to find the path to a file up the directory tree.
For example:
:echo findfile('top-level.txt', '.;')
This will return the path to a file named top-level.txt
up the directory tree. If it's not in the current directory, but a directory up the directory tree, then it will return the full path to the file. (Note that it will return empty if the file is not found, you might need to add some handling for that particular case.)
After you have the path to the file you're interested in, you can use the fnamemodify()
function, together with the filename-modifiers, to extract the directory name (and possibly turn it into a full path.)
For example:
:echo fnamemodify(findfile('top-level.txt', '.;'), ':p:h')
The :p
modifier will turn the path into a full path (actually returns the current directory path if the file is not found, you might want to handle that different by using the filesystem root instead, you can add some more Vimscript logic testing whether findfile()
returns empty in order to accomplish that.)
Then the :h
extracts the "head" of the path, which means the directory in which the file lives in this case.
So that should return the full path of the directory up the directory tree in which the top-level.txt
file resides.
See the :help
article for the items mentioned above. You might also want to look into :help :find
and :help 'path'
, which are native Vim features to help you locate files to edit in the relevant project tree.
curdir = getcwd()
and thencurdir = fnamemodify(curdir, ':h')
. I'm not sure about the:h
part. Read:h filename-modifiers
to make sure that's the one that returns parent directory. Then you can iteratively go up a directory as you would in any normal programming language: with a while loop. Should be easy.