How can I autoformat/indent C code in vim?

后端 未结 9 2332
青春惊慌失措
青春惊慌失措 2020-11-29 14:20

When I copy code from another file, the formatting is messed up, like this:

fun()
{
for(...)
{
for(...)
{
if(...)
{
}
}
}
}

How can I autof

相关标签:
9条回答
  • 2020-11-29 14:51

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

    Hope it's useful for you!

    0 讨论(0)
  • 2020-11-29 14:52

    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.

    0 讨论(0)
  • 2020-11-29 14:53

    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 %
    
    0 讨论(0)
  • 2020-11-29 14:55

    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.

    0 讨论(0)
  • 2020-11-29 14:56

    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
    
    0 讨论(0)
  • 2020-11-29 14:58

    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.

    0 讨论(0)
提交回复
热议问题