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:
Related
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)
{
}
This is the output of reformat code option from intellij (alt + command + L)
int i = Main.someRandomFuntion("arg1",
"arg2",
"arg3", "arg4",
someRandomFunction2("arg1",
"arg2"),
"arg6");
and what i need this is
int i = Main.someRandomFuntion("arg1",
"arg2",
"arg3", "arg4",
someRandomFunction2("arg1",
"arg2"),
"arg6");
which is just more an aesthetic improvement.
Do intellij (I am using 15) support an option to tweak auto format option ?, if so How can i do it ?
Open Settings with Ctrl+Alt+S.
Go to:
Editor > Code Style > Java
Click on the Wrapping and Braces tab, scroll down to Method declaration parameters and change the settings there to what you desire.
Note: I found these particular Settings a little glitchy when I was toggling them but you can usually get what you want with a couple of minutes of fiddling and testing.
Is there anyway to get Eclipse to automatically look for static imports? For example, now that I've finally upgraded to Junit 4, I'd like to be able to write:
assertEquals(expectedValue, actualValue);
hit Ctrl + Shift + O and have Eclipse add:
import static org.junit.Assert.assertEquals;
Maybe I'm asking too much.
I'm using Eclipse Europa, which also has the Favorite preference section:
Window > Preferences > Java > Editor > Content Assist > Favorites
In mine, I have the following entries (when adding, use "New Type" and omit the .*):
org.hamcrest.Matchers.*
org.hamcrest.CoreMatchers.*
org.junit.*
org.junit.Assert.*
org.junit.Assume.*
org.junit.matchers.JUnitMatchers.*
All but the third of those are static imports. By having those as favorites, if I type "assertT" and hit Ctrl+Space, Eclipse offers up assertThat as a suggestion, and if I pick it, it will add the proper static import to the file.
If you highlight the method Assert.assertEquals(val1, val2) and hit Ctrl + Shift + M (Add Import), it will add it as a static import, at least in Eclipse 3.4.
Eclipse 3.4 has a Favourites section under Window->Preferences->Java->Editor->Content Assist
If you use org.junit.Assert a lot, you might find some value to adding it there.
Not exactly what I wanted, but I found a workaround. In Eclipse 3.4 (Ganymede), go to
Window->Preferences->Java->Editor->Content Assist
and check the checkbox for Use static imports (only 1.5 or higher).
This will not bring in the import on an Optimize Imports, but if you do a Quick Fix (CTRL + 1) on the line it will give you the option to add the static import which is good enough.
From Content assist for static imports
To get content assist proposals for static members configure your list of favorite static members on the Opens the Favorites preference page Java > Editor > Content Assist > Favorites preference page.
For example, if you have added java.util.Arrays.* or org.junit.Assert.* to this list, then all static methods of this type matching the completion prefix will be added to the proposals list.
Open Window » Preferences » Java » Editor » Content Assist » Favorites
For SpringFramework Tests, I would recommend to add the below as well
org.springframework.test.web.servlet.request.MockMvcRequestBuilders
org.springframework.test.web.servlet.request.MockMvcResponseBuilders
org.springframework.test.web.servlet.result.MockMvcResultHandlers
org.springframework.test.web.servlet.result.MockMvcResultMatchers
org.springframework.test.web.servlet.setup.MockMvcBuilders
org.mockito.Mockito
When you add above as new Type it automatically add .* to the package.
Shortcut for static import:
CTRL + SHIFT + M
Select the constant, type
Ctrl + 1 (quick fix)
Select "Convert to static import." from the drop down.
"Quick fix" has options even though it is not an error.
In Eclipse 4.9, you can static import existing invocations using a quick fix.
A new quick fix has been implemented that allows the user to convert static field accesses and static methods to use a static import. It's also possible to replace all occurrences at the same time.
More details here
I need to translate my app, so i want to use gettext-common from http://code.google.com/p/gettext-commons
I checked out the svn and tried to compile the example:
javac -classpath ../java I18nExample.java
java -classpath ../../target/gettext-commons-0.9.6.jar:. I18nExample
The program does not give me the targeted output; I have absolutely no idea whats going on!
It seems that the de.properties is completly ignored. If I set the Properties file to "de" in the Factory's constructor, I get partly the output I want to see.
Is there anywhere in the internet a working example of gettext for java?
this is the output from the example script:
First run
This text is marked for translation and is translated
This text is marked for translation but not translated
This text is marked for translation but not translated
Four: 4
chat
chat
1 file is open
2 files are open
Second run
This text is marked for translation and is translated
This text is marked for translation but not translated
This text is marked for translation but not translated
Four: 4
chat
chat
1 file is open
2 files are open
There are a couple of issues, perhaps due to the build process.
First, for the message lookup to work, I needed to move the en and de resources into Messages_en.properties and Messages_de.properties in order to make a real resource bundle.
Second, the example code tries to use messages with no translations available, like the "file is open" stuff. Here's an updated version of what I tried; this all appears to work with the above modification:
public static void main(String[] args) {
I18n i18n = I18nFactory.getI18n(I18nExample.class, "Messages");
for (int i = 0; i < 2; i++) {
if (i == 0) {
print("First run");
} else {
print("Second run");
i18n.setLocale(Locale.GERMAN);
}
print("Current locale: " + i18n.getLocale());
print(i18n.tr("This text is marked for translation and is translated"));
String mark = i18n.marktr("This text is marked for translation but not translated");
print(mark);
print(i18n.tr(mark));
mark = i18n.tr("This is the {0}. text to be translated", "chat (noun)");
print(mark);
mark = i18n.tr("This is the {0}. text to be translated", "chat (verb)");
print(mark);
print(i18n.tr("chat (noun)"));
print(i18n.tr("chat (verb)"));
print("");
}
}
Note also that to insert translated words, you need something like this:
print(i18n.tr("This is the {0}. text to be translated", i18n.tr("chat (noun)")));
print(i18n.tr("This is the {0}. text to be translated", i18n.tr("chat (verb)")));
However, without un-banging (removing the ! and providing an English translation in Messages_en.properties, it shows up as chat (noun), which... strikes me as being almost useless.
The documentation is lacking on this aspect.