Cloud
Cloud

Reputation: 19333

VIM - Reformatting indentation and braces

When working with blocks of code in VIM, I'm able to easily re-indent blocks of code via selecting a region in visual mode (SHIFT+v), then just hit =. This re-tabs lines of code, uses the correct indentation depths, hard-tabs vs spaces, etc.

I have a large set of functions I need to re-factor, and I have several blocks of code with braces on the same line as if/else keywords, ie:

if(something) {
  doFunction(something);
} else if(somethingElse) {
  doFunction(somethingElse);
} else {
  // default stuff to do
}

And I would like to change the brace and spacing style to:

if ( something ) {
  doFunction( something);
}
else if ( somethingElse )
{
  doFunction( somethingElse );
}
else
{
  // default stuff to do
}

The differences include:

Is there a way to set this style as the default in VIM, and to also have re-indentation commands change the style to match the latter of the two I've provided? I've found tools to enforce things like line endings, tabs-vs-spaces, etc, but not style details like those shown above.

Thank you.

Upvotes: 5

Views: 1374

Answers (1)

Vitor
Vitor

Reputation: 1976

The indentation scripts in vim are not constructed for so complex tasks. I would advise you to use the indent command, in particular the following arguments:

-prs, --space-after-parentheses
Put a space after every '(' and before every ')'.
See STATEMENTS.
-sai, --space-after-if
Put a space after each if.
See STATEMENTS.

You should read the command's man page for more details.

Obviously, this command can be used to filter the buffer's content using:

:%!indent

Upvotes: 5

Related Questions