IntelliJ IDEA - Fold for loop and/or if/else statements - java

I'd love to have a way of IntelliJ letting me fold for loops and if/else statements. But, I can't seem to find a way to do it automatically. I know you can use the //region and //endregion comments, or that you can do it manually with Ctrl+Shift+period, but is there a way to avoid all that and have it fold like methods or classes, without doing all that other stuff?

You can fold and unfold:
Code blocks, i.e. code fragments surrounded by a matched pair of curly braces {}.
To collapse a code block, place the cursor within that block and then select Code | Folding | Fold Code Block or press ⇧+⌘+. (mac) or ctrl+⇧+. (Linux / Windows).
Note Code folding works for the keywords if/ while/ else/ for/ try/ except/ finally/ with in case of at least two statements.
See: https://www.jetbrains.com/help/idea/2016.3/code-folding.html

Under Editor > General > Code Folding, you can enable this functionality expressly.
By default, if you wish for it to collapse method bodies, you can tick that selection. There are a lot of other options available, which should cover your needs.
If there's something that isn't covered, you can always enable "Show code folding outline" and use that to fold certain elements, although loops aren't foldable.

Put the cursor anywhere in the line of method definition for which you want the code fragments to be folded and press ctrl+shift+- this will collapse the whole method and press ctrl++ right after. this will keep the if and for loop fragments inside the method collapsed (intellij 2020.1.1 linux)

Related

IntelliJ: (Keyboard shortcut to) jump to next / previous suggestion

I know how to jump to the next and previous error (F2, see SO Link, jetbrains.com), but is there a way to easily jump between suggestions?
If possible, I would really love to have a keyboard shortcut for this, as I am currently learning Kotlin and IntelliJ often has nice suggestions on how to improve the code.
If there is no keyboard shortcut to jump between suggestions, is there at least any other way?
With suggestion I mean things like the following (Ignore the "nonsense code")):
F2 also works to navigate between warnings. If there are errors in the file, it will jump to the next error. If not, it will jump to the next warning.
Adding to yole's answer: if you want to jump backwards you can use Shift + F2 instead.
Additionally you can alter the severity of each inspection (or inspection group) using the settings menu File | Settings | Editor | Inspections or directly using the intention action context menu (ALT + ENTER or similar) when dealing with a highlighted element (be it warning, error, information, etc.).
Note that some inspections are not enabled by default and many allow customization to your needs (e.g. class naming conventions, etc.).
I did once increase the severity of all the inspections and switch them back one by one as needed or even turned many off (or switched them to "weak warnings"), just to easily jump back and forth between them. I can't recommend that approach anymore ;-) (too many highlightings then... but it may help to find out about inspections you consider more helpful).

Automatic code formatting for Eclipse IDE

I use many brackets and braces when I code. Be it casting multiple times, casting multiple times in if blocks, etc. I sometimes get lost in the brackets and also, hate putting a lot of them.
Is there any short-cut key to format this selected part of code?
I have tried Ctrl-Shift-F, but that doesn't give me what I want.
Note: I work on Eclipse Mars.
What you want is Source menu | Cleanup, then customize the profile to add the remove extra parenthesis. From the Code Style tab check the Use parenthesis in expressions Only if necessary. And then complete the wizard:
That changes:
super.start(((BundleContext)(context)));
to:
super.start(context);
As an extra you can set your project to do code cleanup tasks on save automatically if you desire.
did you try ctrl+3 and type formate? for me Ctrl-Shift-F was bound by other app and cause eclipse to miss catching it.
search for formatter Java->code style->formatter
There is a tab Braces.
If you select specific lines and press Ctrl + Shift + F eclipse will only format the lines you selected according to your formatter.

Search and replace if statements without braces to include braces

