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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With