Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntelliJ: foreach Live Template code formatting

In IntelliJ idea when I insert the foreach live template it will put newline after ':' so it will look like this:

  for ( :
    ) {

    }

I want to have the for statement on one line like this:

  for ( : ) {

  }

I tried to change my code formatting preferences, but could not figure out what setting influences this particular case.

So my question is how to set code style options to achieve the desired behavior?

like image 878
jira Avatar asked Apr 19 '16 17:04

jira


3 Answers

Use the iter live template rather than the foreach. foreach is under the Android block, and the default style for that is what adds the newline.

Update:

As of at least 2018.1.1 (not sure when it was added), you can now type the <name of your collection>.for then tab and it will expand out into a foreach loop.

It's also brought in the same surrounding/expansion for stuff like <array>.stream then tab and probably a few others I'm not aware of.

like image 125
Justin Reeves Avatar answered Nov 20 '22 00:11

Justin Reeves


  • Go to File -> Settings -> Editor -> Code Style -> Live Template.
  • At the right side open Android list and stay on foreach .
  • In the Options area uncheck Reformat according to style.

You can see how to do it in the IntelliJ IDEA settings foreach style

like image 41
Andrey Zinovich Avatar answered Nov 20 '22 00:11

Andrey Zinovich


You can change the template for the enhanced for loop in IntelliJ by changing the setting in Live Templates.

Go to File -> Settings -> Editor -> Live Templates. In the right side, choose iterations -> "iter (Iterate Iterable | Array in J2SDK 5.0 syntax)". At the bottom you can see the template text and you can change it by introducing the newline where you want it. Change

for ($ELEMENT_TYPE$ $VAR$ : $ITERABLE_TYPE$) {
    $END$
}

to

for ($ELEMENT_TYPE$ $VAR$ :
     $ITERABLE_TYPE$) {
  $END$
}

and apply your changes.

In the source code editor, choose Code -> Insert Live Template... -> iter, then IntelliJ will insert the code template as you've specified, with boxes around the variable names for changing them.

for (String arg :
        args)
{

}
like image 7
rgettman Avatar answered Nov 19 '22 23:11

rgettman