0

I made a command line tool to generate static websites. I want a way to use this command line tool from the vim command line, something like the G command from the Fugitive plugin.

The tool can only be executed in any directory that contains a specific file (which contains the configuration the program uses for the site), so I need to iterate through parent directories until that file is found, then call the command there.

How can I do this?

1
  • 1
    use something like curdir = getcwd() and then curdir = 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.
    – kadekai
    Aug 5 at 17:16

1 Answer 1

3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.