Take the 2-minute tour ×

For example, to render:

while (head == tail) { head++; a[head] = 0 }


while (head == tail)
    a[head] = 0
share|improve this question
add comment

3 Answers 3

up vote 6 down vote accepted

(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.)

Vim's = 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 d and 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:

indent Install indent

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.

share|improve this answer
Nice answer, thank you! –  trVoldemort May 7 '11 at 12:06
add comment

like in any other text editor, VIM doesn't do that automatically if you meant that.

Open file with vim, press i for insert now you can edit freely, when done press Esc to exit insert mode and then to close and save the document write :wq for write,quit.

share|improve this answer
add comment

This vim plugin uses external formatters to format code within vim. It's therefore stronger than vim's indentation machinery.


share|improve this answer
add comment

Your Answer


