How can I autoformat/indent C code in vim?

Yongwei Xing picture Yongwei Xing · Mar 1, 2010 · Viewed 166.1k times · Source

When I copy code from another file, the formatting is messed up, like this:

fun()
{
for(...)
{
for(...)
{
if(...)
{
}
}
}
}

How can I autoformat this code in vim?

Answer

Amir Rachum picture Amir Rachum · Mar 1, 2010

Try the following keystrokes:

gg=G

Explanation: gg goes to the top of the file, = is a command to fix the indentation and G tells it to perform the operation to the end of the file.