I'm extremely frustrated with the Eclipse formatting rules for a series of qualified invocations (i.e., the Builder pattern style). For example, here is my preferred formatting for some code that creates a new Apache Commons CLI Options object:
Options options = new Options()
.addOption(OPTION_HELP_SHORT, OPTION_HELP, false, "print usage information")
.addOption(OPTION_VERSION_SHORT, OPTION_VERSION, false,
"print version and exit")
.addOption(OptionBuilder.withLongOpt(OPTION_PROPERTIES)
.hasArg()
.withArgName("FILE")
.withType(File.class)
.withDescription("specify a user properties file")
.create());
I.e., parameters are wrapped and indented if necessary and all qualified invocations except the first, unless necessary, are wrapped and indented if there is more than one. If a parameter list wraps inside a qualified invocation, the invocation should wrap first.
The default formatting in Eclipse ("Wrap only when necessary" for arguments and invocations) yields the following mess:
Options options = new Options().addOption(
OPTION_HELP_SHORT, OPTION_HELP, false, "print usage information")
.addOption(OPTION_VERSION_SHORT, OPTION_VERSION, false,
"print version and exit").addOption(
OptionBuilder.withLongOpt(OPTION_PROPERTIES).hasArg().withArgName(
"FILE").withType(File.class).withDescription(
"specify a user properties file").create());
Going into "Java Code Style -> Formatter -> Line Wrapping" and the line wrapping setting to "Wrap all elements, except first element if not necessary" for invocations yields:
Options options = new Options().addOption(
OPTION_HELP_SHORT, OPTION_HELP, false, "print usage information")
.addOption(OPTION_VERSION_SHORT, OPTION_VERSION, false,
"print version and exit")
.addOption(
OptionBuilder.withLongOpt(OPTION_PROPERTIES).hasArg().withArgName(
"FILE").withType(File.class).withDescription(
"specify a user properties file").create());
I don't like that the OptionBuilder expression isn't being wrapped, or that "FILE" gets wrapped without also wrapping withArgName.
Changing the indentation to "Indent on column" yields:
Options options = new Options().addOption(OPTION_HELP_SHORT, OPTION_HELP,
false, "print usage information")
.addOption(OPTION_VERSION_SHORT,
OPTION_VERSION, false,
"print version and exit")
.addOption(
OptionBuilder.withLongOpt(
OPTION_PROPERTIES)
.hasArg()
.withArgName("FILE")
.withType(File.class)
.withDescription(
"specify a user properties file")
.create());
The is breaking the lines where I'd prefer, but pushing things over much too far to the right.
Is there any way to convince Eclipse to apply my preferred formatting style or something closer to it than any of the above?
Turning off formatting with comments, or inserting line comments is too tedious.
The best way is described here:
... or you can select "Line Wrapping > Never join already wrapped
lines" globally. Then, you can break it manually and the formatter
will only format inside lines (or add additional line breaks if
necessary).
With this setting Eclipse formatter will stop ruining your builder statements.
Use comments:
Object o = foo() //
.bar() //
.toString();
Update for 2021. It is possible to change, navigate to: Code Style -> Formatter -> Line Wrapping -> Wrapping settings -> Function Calls -> Qualified invocations and change value to "Wrap all elements, except first element if not necessary"
In Eclipse 3.6 It's possible to turn off formatting for a region of code. See my answer to
How to turn off the Eclipse code formatter for certain sections of Java code?
AFAIK, this is known problem with Eclipse Formatter:
https://bugs.eclipse.org/bugs/show_bug.cgi?id=59891
On the menu select Window -> Preferences when the window opens select Java -> Code Style -> Formatter and from there you can create your own format style to use by selecting the new or edit option. When editing a formatting profile a new window opens that gives you a lot of different options to use.
Related
I am typing some class or method, and using line breaks to help me see where everything is, and it keeps getting edited out when I save. I've tried looking for an answer in the extensions and settings, but can't figure out what might be deleting the new lines.
I'll have something like:
public class SomeClass
{
public static void main (String[] args)
{
Some code here;
}
}
and it will delete the first line break after SomeClass and after args)
it will edit it to look like this:
public class SomeClass {
public static void main (String[] args) {
some code here;
}
}
How do I turn off the editing on save that deletes my new lines?
Here is settings.json:
{
"files.autoSave": "afterDelay",
"editor.suggestSelection": "first",
"vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
"files.exclude": {
"**/.classpath": true,
"**/.project": true,
"**/.settings": true,
"**/.factorypath": true
},
"editor.bracketPairColorization.enabled": true,
"editor.padding.bottom": 5,
"editor.padding.top": 5,
"editor.roundedSelection": false,
"javascript.format.placeOpenBraceOnNewLineForControlBlocks": true,
"javascript.format.placeOpenBraceOnNewLineForFunctions": true,
"files.insertFinalNewline": true,
"editor.renderFinalNewline": false,
"editor.trimAutoWhitespace": false,
"launch": {
"configurations": [],
"compounds": []
}
}
Hit Ctrl + Shift + P and type Save Without Formatting. Hit Enter(Return) and it should save without applying any formatting. Doing this every time doesn't make sense. So maybe you would like to change the key binding from File -> Preferences -> Keyborad Shortcuts.
The doc talks more on that here
EDIT 1: START
If you happen to have a liking for a particular style(like eclipse-java-google-style), you can consider setting up the java.format.settings.url option under File->Preferences->Settings -> Java.
You can also create your own formatting profile in eclipse and export the profile as xml file and provide the path to the xml file.
But in order to be able to do that you will first need to install the extension Language Support for Java(TM) by Red Hat.
Creating profile in eclipse:
Generally speaking you create profiles in Eclipse by going to the Windows -> Preferences -> Java -> Code Style -> Formatter -> New -> Brace Positions -> Choose the option you want(perhaps Next line is what you are looking for, click on the checkbox to modify all with the same value) -> In the same window you will see the export button(somewhere top right corner) -> export your new profile to some safe location of your choice. It will be saved as an XML file.
Copy the full path of the file and paste it in the java.format.settings.url section mentioned above.
Having a profile setup will save you lot of time. You will never have to manually format your braces/ indentation or any other piece. Define the formatting once and forget about it.
This profile setup also gives you the privilege of using the default Save of VSCode. It will format on save but as per your defined profile.
Kind of Win-Win situation for both you and VSCode's default settings.
EDIT 1: END
Press Ctrl+Shift+P in VS Code. It will open settings. There disable auto formatting of code, as in below image.
I'm migrating some pre Java 10 code and I'm wondering if IntelliJ offers a way to automatically refactor the code to replace the variable declarations that uses the actual type with var wherever it's possible.
The code is full of stuff like:
String status = "empty";
BigDecimal interest = BigDecimal.ZERO;
List<Future<Boolean>> results = es.invokeAll(tasks);
LocalDate start = LocalDate.of(2020, 1, 1);
And I would prefer:
var status = "empty";
var interest = BigDecimal.ZERO;
var results = es.invokeAll(tasks);
var start = LocalDate.of(2020, 1, 1);
I already looked in IntelliJ's settings (Code Style/Inspections) and couldn't find anything.
Go to File | Settings, there select Editor | Inspections, then under Java | Java language level migration aids | Java 10.
Right click on Local variable type can be omitted and select Weak Warning or similar.
Move Your cursor onto any of those warnings in Your code (highlighted grey), open quick fix context help (alt+enter), at Replace explicit type with 'var' move to the right and select Fix all 'Local variable type can be omitted' problems in file
Thanks for #olga-klisho for the idea (in comments)
I'm using IntelliJ IDEA 2021.3.2, but don't think the setting is new.
I've been struggling with this one myself.
It seems that the first time to install IntelliJ locally, by default, it will fall back to using traditional defining of variables (i.e. String s = new String();)
How I managed to change it into using var is after I declared something, for example new String(), either I pressed ⌥ Alt/Option+Enter to declare a variable for that declaration or by using ⌘ Command+⇧ Shift+V shortcut (I'm using Mac and classic Intellij key mapping, so YMMV) which activates declaration of a variable, this would show as follows:
As you see, it suggest to hit that key combination shortcut or clicking on the settings button that would open a pop up like this one:
Make sure you have Declare var type selected and you should be good to go.
Use the IntelliJ Edit -> Find -> Replace... option.
Or Ctrl + R
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?
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.
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
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)
{
}
I'm using Eclipse Luna 4.4.0 and Eclipse formatter takes this code:
users = getSingleColUserList(new XSSFWorkbook(fileInputStream),
userId, profCol);
and drops the method call onto a new line:
users =
getSingleColUserList(new XSSFWorkbook(fileInputStream),
userId, profCol);
As you can see, the line width is not the issue. It's not at all obvious what setting in the formatter dialog I need to change.
[UPDATED after Seelenvirtuose's answer]
I can set Eclipse to format Line Wrapping -> Assignments to Do not wrap. However that raises another issue with lines then not getting wrapped when they go over the line width:
List<Map<String, Object>> emailMap = jdbcTemplate.queryForList(DBQueries.LOAD_EMAILS);
The line width is 80 which is either the s or the . of DBQueries so it should be:
List<Map<String, Object>> emailMap = jdbcTemplate.queryForList(
DBQueries.LOAD_EMAILS);
None of the settings that I have tested for Line Wrapping -> Function Calls -> Arguments
It's cute that my browser is currently displaying a scrollbar under the unwrapped code!
It is the formatter's setting for "Line Wrapping -> Assignments". Set it to "Do not wrap".
Using Eclipse Juno I've got the following issue using the Java code formatter:
If a method call leads to a line break, Eclipse inserts a whitespace before the "dot" of the method invocation (_ shall denote the whitespace)
int nbo = new Foo()//linebreak
_.method();
Unfortunately this whitespace triggers a Checkstyle warning (NoWhitespaceBefore rule). Is there some possibility to stop eclipse inserting the whitespace? Or is it a Checkstyle configuration issue?
Thanks for your help in advance.
You can increase Maximum line width to 120 or bigger number.
On menu Windows -> Preferences
Navigate to Java -> Code Style -> Formatter
Click on Edit button to open a new dialog
On Line Wrapping tab, change Maximum line width
Finally, change Profile name and click OK
You can resolve this either by changing the formatter settings or by changing the Checkstyle configuration.
Option 1 - Formatter Settings (for Eclipse 4.3, but should be the same for Juno)
Window → Preferences → Java → Code Style → Formatter → Edit
Line Wrapping → Function Calls → Qualified Invocations
Set to Do Not wrap
Option 2 - Checkstyle Config
Remove the DOT token from the NoWhitespaceBefore rule:
<module name="NoWhitespaceBefore">
<property name="tokens" value="SEMI,POST_DEC,POST_INC"/>
</module>