Wolf7176
Wolf7176

Reputation: 317

Is there a way to change the way vim auto formats c,c++ code

For example -- when i do gg=G on

int main()
{ 
return 0; 
}

it will change it to

int main()
{
   return 0;
}

What I want is --

int main(){
   return 0;
}

The '{' should be on the funciton prototype line

Upvotes: 1

Views: 206

Answers (3)

FDinoff
FDinoff

Reputation: 31429

To go along with Cubic's Answer

To use astyle without modifying file you can use the command gq and the option `formatprg'

formatprg specifies an external program that will be used to format the buffer. After the command has been run the buffer will be replaced by the output of the program.

For exmample: To set this to work with c files you can put the following in your vimdc

autocmd FileType *.c set formatprg=astyle\ --style=kr

Note: the allows you to pass the different command line options to style.

Now to use this in your file you can type gggqG to apply the formatting to the whole file.

Upvotes: 2

Cubic
Cubic

Reputation: 15673

You could use astyle, with something like

nnoremap <A-S-f> :w<CR>:!astyle % --style=java<CR>:edit<CR>

Which binds it to Alt-Shift-f (note that this saves/reloads the file which may not always be what you want, there are ways around that but I didn't want to go too much into this right now).

Of course, you'll have to figure out what options to pass to astyle for your preferred formatting yourself.

Upvotes: 1

Kent
Kent

Reputation: 195059

AFAIK:

= re-adjusts indent, it doesn't reformat your codes' style. e.g, the code block style (your question); or add/removing empty lines; add/remove spaces e.g. a=2 -> a = 2 ...

you could do this to change the { before/after you gg=G:

:%s/)\n\s*{\s*$/) {/g

you could also write them into one line, and make a mapping to do it in one short.

e.g, this line:

:%s/)\n\s*{\s*$/) {/g|norm! gg=G

will turn:

int main()
{ 
if(foo)
{
return 1;
}
if(a>0)
return a;
for(int i=1;i<20;i++)
{
int foo=0;
foo=i;
}
return 0; 
}

into

int main() {
    if(foo) {
        return 1;
    }
    if(a>0)
        return a;
    for(int i=1;i<20;i++) {
        int foo=0;
        foo=i;
    }
    return 0; 
}

EDIT

My original answer suggested :g/)$/j to "join" the two lines, but I found it is not safe, for example:

if (a>0)
  return a;

will be turned into

if (a>0) return a;

which is not expected by OP.

Upvotes: 2

Related Questions