0

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?

0
  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.

1
  • 2
    I think this boils down to expand('%:p') =~# '^/some/dir'
    – D. Ben Knoble
    Jul 8 at 12:27

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.