Is there a way to automatically format curly braces using Vim?

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

if (cond) { foo; } 

to

 if (cond) { foo; } 

Since this is C code, I looked at cindent / cinoptions for use with = , but it does not seem to be related to multi-line rules.

I was considering formatoptions for use with gq , and this is also not possible.

So is it possible to use the default Vim options or use a specific plugin or function?

+4
source share
4 answers
 :%s/^\(\s*\).*\zs{\s*$/\r\1{/ 

Structure:

^\(\s*\) = grab a space at the beginning of a line

.* = everything else

\zs = start replacing after this

{ = open braces

\s*$ = end space before end of line

\r\1{ = newline, trapped spaces, parentheses

+4
source

I don't know if this solves your problem completely, but if this is a one-time operation, you can try regular expressions:

 :%s/^\(\s*\)\(.*)\)\s*{\s*$/\1\2^M\1{/ 

Note that ^M is a control character that is usually generated (depending on your terminal) by pressing CTRL-V and then ENTER .

EDIT . As pointed out in the comments by Jay and Zyx, \r is the best way to insert a line break in a replaced string. I did not know about this, thank you very much for the hint.

+5
source

If you install Artistic style , you can do something like:

 :set formatprg=astyle\ -b 

Then use gq to reformat the code snippets. Character text

If you want this to be included every time you edit the C file, you can add the following to your .vimrc file.

 autocmd BufNewFile,BufRead *.c set formatprg=astyle\ -b 
+4
source

I don't know if you can do this inside vim itself, but you can try the BSD indent command with the -bl option. Using the cursor on the first { you can enter ! % indent -bl Enter .

+1
source

Source: https://habr.com/ru/post/1332377/


All Articles