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)
{
}
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.
How to add space between ) and Enum name?
I want to see this:
enum SampleEnum {
#Annotation("1") ONE,
#Annotation("2") TWO,
#Annotation THREE
}
This is how auto-formatting works:
enum SampleEnum {
#Annotation("1")ONE,
#Annotation("2")TWO,
#Annotation THREE
}
Don't want to use #formatter:off / on
UPDATE:
I added an issue https://youtrack.jetbrains.com/issue/IDEA-170457
The settings for auto formatting code are grabbed from the settings for "Code Style." These settings can be found at:
File - Settings - Editor - Code Style - Java
The setting your looking for is probably under the "Spaces" tab
Hopefully this fixes your problem.
Alternatively you can look through the IDEA add on repository for code style add-ons:
https://plugins.jetbrains.com/search/idea?correctionAllowed=true&search=code+style
I mean stuff like typing "iter" and getting a "for" loop with a choice of what variable to iterate on , typing "soutv" to generate a "System.out.println" with the "variable=" already in ...
Thanks !
It is called Templates and it's found under,
Window → Preferences → Java → Editor → Templates
The "soutv" template does not exist ("sysout" does, and it's similar), but it's easy to add. I used this pattern:
System.out.println("variable=" + ${cursor}${});
For 'soutv' particularly, I found the following pattern worked well in Eclipse:
System.out.println("${var} = ${cursor}" + ${var});
As others have mentioned, you can add this template by navigating to Window > Preferences > Java > Editor > Templates and clicking New.
The equivalent of 'iter' seems to be 'for' in Eclipse.
Check under
Window -> Preferences -> Java -> Editor -> Templates
Reference:
Template Variables
They are called Templates.
Go to Preferences > Java > Editor > Templates to see a list of pre-defined templates.
For example, sysout is:
System.out.println(${word_selection}${});${cursor}
You can also create your own.
I want to use regions for code folding in Eclipse; how can that be done in Java?
An example usage in C#:
#region name
//code
#endregion
Jet Brains IDEA has this feature. You can use hotkey surround with for that (ctrl + alt + T). It's just IDEA feature.
Regions there look like this:
//region Description
Some code
//endregion
There's no such standard equivalent. Some IDEs - Intellij, for instance, or Eclipse - can fold depending on the code types involved (constructors, imports etc.), but there's nothing quite like #region.
With Android Studio, try this:
//region VARIABLES
private String _sMyVar1;
private String _sMyVar2;
//endregion
Careful : no blank line after //region ...
And you will get:
No equivalent in the language... Based on IDEs...
For example in netbeans:
NetBeans/Creator supports this syntax:
// <editor-fold defaultstate="collapsed" desc="Your Fold Comment">
...
// </editor-fold>
http://forums.java.net/jive/thread.jspa?threadID=1311
Custom code folding feature can be added to eclipse using CoffeeScript code folding plugin.
This is tested to work with eclipse Luna and Juno. Here are the steps
Download the plugin from here
Extract the contents of archive
Copy paste the contents of plugin and features folder to the same named folder inside eclipse installation directory
Restart the eclipse
Navigate Window >Preferences >Java >Editor >Folding >Select folding to use: Coffee Bytes Java >General tab >Tick checkboxes in front of User Defined Fold
Create new region as shown:
Restart the Eclipse.
Try out if folding works with comments prefixed with specified starting and ending identifiers
You can download archive and find steps at this Blog also.
For Eclipse IDE the Coffee-Bytes plugin can do it, download link is here.
EDIT:
Latest information about Coffee-Bytes is here.
This is more of an IDE feature than a language feature. Netbeans allows you to define your own folding definitions using the following definition:
// <editor-fold defaultstate="collapsed" desc="user-description">
...any code...
// </editor-fold>
As noted in the article, this may be supported by other editors too, but there are no guarantees.
the fastest way in Android Studio (or IntelliJ IDEA)
highlight the code you want to surround it
press ctrl + alt + t
press c ==> then enter the description
enjoy
AndroidStudio region
Create region
First, find (and define short cut if need) for Surround With menu
Then, select the code, press Ctrl+Alt+Semicolon -> choose region..endregion...
Go to region
First, find Custom Folding short cut
Second, from anywhere in your code, press Ctrl+Alt+Period('>' on keyboard)
Contrary to what most are posting, this is NOT an IDE thing. It is a language thing. The #region is a C# statement.
I were coming from C# to java and had the same problem and the best and exact alternative for region is something like below (working in Android Studio, dont know about intelliJ):
//region [Description]
int a;
int b;
int c;
//endregion
the shortcut is like below:
1- select the code
2- press ctrl + alt + t
3- press c and write your description
The best way
//region DESCRIPTION_REGION
int x = 22;
// Comments
String s = "SomeString";
//endregion;
Tip: Put ";" at the end of the "endregion"
If anyone is interested, in Eclipse you can collapse all your methods etc in one go, just right click when you'd normally insert a break point, click 'Folding' > 'Collapse all'. It know it's not an answer to the question, but just providing an alternative to quick code folding.
here is an example:
//region regionName
//code
//endregion
100% works in Android studio
#region
// code
#endregion
Really only gets you any benefit in the IDE. With Java, there's no set standard in IDE, so there's really no standard parallel to #region.
I usually need this for commented code so I use curly brackets at start and end of that.
{
// Code
// Code
// Code
// Code
}
It could be used for code snippets but can create problems in some code because it changes the scope of variable.
vscode
I use vscode for java and it works pretty much the same as visual studio except you use comments:
//#region name
//code
//#endregion
Meet custom folding regions ⌥⌘T
Actually johann, the # indicates that it's a preprocessor directive, which basically means it tells the IDE what to do.
In the case of using #region and #endregion in your code, it makes NO difference in the final code whether it's there or not. Can you really call it a language element if using it changes nothing?
Apart from that, java doesn't have preprocessor directives, which means the option of code folding is defined on a per-ide basis, in netbeans for example with a //< code-fold> statement
On Mac and Android Studio follow this sequence:
Highlight the source code to fold
Press Alt+Command+t
Select <editor-fold>
Also you can select other options:
In Visual Studio Code, try this:
//region Variables
// Code you need
//endregion
In Eclipse you can collapse the brackets wrapping variable region block. The closest is to do something like this:
public class counter_class
{
{ // Region
int variable = 0;
}
}
Just intall and enable Coffee-Bytes plugin (Eclipse)
There is some option to achieve the same, Follow the below points.
1) Open Macro explorer:
2) Create new macro:
3) Name it "OutlineRegions" (Or whatever you want)
4) Right Click on the "OutlineRegions" (Showing on Macro Explorer) select the "Edit" option and paste the following VB code into it:
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics
Imports System.Collections
Public Module OutlineRegions
Sub OutlineRegions()
Dim selection As EnvDTE.TextSelection = DTE.ActiveDocument.Selection
Const REGION_START As String = "//#region"
Const REGION_END As String = "//#endregion"
selection.SelectAll()
Dim text As String = selection.Text
selection.StartOfDocument(True)
Dim startIndex As Integer
Dim endIndex As Integer
Dim lastIndex As Integer = 0
Dim startRegions As Stack = New Stack()
Do
startIndex = text.IndexOf(REGION_START, lastIndex)
endIndex = text.IndexOf(REGION_END, lastIndex)
If startIndex = -1 AndAlso endIndex = -1 Then
Exit Do
End If
If startIndex <> -1 AndAlso startIndex < endIndex Then
startRegions.Push(startIndex)
lastIndex = startIndex + 1
Else
' Outline region ...
selection.MoveToLineAndOffset(CalcLineNumber(text, CInt(startRegions.Pop())), 1)
selection.MoveToLineAndOffset(CalcLineNumber(text, endIndex) + 1, 1, True)
selection.OutlineSection()
lastIndex = endIndex + 1
End If
Loop
selection.StartOfDocument()
End Sub
Private Function CalcLineNumber(ByVal text As String, ByVal index As Integer)
Dim lineNumber As Integer = 1
Dim i As Integer = 0
While i < index
If text.Chars(i) = vbCr Then
lineNumber += 1
i += 1
End If
i += 1
End While
Return lineNumber
End Function
End Module
5) Save the macro and close the editor.
6) Now let's assign shortcut to the macro. Go to Tools->Options->Environment->Keyboard and search for your macro in "show commands containing" textbox (Type: Macro into the text box, it will suggest the macros name, choose yours one.)
7) now in textbox under the "Press shortcut keys" you can enter the desired shortcut. I use Ctrl+M+N.
Use:
return
{
//Properties
//#region
Name:null,
Address:null
//#endregion
}
8) Press the saved shortcut key
See below result:
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.