3

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>
endif

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.

user137369
  • 477
  • 2
  • 4
  • 13

2 Answers2

2

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

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

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

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

You can compare that to your desired path.

muru
  • 69,900
  • 13
  • 192
  • 292
  • 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 '21 at 12:56
  • @user137369 You put `expand("%:ph")` instead of `current_file_directory` in your `if` command. – muru Jul 28 '21 at 13:20