Local .vimrc files
Even if you’re a Vim purist with few plugins, most everyone has some kind of configuration they want to persist from session to session. This config goes in your
.vimrc file, typically stored in your home directory.
But if you use Vim on many projects, it can be handy to have project-specific configuration, customizing your Vim config with tweaks or overrides that apply only when working on files in that directory:
Vim has an option called
set exrc which we can add to our
.vimrc file. When this is enabled, Vim will also look for and process a
.vimrc file in the directory from which Vim is started. My most common use for this is to bind keys for things like invoking tests which might vary between projects. I also can setup project-specific configurations like Syntastic checkers.
But, not too fast, what if someone could put nefarious commands in a local
.vimrc without you knowing? This could include auto commands that run scripts every time a buffer is opened or written. Vim has a way to prevent this called
set secure. With this enabled, Vim will not allow dangerous commands like
autocmd in local
.vimrc files — unless the files are owned by you.
But wait again! How is that useful to us? With today’s modern workflows, we might be pulling files from a remote Git server. Those files will definitely be owned by us, which means the protections we get from
set secure aren’t applied.
So how can we get the benefits of
set exrc but still protect ourselves from nefarious users putting insecure commands in
.vimrc files we pull down via Git? We can whitelist specific directories in our system-wide
.vimrc. So let’s put together everything that we’ve learned. This is what I recommend you put in your
.vimrc inside your home directory:
if getcwd() =~# '^\(/some/safe/path/\|/another/safe/path/\)' set secure exrc endif
Specify the directory paths you deem to be safe. And be careful to get the escaping correct: the
) need to be escaped with
You might also consider adding these local
.vimrc files to your global
.gitignore. If you’re using Fugitive, the Git plugin for Vim, you can use
1gI to add these to your local Git exclude or ignore lists. We cover that in our course Git Better with Vim.
We are sorry that this post was not useful for you!
Let us improve this post!
Tell us how we can improve this post?