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.
Related
I recently upgraded my IDEA and now using IntelliJ IDEA 2022.2 Ultimate Edition.
I found the Complete Current Statement in Scala code behaves differently as in Java code, which is very annoying.
For example in Java code:
public static void main(String[] args) {
String foo = "bar"
}
Press Complete Current Statement shortcut(shift+cmd+enter for me) anywhere in line #2, will add a ; at the end of the line, and an auto-indent will be applied too:
public static void main(String[] args) {
String foo = "bar";
}
Then press Complete Current Statement again will bring you to a new line when there is nothing more to adjust.
public static void main(String[] args) {
String foo = "bar";
}
In previous version of IntelliJ, I roughly remember the behavior is same for Scala code.
But in this version of IntelliJ, when I try to do samething in Scala code, for example:
def foo (): Unit = {
throw new RuntimeException
}
When I press Complete Current Statement in line #2, nothing happens.
Could anyone please help me checkout why or how should I config to align with Java code's behavior? Thank you very much!
You don't need to use that in Scala because semicolons are optional, and almost never used. Actually, your Scala code sample is already what you would call a "complete statement".
For formatting what I do and recommend is having set File -> Settings -> Tools -> Actions on save and check Reformat code and optionally Optimize imports, and it will do both whenever you save your source file using Ctrl + S. I believe it's Cmd + S on your Mac.
This uses the default Intellij Formatter for Scala. Scala also has it's own Formatter called Scalafmt with customizable setups more control of formatting different Scala features based on your preferences. This is located at Settings -> Editor -> Code Style -> Scala.
If for some reason you would still like to use your shortcut key, then the only thing the Complete current statement can do to your Scala code is auto-indenting the current line, which for some reason it doesn't so it seems to be a bug on Intellij's side. But what you can do is replace the Auto-Indent Lines shortcut key to use your Complete current statement shortcut key instead and get the same behavior.
I'm trying to studying how a method in java String class works, so I created some customised code that calls that String class method.
As you can see, I have set a break point in my own code and I have set another break point in the java String class source code.
While I'm in debug mode and is on line 7 of my code, I pressed step into.
However, rather than stepping into the String class method indexOf, eclipse instead moved onto line 8 of my code.
Why is this happening? how can I step into the java string method source code?
public class TestingIndexOfMethod {
public static void main(String[] args) {
final String stringToBeSearchedThrough = "hello world";
final String substringToLookFor = "ll";
int a = stringToBeSearchedThrough.indexOf(substringToLookFor, 0);
System.out.println(a);
}
}
Edit 1:
I have already check to see, if "use step filter" is activated before asking this question on SO, and it is not activated. So I dont think "use step filter" is the problem here.
Edit 2:
step into works fine with methods I defined myself
Most probably there is a step filter which instructs the debugger to skip certain classes.
In the preferences dialog (menu Window -> Preferences) check the step filtering settings.
Either deactivate Use Step Fitlers which deactivates all step filters or deactivate the filter for the classes java.* only.
edit Another reason might be that your project is using a JRE instead of a JDK for the execution. Find below an example using a Java 8 JRE respective a Java 8 JDK.
project build path using a JRE (pay attention to jre1.8.0_112)
project build path using a JDK (pay attention to JavaSE-1.8)
edit 2 To determine the used Java runtime library add following statement in your code and run it in debug mode.
...
public static void main(String[] args) {
Stream.of(System.getProperty("sun.boot.class.path")
.split(File.pathSeparator))
.filter(s -> s.endsWith("rt.jar"))
.forEach(System.out::println);
...
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 am using Eclipse Mars to write my Java code. When I use Ctrl-/ to comment some lines and then apply Ctrl-Shift-F to format them and then un-comment the lines, it turns out to two lines of code instead of just the original one:
System.out.printf("%s => Cowz Testing: testing Add a Representative\n",
new Date());
Instead of that, I wish new Date()); to be at the end of first line.
Edit: The right sequence of steps to reproduce my error have been perfectly described in Jonah Graham's answer.
(I can't see exactly the error you have faced, but I have seen something similar.)
Starting with some code like this:
public static void main(String[] args) {
System.out.printf("%s => Cowz Testing: testing Add a Representative\n", new Date());
}
Then, comment out the printf line, so it now looks like this:
public static void main(String[] args) {
// System.out.printf("%s => Cowz Testing: testing Add a Representative\n", new Date());
}
Apply formatting and the result you have is this:
public static void main(String[] args) {
// System.out.printf("%s => Cowz Testing: testing Add a
// Representative\n", new Date());
}
Uncomment the code and you have an error because the string is not terminated:
public static void main(String[] args) {
System.out.printf("%s => Cowz Testing: testing Add a
Representative\n", new Date());
}
If the above describes your issue, then I recommend disabling Enable line comment formatting in your code style.
How to do it
From the Window menu, select Preferences
Select Java / Code Style / Formatter
Press Edit...
In Comments tab, uncheck Enable line comment formatting (see screenshot)
If you are editing a built-in profile, provide a new name
Press OK twice
Now when you comment out code, it will not edit the contents of comments when you format your code.
You can still use /* */ comments to have reflowed comments, i.e. for "real" comments, not temporarily commented out code.
Finally, I would recommend that you apply the code style to your projects in addition to your workspace to ensure your whole team shares a code style.
Try this
Window > Preferences > Java > Code Style > Formatter
Click Edit
Select the Line Wrapping tab
Uncheck Force split, even if line shorter than maximum line width (...)
I've noticed Eclipse Mars had other bugs in formatting, for example when using tabs for indentation. In this bug it's explained a workaround consisting in setting the indentation policy to spaces only, set the same value to tab size and indentation size, and then switch back to tabs only.
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.