简体   繁体   English

在Eclipse Mars中格式化Java代码的特定部分

[英]Format specific part of Java code in Eclipse Mars

I am able to format my Java code by configuring it in Save Actions. 我可以通过在“保存操作”中配置Java代码来设置其格式。 What I get after Saving the file is that the whole code gets formatted according to my settings. 保存文件后,我得到的是整个代码都根据我的设置进行了格式化。 What I need is, that only a part of code gets formatted according to the settings. 我需要的是,只有一部分代码会根据设置进行格式化。 Say, there are 10 methods in my code and I add one more to it. 说,我的代码中有10种方法,我又添加了一种。 What I want is that only my 11th method gets formatted and the previous 10 gets untouched. 我想要的是仅格式化我的第11种方法,而前10种保持不变。 Is that possible? 那可能吗? I am using Eclipse Mars NOTE: The format includes, removing unnecessary casts, parenthesis, etc. 我正在使用Eclipse Mars 注:该格式包括删除不必要的强制转换,括号等。

Source code formatting on save can be limited to edited lines only : 保存时的源代码格式只能限于已编辑的行

在此处输入图片说明

The other save actions however are applied to the whole file. 但是,其他保存操作将应用于整个文件。

Select the text you want to format, and press Ctrl + Shift + F to format the selection. 选择要设置格式的文本,然后按Ctrl + Shift + F设置选择的格式。

Alternatively you can do Ctrl + I on the selected text to just correct the indentation. 或者,您可以对所选文本执行Ctrl + I ,以更正缩进。

I always use CTRL + SHIFT + F to format my code. 我总是使用CTRL + SHIFT + F格式化我的代码。 In eclipse you can just drag your mouse and select the code you want, then press CTRL + SHIFT + F . 在Eclipse中,您只需拖动鼠标并选择所需的代码,然后按CTRL + SHIFT + F That way it will just format the selected code. 这样,它将仅格式化所选代码。

Normal the Ctrl + Shift + F will format the current class. 正常情况下, Ctrl + Shift + F将格式化当前类。 Or when a selection is made, only that selected part will be formated. 或者当选择时, 只有选定的部分将被格式化。

To make a quick selection, from the current place, use Ctrl + Shift + Arrow-Up to make it bigger. 要从当前位置进行快速选择,请使用Ctrl + Shift + 向上箭头将其放大。 Or Ctrl + Shift + Arrow-Down to make it smaller again. 按Ctrl + Shift + 向下箭头使其再次变小。

Telling Eclipse "manually" which parts of your code to format and which not can be a daunting task. “手动”告诉Eclipse要格式化的哪些部分以及哪些不是格式化的艰巨任务。 Especially if others work on the same project and don't know which parts of the code have to be left out. 尤其是如果其他人在同一个项目上工作并且不知道必须遗漏代码的哪些部分。

Because of this Eclipse allows you to set "markers", simply surround your code with these tags: 因此,由于Eclipse允许您设置“标记”,因此只需在代码中加上以下标记即可:

// @formatter:off
Here goes your code
// @formatter:on

In order to make this work you have to adjust the Java Code Formatter (it can be reached via Window / Preferences) settings like this: 为了使这项工作有效,您必须调整Java代码格式化程序(可通过Window / Preferences进行访问)的设置,如下所示:

在此处输入图片说明

在此处输入图片说明

As far as I know this has been in Eclipse since version 3.6. 据我所知,这是自3.6版以来的Eclipse。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM