【问题标题】:Reformat a one-line method to a single line of text in IntelliJ在 IntelliJ 中将单行方法重新格式化为单行文本
【发布时间】:2019-11-28 03:28:59
【问题描述】:

我想让 IntelliJ 2019.x 改成这样的单行方法:

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

…成为单行文本,像这样:

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

我希望格式是永久性的。是否有一些代码样式或其他设置?

我没有想暂时“折叠”它,只是在我点击它时让它展开回四行。 herehere 已涵盖此折叠功能。

【问题讨论】:

    标签: intellij-idea


    【解决方案1】:

    以下代码样式设置可用:
    Preferences | Editor | Code Style | Java | Wrapping and Braces | Keep when reformatting | Simple methods in one line
    启用它以将任何方法的格式设置为您想要的样式。

    不幸的是,没有代码样式设置来格式化单行单行体的方法。但是有一种使用结构搜索和替换的解决方法,使用这样的模板:

    <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>
    

    复制上面的模板并打开Edit | Find | Replace Structurally。接下来通过调用Import Template from Clipboard(在cog 菜单下)导入模板并单击Find。

    这将找到所有具有单行正文的方法,并将它们替换为在一行中格式化的相同方法。

    【讨论】:

      【解决方案2】:

      您可以通过将代码包装在 //@formatter:off//@formatter:on 之间来禁用 IDE 对特定块的默认格式

      参考:Official Document

      【讨论】:

        猜你喜欢
        • 2019-04-05
        • 2021-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-15
        • 2017-12-21
        • 2018-04-28
        • 1970-01-01
        相关资源
        最近更新 更多