Reformat vs reindent in Vim

When I see questions about Vim and reformatting and reindenting, I usually feel confusion. But it is pretty easy.

Reindenting, done with = key, is a process of shifting line indetation without inserting any line ends - no hard wrapping. Simply put, beginning columns of the selected lines can change, but the content cannot.

On the other hand, reformatting is complete rewrite of a selected piece of code. Simply put, everything is deleted and written again according to the language rules defined in Vim. Easy, huh?

The usual patern for reindentation is to go to the beginning of the file (gg), change to line selection (V), go to the end of the file (G) and perform reidentation (=).

That's indenting in vim: ggVG=

Reformatting pattern starts with the very same keys (ggVG), but instead of equal key, you do gq - reformat Vim command.

That's formatting in vim: ggVGgq

This works out-of-box in every Vim instance, even with plain text. Only when Vim does not understand the programming language you need to provide it with correct formatting rules (usually bunch of .vim files which have to go to the .vim directory structure).

There is even shorter version how to do both, let me show you reindentation: qqG=. Or maybe you like longer version, which returns your caret to the last position before the action: mzgg=G`z. And there are many more options... ;-)

Isn't Vim cool? It is.
27 October 2011 | vim