:best of Vim

Showcasing the top Vim plugins, tips and tricks.

What is Vim?

Vim is a text editor for programmers, power users & command-line junkies.

What is :best of Vim?

:best of Vim showcases the best plugins, extensions & tips for making the most of Vim.

It was built for NoVIMber 2011.

Learn more...

Follow

Auto-Reload Your Vimrc

If you're going to master Vim, you're going to spend some time tweaking & tailoring your .vimrc file. And when you're doing that you'll want to see the effects of any changes as quickly as possible.

It's easy to get Vim to reload the .vimrc file whenever it changes. Just add this to your .vimrc file:

augroup reload_vimrc " {
    autocmd!
    autocmd BufWritePost $MYVIMRC source $MYVIMRC
augroup END " }

Save, then try it out. Put set number at the bottom of your .vimrc & save. Then change it to set nonumber and save again. Line numbering should pop in an out. Instant reloading.

Breakdown

Let's take a look at what's happening. The bulk of the work's done by the line:

autocmd BufWritePost $MYVIMRC source $MYVIMRC

$MYVIMRC is the platform-independent location of your .vimrc file. So this command says that whenever that file is written, source (reload) it immediately afterwards.

The rest of the code, the wrapping, is a pattern you'll see a lot in .vimrc files:

augroup somename " {
    autocmd!
    ...
augroup END " }

This is housekeeping. Putting the commands in a group, and starting with autocmd! clears out any previous autocommands Vim has registered for that group. If we didn't do this, Vim would append a new autocommand every time we wrote the .vimrc file. Pretty quickly we'd have dozens of source $MYVIMRC commands queued up for every single write.

See :help $MYVIMRC, :help source and especially :help autocmd for more.

Plus: Steve Losh's excellent Learn Vimscript The Hard Way has a great explanation of how autocommand groups work.

Tags:.vimrc
Comments...