How can I autoformat/indent C code in vim?
Solution 1
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.
Solution 2
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.
Solution 3
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 %
Solution 4
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
Solution 5
The plugin vim-autoformat lets you format your buffer (or buffer selections) with a single command: https://github.com/vim-autoformat/vim-autoformat. It uses external format programs for that, with a fallback to vim's indentation functionality.
Related videos on Youtube
Yongwei Xing
Updated on July 14, 2021Comments
-
Yongwei Xing almost 3 years
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?
-
Derek about 9 yearsFor anyone looking to format and not just indent the code, the second answer (mine) addresses that. If you just want to fix indenting, the accepted answer is the simplest way.
-
-
N 1.1 about 14 yearsthis only indents the code. can something not be done to AUTOFORMAT the entire thing?
-
Lazer over 13 years@Ton van: See my answer for the difference (Could not have explained here in comments).
-
derGral almost 13 yearsIs there anything like this for other formats; ruby, xml, json, etc.?
-
chtenb about 11 years@Ryan check vim-autoformat, see answer below. BTW vim-autoformat also uses astyle among others.
-
oligofren about 11 years-1 This only fixes indentation, not formatting (which was what being asked for).
-
Amir Rachum about 11 years@oligofren The OP's example only included indentation errors and he accepts the answer, so I guess that's what he meant.
-
Amir Rachum about 11 years@oligofren Also, he specified he copies the code from another file, which makes indentation problems more likely than other formatting problems.
-
xor007 over 9 yearsSuggested edit: change title to "Auto indent C code in Vim" otherwise, some people (like me) find this answer while looking for the AStyle answer.
-
Frank A. about 9 yearsGreat, clear explanation. I will be using this command often.
-
jmmk over 8 yearsI haven't known such combination. I used == for single line, but I thought that = works only in visual mode,
-
user3640967 over 8 yearsThank you! I was beginning to think I was the only person in the word who didn't want their opening brackets on the same line as the function declaration!
-
domi91c over 7 yearsYou can then hit <C-o><C-O> to go back to where you were.
-
mellow-yellow about 6 yearsIn "Ex mode" (which you typically enter with :), the equivalent is
:%normal ==
(where % means all lines in the current buffer--aka file in vim's memory--and == means autoindent the current line). This approach allows you to limit auto-indent by line number, like:5,10normal ==
(meaning, lines 5-10). And you can abbreviatenormal
tonorm
to save typing, as well eliminate the space::%norm==
. -
Eric about 6 yearsNeed to install it first, e.g for ubuntu 16.04+:
sudo apt install clang-format
-
a'r about 4 yearsI use
:set paste!
for this, which toggles the paste value instead of setting it. This makes it easier to turn off as you can simply scroll back a few commands and press enter. -
71GA about 3 yearsThis GNU tool sucks is weird... I did not like it!
-
user26742873 about 3 yearsWarning for readers: this set tabstop to
8
. Tryastyle
. -
Amir Rachum about 3 years@asuka you can
set tabstop=4
. -
Roel Van de Paar almost 2 yearsBefore using this command, ensure to do
sudo apt install indent
to install the indent utility.