Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • Having the opening/closing braces on their own dedicated line
  • The argument to if, else if, and functions has a space separating the beginning and end of the argument list from the surrounding round brackets.
  • There is a space between if/else if and the argument brackets, but not for function names and the argument brackets.

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.

like image 518
Cloud Avatar asked Jun 10 '15 18:06

Cloud


1 Answers

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
like image 157
Vitor Avatar answered Oct 22 '22 20:10

Vitor