Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to reformat braces automatically with Vim?

Tags:

vim

formatting

I would like to reformat some code which looks like this :

if (cond) {
  foo;
}

to

if (cond)
{
  foo;
} 

Since this is C code, I have been looking at cindent/cinoptions to use with = but it seems it does not deal with multiline rules.

I have been looking at formatoptionsto use with gq, and it does not seem to be possible either.

So is it possible using default Vim options or should I use a specific plugin or function ?

like image 978
Xavier T. Avatar asked Dec 07 '22 00:12

Xavier T.


1 Answers

:%s/^\(\s*\).*\zs{\s*$/\r\1{/

Breakdown:

^\(\s*\) = capture the whitespace at the beginning of the line

.* = everything else

\zs = start replacement after this

{ = open curly brace

\s*$ = trailing whitespace before line end

\r\1{ = newline, captured whitespace, brace

like image 163
Jay Avatar answered Dec 23 '22 11:12

Jay