[c] How can I autoformat/indent C code in vim?

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?

This question is related to c vim code-formatting

The answer is


The plugin vim-autoformat lets you format your buffer (or buffer selections) with a single command: https://github.com/Chiel92/vim-autoformat. It uses external format programs for that, with a fallback to vim's indentation functionality.


I like to use the program Artistic Style. According to their website:

Artistic Style is a source code indenter, formatter, and beautifier for the C, C++, C# and Java programming languages.

It runs in Window, Linux and Mac. It will do things like indenting, replacing tabs with spaces or vice-versa, putting spaces around operations however you like (converting if(x<2) to if ( x<2 ) if that's how you like it), putting braces on the same line as function definitions, or moving them to the line below, etc. All the options are controlled by command line parameters.

In order to use it in vim, just set the formatprg option to it, and then use the gq command. So, for example, I have in my .vimrc:

autocmd BufNewFile,BufRead *.cpp set formatprg=astyle\ -T4pb

so that whenever I open a .cpp file, formatprg is set with the options I like. Then, I can type gg to go to the top of the file, and gqG to format the entire file according to my standards. If I only need to reformat a single function, I can go to the top of the function, then type gq][ and it will reformat just that function.

The options I have for astyle, -T4pb, are just my preferences. You can look through their docs, and change the options to have it format the code however you like.

Here's a demo. Before astyle:

int main(){if(x<2){x=3;}}

float test()
{
if(x<2)
x=3;
}

After astyle (gggqG):

int main()
{
    if (x < 2)
    {
        x = 3;
    }
}

float test()
{
    if (x < 2)
        x = 3;
}

Hope that helps.


Their is a tool called indent. You can download it with apt-get install indent, then run indent my_program.c.


I find that clang-format works well.

There are some example keybindings in the clang documentation

I prefer to use the equalprg binding in vim. This allows you to invoke clang-format with G=gg or other = indent options.

Just put the following in your .vimrc file:

autocmd FileType c,cpp setlocal equalprg=clang-format

The builtin command for properly indenting the code has already been mentioned (gg=G). If you want to beautify the code, you'll need to use an external application like indent. Since % denotes the current file in ex mode, you can use it like this:

:!indent %

I wanted to add, that in order to prevent it from being messed up in the first place you can type :set paste before pasting. After pasting, you can type :set nopaste for things like js-beautify and indenting to work again.


Maybe you can try the followings $indent -kr -i8 *.c

Hope it's useful for you!


I like indent as mentioned above, but most often I want to format only a small section of the file that I'm working on. Since indent can take code from stdin, its really simple:

  1. Select the block of code you want to format with V or the like.
  2. Format by typing :!indent.

astyle takes stdin too, so you can use the same trick there.


Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to vim

Why does using from __future__ import print_function breaks Python2-style print? How to run vi on docker container? How can I install MacVim on OS X? Find and replace strings in vim on multiple lines Running Python code in Vim How do I set the default font size in Vim? Move cursor to end of file in vim Set encoding and fileencoding to utf-8 in Vim How to select all and copy in vim? Why I've got no crontab entry on OS X when using vim?

Examples related to code-formatting

How do you format code on save in VS Code How do you format code in Visual Studio Code (VSCode) JavaScript Chart.js - Custom data formatting to display on tooltip Is there a command for formatting HTML in the Atom editor? How to auto-indent code in the Atom editor? Code formatting shortcuts in Android Studio for Operation Systems How to auto-format code in Eclipse? How to format code in Xcode? What is the proper way to format a multi-line dict in Python? How do I format XML in Notepad++?