Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 277 Vote(s) - 3.67 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I autoformat/indent C code in vim?

#1
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?
Reply

#2
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][1]. Since `%` denotes the current file in ex mode, you can use it like this:

:!indent %


[1]:

[To see links please register here]

Reply

#3
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.


Reply

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

Hope it's useful for you!
Reply

#5
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 <kbd>V</kbd> or the like.
2. Format by typing `:!indent`.

`astyle` takes stdin too, so you can use the same trick there.
Reply

#6
I find that `clang-format` works well.

There are some example keybindings in the [clang documentation](

[To see links please register here]

)

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
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through