如何关闭 Java 代码某些部分的 Eclipse 代码格式化程序?

发布于 2024-08-12 10:26:07 字数 1347 浏览 5 评论 0原文

我有一些 Java 代码,其中的 SQL 语句编写为 Java 字符串(请不要进行 OR/M 争论,嵌入式 SQL 就是这样 - 不是我的决定)。

我已将 SQL 语句在语义上分解为几行代码中的多个串联字符串,以便于维护。因此,而不是像这样:

String query = "SELECT FOO, BAR, BAZ FROM ABC WHERE BAR > 4";

我有这样的东西:

String query =
    "SELECT FOO, BAR, BAZ" +
    "  FROM ABC          " +
    " WHERE BAR > 4      ";

这种风格使 SQL 更容易阅读和维护(恕我直言),特别是对于较大的查询。例如,我可以将编辑器置于“覆盖”模式并相当轻松地就地修改文本。

请注意,此问题的普遍性超出了 SQL 的特定示例。任何使用任何垂直格式编写的代码,特别是表格结构,都容易被漂亮的打印机破坏。

现在,一些项目成员使用 Eclipse 编辑器,当他们格式化整个源文件时,语义格式通常会被破坏。

有没有办法指示 Eclipse 在格式化方面忽略某些源代码行?

我正在寻找诸如切换 Eclipse 格式化程序的特殊注释之类的东西。理想情况下,这样的注释可以配置为我们选择的任何内容,并且其他格式化程序也可以编程为尊重它:

// STOP-ECLIPSE-FORMATTING
String query =
    "SELECT FOO, BAR, BAZ" +
    "  FROM ABC          " +
    " WHERE BAR > 4      ";
// START-ECLIPSE-FORMATTING

显然,一个“解决方案”是让我们的团队成员标准化一些外部格式化程序,例如 JalopyJIndent< /a>,但这不是这个问题的目的(也不是我对这个项目的决定):我专门寻找一种临时避免 Eclipse 格式化程序的方法。

理想情况下,解决方案将允许我插入 Eclipse 格式化程序的指令,不需要使用 Eclipse 的团队成员进行任何 IDE 重新配置(除了可能选择与格式化程序无关的命令注释:STOP-ECLIPSE-格式化停止格式化)。

I've got some Java code with SQL statements written as Java strings (please no OR/M flamewars, the embedded SQL is what it is - not my decision).

I've broken the SQL statements semantically into several concatenated strings over several lines of code for ease of maintenance. So instead of something like:

String query = "SELECT FOO, BAR, BAZ FROM ABC WHERE BAR > 4";

I have something like:

String query =
    "SELECT FOO, BAR, BAZ" +
    "  FROM ABC          " +
    " WHERE BAR > 4      ";

This style makes the SQL much easier to read and maintain (IMHO), especially for larger queries. For example, I can put my editor into "overwrite" mode and modify the text in-place fairly easily.

Note that this issue generalizes beyond the particular example of SQL. Any code that is written with any vertical formatting, particularly tabular constructs, is susceptible to destruction by a pretty printer.

Now, some project members use the Eclipse editor and the semantic formatting is often destroyed when they format an entire source file.

Is there a way to instruct Eclipse to ignore certain lines of source with respect to formatting?

I'm looking for something like a special comment that toggles the Eclipse formatter. Ideally, such a comment could be configurable to be whatever we choose, and other formatters could be programmed to respect it as well:

// STOP-ECLIPSE-FORMATTING
String query =
    "SELECT FOO, BAR, BAZ" +
    "  FROM ABC          " +
    " WHERE BAR > 4      ";
// START-ECLIPSE-FORMATTING

Obviously, one "solution" is to have our team members standardize on some external formatter like Jalopy or JIndent, but that's not what this question is about (also, not my decision on this project): I'm specifically looking for a way to avoid the Eclipse formatter on an ad-hoc basis.

Ideally, a solution will allow me to insert instructions for the Eclipse formatter without requiring team members using Eclipse to do any IDE reconfiguration (other than possibly choosing a formatter agnostic command comment: STOP-ECLIPSE-FORMATTINGSTOP-FORMATTING).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

像极了他 2024-08-19 10:26:07

Eclipse 3.6 允许您通过放置特殊注释来关闭格式化,例如

// @formatter:off
...
// @formatter:on

必须在 Eclipse 首选项中“打开”开/关功能: Java 代码样式格式化程序。单击编辑关闭/开启标签,启用启用关闭/开启标签

还可以更改首选项中的魔术字符串 - 在此处查看 Eclipse 3.6 文档

更多信息

Java
代码风格

格式化程序

编辑

关闭/打开标签

此首选项允许您定义一个要禁用的标签和一个要启用格式化程序的标签(请参阅格式化程序配置文件中的“关闭/打开标签”选项卡):

在此处输入图像描述

您还需要启用 Java 格式设置 中的标志

注意:如果这些控件放置在Javadoc 注释。

Eclipse 3.6 allows you to turn off formatting by placing a special comment, like

// @formatter:off
...
// @formatter:on

The on/off features have to be turned "on" in Eclipse preferences: Java Code StyleFormatter. Click on Edit, Off/On Tags, enable Enable Off/On tags.

