How do I load project-specific Vim settings automatically when opening files in a directory?
Answer
:set exrc
Explanation
Vim's exrc option tells Vim to look for a .vimrc (or .exrc) file in the current directory when it starts and source it automatically. This lets you define per-project settings — such as indentation style, makeprg, or project-specific key mappings — without modifying your global ~/.vimrc.
How it works
- Add
set exrcto your~/.vimrcto enable the feature globally. - When Vim starts from a project directory, it searches for
.vimrcor.exrcin that directory and sources it. - To prevent arbitrary code execution, also add
set secure— this restricts what local.vimrcfiles can do (no shell commands, no writes).
Example
" In ~/.vimrc:
set exrc
set secure
" In /projects/myapp/.vimrc:
setlocal tabstop=2 shiftwidth=2 expandtab
setlocal makeprg=npm\ test
nnoremap <leader>t :make<CR>
Now, every time you open Vim from /projects/myapp/, the project's two-space indentation and test mapping are applied automatically.
Tips
- Always pair
exrcwithsecureto avoid executing malicious.vimrcfiles from untrusted repositories. - Neovim supports a more powerful alternative via the
exrcoption and.nvim.luafiles (Neovim 0.9+), which can contain full Lua configuration. - Commit the project
.vimrcto your repository so teammates who also use Vim benefit from the same settings.