In my init.vim, I want to run certain commands only if the current file is under a certain hierarchy. Pseudo-code:

if current_file_directory == ~/some/path/here
  autocmd <whatever>
  set <whatever>

But all the if examples I’m finding are too basic to extrapolate.

To clarify, neither :pwd nor getcwd() apply, because those return the directory one is in when invoking neovim. I care about the directory the file is in. Following the code above, the commands should fire if I’m under /tmp but editing the file ~/some/path/here/more/deep/still.txt but not if I’m under ~/some/path/here but editing the file /tmp/example.txt.

2 Answers 2


You can use expand() on the filename (%) with various modifiers (:p, :h, etc.):

:e ~/some/path/here/more/deep/still.txt
:echo expand("%:ph")

You can compare that to your desired path.

  • I did find some references to expand, but I’m unclear on how to use it in the required if context inside init.vim. Could you provide an example?
    – user137369
    Jul 28, 2021 at 12:56
  • @user137369 You put expand("%:ph") instead of current_file_directory in your if command.
    – muru
    Jul 28, 2021 at 13:20

Based on @muru’s answer and further testing, the final code would be:

if expand('%:h') =~ 'some/path/here'
  autocmd <whatever>
  set <whatever>
  • expand('%:h') gives the directory’s path to the file without the home directory.
  • =~ is required for the partial match.

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.