It's also possible to change the magic strings in the preferences — check out the Eclipse 3.6 docs here.

More Information

Java
Code Style

Formatter

Edit

Off/On Tags

This preference allows you to define one tag to disable and one tag to enable the formatter (see the Off/On Tags tab in your formatter profile):

enter image description here

You also need to enable the flags from Java Formatting

Note: Javadoc generation will fail if these controls are placed inside a Javadoc comment.

泪意 2024-08-19 10:26:07

据我所知,格式化程序上的 Eclipse 3.5 M4 有一个选项“从不加入行”,可以保留用户换行符。也许这就是你想要的。

否则还有这个丑陋的黑客

String query = //
    "SELECT FOO, BAR, BAZ" + //
    "  FROM ABC"           + //
    " WHERE BAR > 4";

AFAIK from Eclipse 3.5 M4 on the formatter has an option "Never Join Lines" which preserves user lines breaks. Maybe that does what you want.

Else there is this ugly hack

String query = //
    "SELECT FOO, BAR, BAZ" + //
    "  FROM ABC"           + //
    " WHERE BAR > 4";
清秋悲枫 2024-08-19 10:26:07

请参阅此答案

您可以使用另一种解决方案来抑制特定块注释的格式。在块注释的开头使用 /*- (注意连字符),如果您格式化文件的其余部分,格式不会受到影响。

/*-
 * Here is a block comment with some very special
 * formatting that I want indent(1) to ignore.
 *
 *    one
 *        two
 *            three
 */

来源:Oracle 文档

See this answer on SO.

There is another solution that you can use to suppress the formatting of specific block comments. Use /*- (note the hyphen) at the beginning of the block comment, and the formatting won't be affected if you format the rest of the file.

/*-
 * Here is a block comment with some very special
 * formatting that I want indent(1) to ignore.
 *
 *    one
 *        two
 *            three
 */

Source: Documentation at Oracle.

快乐很简单 2024-08-19 10:26:07

您可以将其配置为不连接已经换行的行,而不是关闭格式。与 Jitter 的响应类似,这是针对 Eclipse STS 的:

属性 → Java 代码样式 → 格式化程序 → 启用项目特定设置或配置工作区设置 → 编辑 → 换行(选项卡)→ 选中“从不加入已换行”

保存、应用。

在此处输入图像描述

Instead of turning the formatting off, you can configure it not to join already wrapped lines. Similar to Jitter's response, here's for Eclipse STS:

Properties → Java Code Style → Formatter → Enable project specific settings OR Configure Workspace Settings → Edit → Line Wrapping (tab) → check "Never join already wrapped lines"

Save, apply.

enter image description here

淡淡绿茶香 2024-08-19 10:26:07

您必须启用添加格式化程序标签的功能。在菜单栏中转到:

Windows

首选项
Java

代码风格

格式化程序

编辑 按钮。选择最后一个选项卡。注意“开/关”框并通过复选框启用它们。

You have to turn on the ability to add the formatter tags. In the menubar go to:

Windows

Preferences
Java

Code Style

Formatter

Press the Edit button. Choose the last tab. Notice the On/Off box and enable them with a checkbox.

忆梦 2024-08-19 10:26:07

如果将加号放在行的开头,则其格式会有所不同:

String query = 
    "SELECT FOO, BAR, BAZ" 
    +    "  FROM ABC"           
    +    " WHERE BAR > 4";

If you put the plus sign on the beginning of the line, it formats differently:

String query = 
    "SELECT FOO, BAR, BAZ" 
    +    "  FROM ABC"           
    +    " WHERE BAR > 4";
獨角戲 2024-08-19 10:26:07

每行以双斜杠“//”结束。这将阻止日食将它们全部移动到同一条线上。

End each of the lines with a double slash "//". That will keep eclipse from moving them all onto the same line.

怎言笑 2024-08-19 10:26:07

我使用固定宽度的字符串部分(用空格填充)以避免格式化程序弄乱我的 SQL 字符串缩进。这会给你带来混合的结果,并且在 SQL 中不忽略空格的情况下不起作用,但可能会有所帮助。

    final String sql = "SELECT v.value FROM properties p               "
            + "JOIN property_values v ON p.property_id = v.property_id "
            + "WHERE p.product_id = ?                                  "
            + "AND v.value        IS NOT NULL                          ";

I'm using fixed width string-parts (padded with whitespace) to avoid having the formatter mess up my SQL string indentation. This gives you mixed results, and won't work where whitespace is not ignored as it is in SQL, but can be helpful.

    final String sql = "SELECT v.value FROM properties p               "
            + "JOIN property_values v ON p.property_id = v.property_id "
            + "WHERE p.product_id = ?                                  "
            + "AND v.value        IS NOT NULL                          ";
年少掌心 2024-08-19 10:26:07

替代方法:在 Eclipse 3.6 中,在“换行”和“常规设置”下有一个选项“从不加入已换行”。这意味着格式化程序将换行长行,但不会撤消您已有的任何换行。

