7

When I write code, I'd like to use ANSI C style, but the code style in c.vim template is K&R.

Where can I get another template or any other plugin instead of c.vim?

Igor
  • 26,650
  • 27
  • 89
  • 114
Yucoat
  • 183
  • 1
  • 1
  • 6
  • Also look into GNU indent, astyle, clang-format, etc https://superuser.com/questions/125614/command-line-tool-to-format-c-code-on-ubuntu – qwr Jul 31 '22 at 05:57

2 Answers2

6

You should check :help cinoptions-value and define your own C style.

IIRC, you need to set cindent so that cinoptions are taken into account.

FWIW, it is what I do when opening a C or h file :

setlocal cinoptions={0,:1s,g1s,t0,(0,=.5s
setlocal noautoindent
setlocal nosmartindent
setlocal cindent
Xavier T.
  • 40,509
  • 10
  • 68
  • 97
  • Accoding to `:help C-indenting`, "There are in fact four main methods available for indentation, each one overrides the previous if it is enabled" - so it seems that lines `setlocal noautoindent`and `setlocal nosmartindent` are not needed. – mMontu Dec 06 '11 at 15:33
4

There is a great program called Artistic Style, or astyle, that does a whole bunch of code formatting for you. You can tell it if you want spaces around operators, opening braces on the same line as loops, how you want to indent, etc. I talk about it in a bit more detail here: Auto format C. It is easy to use, but the options allow you to set up a huge variety of coding styles, including some pre-defines for common styles, like K&R.

Basically, once you set it up in vimrc, just type gggqG to reformat your file. (gg to go to the top, gq to begin formatting, G to have it format all the way to the end.)

This doesn't help formatting while you code, but it can be a life-saver when having to work with a pre-existing file that's not formatted correctly, or quickly cleaning up your own code.

Community
  • 1
  • 1
Derek
  • 3,087
  • 1
  • 21
  • 23