4

For example, to render:

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

into

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

3 Answers 3

7

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

0
1

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

vim-autoformat on GitHub

0

Like any other text editor, VIM doesn't do that automatically.

Open a file with vim, press i for insert, and 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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .