Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 481
Yongwei Xing Avatar asked Mar 01 '10 12:03

Yongwei Xing


People also ask

How do I indent C in vim?

First, go to the start point of codes to be formatted, then press v to start selection. Second, go to the end point. Third, press = to format the codes that have been selected. All braces and indentations will be aligned.

How do I turn off indent in vim?

vim" in 'runtimepath'. This disables auto-indenting for files you will open. It will keep working in already opened files. Reset 'autoindent', 'cindent', 'smartindent' and/or 'indentexpr' to disable indenting in an opened file.

How do I indent all codes in Vim?

Just go to visual mode in vim , and select from up to down lines after selecting just press = , All the selected line will be indented.


2 Answers

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.

like image 64
Amir Rachum Avatar answered Oct 21 '22 06:10

Amir Rachum


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.

like image 30
Derek Avatar answered Oct 21 '22 08:10

Derek