Vim Tips #20: Indentation and White Space

Vim Tips

Let's talk about white space and indenting.

In your ~/.vimrc, you can tell Vim how many spaces a tab should take up:

set tabstop=4

This is my preferred setting: when I hit tab, I get something four spaces wide. But I don't like Tabs, so I also tell Vim to always turn them into spaces when I use the Tab key (still in the ~/.vimrc):

set expandtab

And if I ever find a file that has existing tabs in it, I tell Vim to replace them all with spaces:

:retab

This goes through the entire file and replaces tabs with your preferred space setting.

(Of course if you're working on a shared project rather than just your own files, you may want to reconsider: if the project standard is to use tabs, DON'T be the person rewriting them all to spaces - or possibly even worse mixing tabs and spaces ...)

If you're writing a program and you realize you need to enclose a block of code inside a loop, you may suddenly find yourself needing to indent a good-sized block of code. To do this, I use:

:.,+3>

which means "indent the current line and the three following by one tabstop." Possibly more useful is the ability to do the same thing by line number (use :set number to see line numbers):

35,38>>

which means "indent lines 35 through 38 two tabstops." You can likewise dedent lines with the "<" symbol.