Basil Bourque
Basil Bourque

Reputation: 339482

Reformat a one-line method to a single line of text in IntelliJ

I want IntelliJ 2019.x to change a single-line method such as this:

public String getFileName ( )
{
    return this.fileName;
}

…to be a single line of text, like this:

public String getFileName ( ) { return this.fileName; }

I want the formatting to be permanent. Is there some code-style or other setting for this?

I no not want to “collapse” it temporarily, only to have it expand back to four lines when I click on it. This collapsing feature has been covered here and here.

Upvotes: 0

Views: 1072

Answers (2)

Bas Leijdekkers
Bas Leijdekkers

Reputation: 26522

The following Code Style setting is available:
Preferences | Editor | Code Style | Java | Wrapping and Braces | Keep when reformatting | Simple methods in one line
Enable it to keep the formatting of any methods formatted in your desired style.

Unfortunately there is no code style setting to format methods with a single line body on a single line. But there is the workaround of using Structural Search & Replace for this formatting using a template like this:

<replaceConfiguration name="constructors &amp; methods" text="$ReturnType$ $Method$($ParameterType$ $Parameter$) {&#10;    $st$;&#10;}" recursive="false" caseInsensitive="true" type="JAVA" pattern_context="member" reformatAccordingToStyle="true" shortenFQN="true" replacement="$ReturnType$ $Method$($ParameterType$ $Parameter$) { $st$; }">
  <constraint name="__context__" within="" contains="" />
  <constraint name="ReturnType" minCount="0" within="" contains="" />
  <constraint name="Method" within="" contains="" />
  <constraint name="ParameterType" within="" contains="" />
  <constraint name="Parameter" minCount="0" maxCount="2147483647" within="" contains="" />
  <constraint name="st" within="" contains="" />
</replaceConfiguration>

Copy the template above and open Edit | Find | Replace Structurally. Next import the template by invoking Import Template from Clipboard (under the cog menu) and click Find.

This will find all methods with a single line body and replace them with the same method formatted on one line.

Upvotes: 2

seenukarthi
seenukarthi

Reputation: 8664

You can disable IDE's default formatting for a particular block by wrapping the code between //@formatter:off and //@formatter:on

Ref: Official Document

Upvotes: 2

Related Questions