I've been recently using sonar for code analysis. When I go thorough violation drilldown, I found many java files with if statement defined without braces (thousands of places). Is there a simple way to replace or add braces to if statements or what are the steps that I can perform to achieve this task without doing it manually in each of the files.
I'm currently using intelliJ.
Is there a simple way to replace or add braces to if statements or what are the steps that I can perform to achieve this task without doing it manually in each of the files.
I don't know if there is a tool to do this automatically. (There probably is ...) But assuming that such a tool exists, I'm not convinced it would be the right approach.
Step back for a moment and consider why the code analysis has reported this as a problem. A lot of people (like #pst and me) think that the braces always should be there, even though various style guides don't insist on this. There is a good reason for this ... apart from "it looks ugly". Consider these example code snippets:
if (i == 1)
i++;
doSomething();
while (i < 1)
i++;
doSomething();
If you don't read those carefully, your eyes will trick you into thinking that doSomething(); is called conditionally ... due to the incorrect indentation. And it happens.
(Aside: labelling someone as "inept" for misreading that code is not helpful. If you are desperately trying to fix a show-stopper bug and you've been working for 14 hours straight, then you are likely to miss this kind of thing. And not because you are inept. Once you've been in that situation a couple of times, the lesson sinks in ...)
OK, now suppose that you run an automatic tool to add the braces. What you will get is this:
if (i == 1) {
i++;
}
doSomething();
while (i < 1) {
i++;
}
doSomething();
It means exactly the same thing as the original code. BUT ... what if the original code was actually a bug? What if the programmer intended the doSomething() calls to be conditional?
In short, by adding the braces automatically, we've obscured the original programmer's intention, and made these bug(s) harder to track down.
Bottom line - I think it would be prudent to manually review each of these occurrences ... rather than just "fixing" them automatically. Indeed, I'd argue that if you don't have the time or patience to review them manually, it would be better to leave the code alone. It would be better to turn off the warning ... IMO.
I can reformat the code to make intelliJ do the thing for me, but I need to go through all the files and reformat it. Yes, I might turned off the check but wondering if there is a good tool to do the task. I've good set of tests to check whether it introduce bugs during the process.
If you are sure that you have some ways to test that you will not introduce bugs then use the IntelliJ Reformat Code feature.
Just make sure that the Code Style you have in IntelliJ is in line with your company's policies. Otherwise you will force your style on everybody else too.
To force braces just mark them as Always on the Wrapping and Braces tag in the Code Style settings dialog in IntelliJ.
Mark the source folder in the project view and press Ctrl-Alt-L. A dialog pops up and there you can chose All files in directory <...>.
Then press Run and see what happens. If you are not satisfied then just revert from your VCS.
IntelliJ IDEA has an inspection for this as well, and it has a quick fix to automatically add the braces.
Invoke Analyze | Run Inspection by Name and enter inspection name Control flow statement without braces. Run it on the desired part of your project. In the inspection results you can apply the quick fix Add braces to statement.
Note that this inspection will also report control flow statement other than if, like for example while statements. Invoking the quick fix will also add braces to those statements.

NetBeans Java code completion is way too eager to please

Is it normal that the default behavior for code completion when editing Java is the following?
If I import a package, after typing the first ., any key I press results in the first item in the list being selected
Sometimes while typing keywords like public and protected, NetBeans will make some wild leaps and insert private after just a p or pu are typed!
In general, it tends to make some big guesses in terms of autocompletion, guesses that are not supported by my previous input at all.
I feel like this cannot be the desired behavior for every user. Is there a way to make the code completion not autocomplete anything, or at least make it way less eager?
Edit: To be clear, I do not want to have to disable the sometimes-useful "Autopopup Window." I want the window to eagerly appear with tips and suggestions for methods, syntax, whatnot - I just don't want NetBeans to try to guess what I want, because it is wrong 90 - 100% of the time.
Which version of Netbeans are you using because that doesn't seem to be the behaviour I am seeing in 7.1.
AutoCompletion popups don't appear until I hit Ctrl+Space.
If I type "p" and then hit Ctrl + Space, the popup shows "private", "protected" and "public". I can either keep typing (and the list gets smaller as possible matches are removed) or use the cursors to select the word I want and hit Enter.
If there is only one logical option e.g. I start typing "pu" and then hit Ctrl+Space, then Netbeans inserts "public" automatically (though this can be turned off).
Code templates are a different story, I have them set to be activated using Shift+Space. As far as I know, templates don't show any popups. Anyone who likes pain can consider changing the activation key to just Space :P
I definitely share your complaints, especially re: 1. A quick google search reveals ways to turn off autocomplete:
AutoComplete drives me crazy. I’ve always hated it – I feel like it
slows my computer down and sometimes it even seems to derail me in the
middle of typing something because the window comes up and somehow
snags focus. I turn it off under Options, Editor, General (uncheck
Auto Popup Completion Window).
Item 2) sounds more like the "code template" feature rather than the auto-completion.
If that gets in your way, you have two options:
change the key that "triggers" the code-template expansion (e.g. from "Space" to "Tab"
remove all two-stroke templates (or any other abbreviation that you would rather not have)
Both can be done under "Tools -> Options -> Editor -> Code Templates"

Java: Triple Curly Bracing

I've been given some code with commenting unlike anything I've come across before:
//{{{ Imports
import imports;
//}}}
It is the same for each method block,
//{{{ above the code block
//}}} below the code block
Also see: http://en.wikipedia.org/wiki/Folding_editor
A quick search for "triple curly" comment suggests it's "Emacs folding mode".
Or some other code folding marker in any case.
jEdit uses {{{ and }}} to mark "explicit" folds.
It may also be for some code generators. Some generators allow you to edit generated code, and use markers like that so the generator knows where it can regenerate.
Actually, Vim uses those triple braces in comments, too.
Tell the one you got the code from, that folding this way is a bad idea. Vim can set fold points at syntactic folding hints, defined in the highlighting file.
Maybe it's to emphasize a code block?
shrugs

Categories

Resources