From Vim Tips Wiki
It's possible to reformat an entire file, or a section of a file, using Vim's built-in = filter. Vim veterans often find this operator to be one of the most useful in their repertoire, but so common that it becomes second-nature and is rarely mentioned.
In normal mode, typing
gg=G will reindent the entire file. This is a special case;
= is an operator. Just like
y, it will act on any text that you move over with a cursor motion command. In this case,
gg positions the cursor on the first line, then
=G re-indents from the current cursor position to the end of the buffer.
In visual mode, typing
= will fix indentation of the current section. Thus, an equivalent but less efficient command to accomplish the same as
gg=G in normal mode, would be
ggVG to select the entire buffer in visual mode, followed by
= to re-indent the entire selection.
If you often re-indent large areas (like the entire file, or a large text object), it can be useful to map a key to do it for you, using marks to restore your position. To format and return the same line where you were, just add this mapping to your vimrc:
map <F7> mzgg=G`z
Now, just press <F7> whenever you want to format your file.
= operator works using whatever automatic indentation settings you have turned on. If you don't have this set up, see indenting source code before using.
 See also
- :help 30.3
- :help indent-expression
- :help indent.txt
- Indenting source code#Methods for automatic indentation