I want to have a piece of vimscript (a custom formatter) only apply if the current file is inside some directory. How can I tell whether the active buffer is within a particular directory?
1 Answer
fu! StartsWith(longer, shorter) abort
return a:longer[0:len(a:shorter)-1] ==# a:shorter
endfunction
fu! FileIsInDirectory(directory) abort
let l:fname = expand('%:p')
return StartsWith(l:fname, a:directory)
endfunction
function YourFunction() abort
if !FileIsInDirectory(expand("$HOME") . "/project/dir/")
return
endif
(...)
I believe you can also put a gitignored / committed .vim/something.vim
inside the project directory, and it will only apply for buffers in that directory, but I'm not sure how it works.
-
10I think this boils down to
expand('%:p') =~# '^/some/dir'
– D. Ben Knoble ♦Commented Jul 8, 2021 at 12:27