Alternative method: In Eclipse 3.6, under "Line Wrapping" then "General Settings" there is an option to "Never join already wrapped lines." This means the formatter will wrap long lines but not undo any wrapping you already have.

许久 2024-08-19 10:26:07

@xpmatteo 有禁用部分代码的答案,但除此之外,默认的 Eclipse 设置应该设置为仅格式化已编辑的代码行而不是整个文件。

Preferences->Java->Editor->Save Actions->Format Source Code->Format Edited Lines

这本来可以防止这种情况发生,因为您的同事正在重新格式化他们实际上没有更改的代码。这是一个很好的做法,可以防止出现使源代码管理上的差异变得无用的事故(当由于较小的格式设置差异而重新格式化整个文件时)。

如果关闭开/关标签选项,它也会阻止重新格式化。

@xpmatteo has the answer to disabling portions of code, but in addition to this, the default eclipse settings should be set to only format edited lines of code instead of the whole file.

Preferences->Java->Editor->Save Actions->Format Source Code->Format Edited Lines

This would have prevented it from happening in the first place since your coworkers are reformatting code they didn't actually change. This is a good practice to prevent mishaps that render diff on your source control useless (when an entire file is reformatted because of minor format setting differences).

It would also prevent the reformatting if the on/off tags option was turned off.

堇年纸鸢 2024-08-19 10:26:07

虚拟注释,在您想要换行的地方添加 // ,非常棒!

  1. @formatter: off 添加从代码到编辑器的引用。在我看来,代码不应该有这样的引用。

  2. 无论使用何种格式化工具,虚拟注释 (//) 都将起作用。无论 Eclipse 还是 InteliJ 或者您使用的任何编辑器。这甚至可以与非常好的 Google Java 格式

    一起使用

  3. 幻影评论 (/ /) 将适用于您的整个应用程序。如果您也有 Javascript,并且可能使用类似 JSBeautifier 的东西。您也可以在 Javascript 中使用类似的代码样式。

  4. 实际上,您可能确实需要格式化,对吗?您想要删除混合制表符/空格和尾随空格。您想要根据代码标准缩进行。 你不想要的是一长串。这就是幻像评论给你的!

The phantom comments, adding // where you want new lines, are great!

  1. The @formatter: off adds a reference from the code to the editor. The code should, in my opinion, never have such references.

  2. The phantom comments (//) will work regardless of the formatting tool used. Regardless of Eclipse or InteliJ or whatever editor you use. This even works with the very nice Google Java Format

  3. The phantom comments (//) will work all over your application. If you also have Javascript and perhaps use something like JSBeautifier. You can have similar code style also in the Javascript.

  4. Actually, you probably DO want formatting right? You want to remove mixed tab/space and trailing spaces. You want to indent the lines according to the code standard. What you DONT want is a long line. That, and only that, is what the phantom comment gives you!

无声静候 2024-08-19 10:26:07

在 VS Code 中,

在格式化程序 xml 设置中设置以下属性

<setting id="org.eclipse.jdt.core.formatter.use_on_off_tags" value="true"/>

,然后在代码中使用以下标签来打开和关闭格式化

            // @formatter:off
            //Create Payment Transaction
            payTxn = EN_PaymntTxn.builder()
                    .orderId(paymReq.getOrderId())
                    .paymentMode(paymReq.getPaymentMode())
                    .amount(paymReq.getAmount())
                    .paymentStatus("PAID")
                    .referenceNumber(UUID.randomUUID().toString())
                    .timestamp(Instant.now())
                    .build();
            // @formatter:on

In VS Code

Set the below property in you formatter xml settings

<setting id="org.eclipse.jdt.core.formatter.use_on_off_tags" value="true"/>

Then in your Code use the below tags to switch on and off formatting

            // @formatter:off
            //Create Payment Transaction
            payTxn = EN_PaymntTxn.builder()
                    .orderId(paymReq.getOrderId())
                    .paymentMode(paymReq.getPaymentMode())
                    .amount(paymReq.getAmount())
                    .paymentStatus("PAID")
                    .referenceNumber(UUID.randomUUID().toString())
                    .timestamp(Instant.now())
                    .build();
            // @formatter:on
浅沫记忆 2024-08-19 10:26:07

不太漂亮,但也适用于默认设置和第一行:

String query = "" +
    "SELECT FOO, BAR, BAZ" +
    "  FROM ABC          " +
    " WHERE BAR > 4      ";

Not so pretty but works with default settings and for the first line as well:

String query = "" +
    "SELECT FOO, BAR, BAZ" +
    "  FROM ABC          " +
    " WHERE BAR > 4      ";
罪#恶を代价 2024-08-19 10:26:07

这个技巧有效:

String x = "s" + //Formatter Hack
    "a" + //
    "c" + //
    "d";

我建议不要使用格式化程序。 糟糕的代码应该看起来很糟糕,而不是人为地好。好的代码需要时间。你不能在质量上作弊。格式化是源代码质量的一部分。

This hack works:

String x = "s" + //Formatter Hack
    "a" + //
    "c" + //
    "d";

I would suggest not to use the formatter. Bad code should look bad not artificially good. Good code takes time. You cannot cheat on quality. Formatting is part of source code quality.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文