When I copy code from another file, the formatting is messed up, like this:
fun()
{
for(...)
{
for(...)
{
if(...)
{
}
}
}
}
How can I autof
Maybe you can try the followings $indent -kr -i8 *.c
Hope it's useful for you!
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.
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 %
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 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
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:
:!indent
.astyle
takes stdin too, so you can use the same trick there.