(Firstly, you need a semicolon before the last
} in order for this to be valid C; the semicolon should be thought of as terminating statements in C, rather than as separating statements. Smart automatic indentation may not work properly unless you add that semicolon.)
= command (
:help =) can be used to run code through an automatic indentation program, though it requires some configuration. The basic idea is that you set the
equalprg option (
:help 'equalprg') to a program that applies the indentation you want, and then use
= in command mode to run it.
= works like other Vim motion-based commands such as
y; for example,
== indents the current line,
=ap indents a paragraph, or you can use a visual range:
ggVG= indents the whole file.
Now, by default,
equalprg is set to the empty string, which only does basic per-line indentation built into Vim. To do the kind of thing you're asking for, the best tool for the job is
indent has a vast array of options for various indentation styles; by default it uses the GNU coding style, but you'll probably want to customise it to suit your project's preferences. See
man indent for details. To include spaces in the value of
equalprg, you need to quote them with a backslash, so for example if you wanted to use K&R indentation style you would use
:set equalprg=indent\ -kr.
You can also have the '=' command choose the appropriate indentation based on the file type, by using
:filetype indent on - type
:help filetype within vim for more info.
:set autoindent will tell vim to indent as you type. Adding either of these commands (minus the leading ':') to your ~/.vimrc file will make them permanent.