Is there a simpler way of reordering methods within a class source file in IntelliJ than cutting and pasting the code manually? Nowadays I often need this while refactoring legacy code, e.g. to move related methods close to each other in the source code.
In Eclipse AFAIK there is a view similar to the Structure view of IntelliJ, where I can drag and drop methods around. However, this does not work in IntelliJ and I couldn't find any hints from its help either.
I am using IntelliJ 9.0.2 to be specific.
You can select a method name and hit: Ctrl+Shift+Up or Ctrl+Shift+Down to move it up and down.
On OS X: Cmd+Shift+Up or Cmd+Shift+Down
Beyond this the Rearranger Plugin lets you move methods around quickly, and even define a standard ordering based on your coding convention.
IntelliJ has a built in system that allows you to specify how to order your methods. You need to go to Settings (Ctrl + Alt +S) -> Editor -> Code Style -> Java -> Arrangement (tab) and scroll down until you find the icons with methods. There you can manipulate the options to sort them by visibility, or alphabetically, or to keep related ones grouped together.
Here is a screenshot of my settings which will order methods automatically by visibility (public, protected, private) and alphabetically (a-z).
The blue highlights show the currently selected rules.
Not a perfect answer yet, due to a bug in IntelliJ.
Though IntelliJ offers this feature implicitly, but it needs to be enabled as well as fixed. The OP's suggested way is technically arranging methods in depth-first order. However, if you use Breadth-first ordering(which works properly), it should reduce the manual work of moving functions by a lot, by arranging all caller and callee methods together.
Issue Link: https://youtrack.jetbrains.com/issue/IDEA-149524. Please do vote for its resolution.
The appropriate action for this is Rearrange Code. This has no key assigned to it, but you can define your own using Preferences->Keymap.
With your cursor on the method definition line (you do not have to and press ctrl+shift+up or ctrl+shift+down, to move up or down respectively.
You can also to ctrl+shift+numberpad - to quickly collapse everything so you can focus on moving around (plain - works on my laptop as well, not sure why) and ctrl+shift+numberpad + to get back to see everything (ctrl-shift-equals works on my laptop as well).
Select a block of text (hit Ctrl-W a few times) and then use Ctrl-Shift-Up and Ctrl-Shift-Down to move it around.
There is an automated way, which you can later tweak
Code -> show reformat file dialog
and tick "rearrange code" box
Related
Does anyone with IntelliJ & NetBeans experience know, if IntelliJ has some similar feature as for NetBeans "Make controller" when right clicking the corresponding FXML file?
I think it is pretty important since it updates, if I have added something new (a FXID for example), and if I deleted it and such - and also places it in the correct place by itself.
I know you, in Scene Builder, can go to "View -> Show Sample Controller Skeleton", but this is just not enough automation, especially not from a Jetbrains IDE.
This also means that the following link is not an answer:
how to do netbeans'"make controller" in intellij idea
[]
Rather than having an action to create the controller, IDEA uses intentions (activate via Alt+Enter or ⌥⏎). And its philosophy would be to keep the controller in sync as you edit the FXML file rather than recreating it to update it with changes.
For example, when you create an FXML file, IDEA offers to create the controller:
First I name it as desired, and then use an Intention to create the corresponding class:
Then as I add things to the FXML, IDEA offers to create the corresponding items in the controller:
Similarly with an fx:id:
And if I use the rename refactor to change the fx:id
it renames the corresponding field name in the Controller to match. So instead of editing it and then recreating the controller to capture the name change, it simply keeps them in sync. But again, the key is to use the rename refactoring and not just "manually" edit the fx:id.
Edit to answer follow-up questions in comments
First a disclaimer... I only dabble in JavaFX to write simple dialogs as front ends to command line scripts. So I'm by no means an expert and may not be aware of a JavaFX related feature in IDEA. But I have been using IDEA for 14 years and typically know what to look for in terms of features and "how do I" questions.
Can you shed some light on using this kind of stuff with Scene Builder, if you know something about it?
Whenever I use a WYSIYWG editor like Scene Builder, I still keep an eye on and cleanup the code it generates. I'm still a bit old school in that way. And I believe IntelliJ IDEA adheres to that philosophy.
I find it really hard to believe IDEA has no way of "mass automatic updating" edits made in Scene Builder
I can tell you as an IDE, IDEA is not big on Wizards or mass code generation. Instead it's more "surgical" in nature. It's "code by intentions" philosophy is to enter/edit your intent, and then use an intention/quick-fix to implement that intention. Thus any code generation it does is small and focused. But... in some cases you can ask it to simultaneously apply an intention to multiple items by opening the intentions side menu (using the right arrow → key) and selecting the "Fix All 'issue name' problems in file". Again, given my limited experience with JavaFx work, I may not be aware of something. But I'm not seeing anything where such a thing would be and I'm not seeing anything in the Help pages.
<soapbox>
When I first started using IDEA in 2003 I too wondered where all the wizards and mass code generation features that my old IDE provided were. (I previously used Forte for Java, the predecessor to NetBeans.) At first I missed them. Then I started using intentions and refactorings for everything. After a couple of months, I didn't miss the wizards. After a few more months, I came to hate wizards in other IDEs. In the long run, I was far more productive using the intentions & refactorings. And I noticed I was no longer spending a lot of time dealing with compile issues and bugs that I did when I used wizards.
</soapbox>
If I assign fx:id's to a lot of buttons and such in Scene Builder, do I then have to manually go into the code view of the fxml file, find all of the fx:id's and for each of them alt+enter to get them into the controller?
Unfortunately for the "create field" intention for missing IDs" there is not a batch mode available. So you can not use the "fix all" option. My educated guess as to why not is that when creating the field you are given the opportunity to select the type for it. For example, with the fx:id for a label, I may want to type the field as Label, Labeled, Control, etc. Granted in most cases you are likely to type it as the actual type it is in your FXML. So you may want to open a feature request asking for a batch mode to be made available for the "Create field" intention that defaults the field to type used in the FXML. Nevertheless, if you get use to using F2 to navigate to the next error, and then using Alt+Enter (or ⌥⏎) to open the quick fix, you'll find you can add the missing fields very quickly.
if I deleted some fx:id's also, then I would have to remember which ones they were, to them manually delete them in the controller?
Again, instead of just "manually" deleting an fx:id, use an IDEA refactoring. When deleting fx:ids (or anything) use the "Safe Delete" refactoring. With your cursor on the id (either in the FXML file or the Controller), type Alt+Delete (or ⌘⌦) to launch "Safe Delete".
If there are no usages, the field is deleted. Otherwise you get a warning:
Click the "View Usages" button. The "Find" toolbar will open up showing the usages.
Update your code to remove their usages. Use the "Rerun Safe Delete" button to monitor your progress. Once all usages are done, hit the "Do Refactor" button to delete the usages. While this may seem more involved than some sort of regenerate the controller option, my question would be how would such a feature deal with the usage of that field in a method within the controller? Would it just not recreate the field leaving a compile error in my controller? How would it "regenerate" all the customization I've made to the controller?
The Safe Delete also keeps your code error free. If I had a dollar for every time I went to delete a something I absolutely knew was not being used anywhere only for the safe delete refactoring to pop up a warning about the place its being used that I totally forgot about.
If you use Javaru's solution then created fields will be public and without #FXML annotations.
To change it go to:
File | Settings | Editor | Code Style | Java | Code Generation | Default Visibility - choose Escalate or Private, and check "use external annotations" at the bottom.
Second solution: open fxml file in scene builder set the controller class in controller section at left bottom part of window. Go to: view | show sample controller skeleton and copy controller class code.
It is my first post, hope I've helped. :)
I can't see create method or create field
I see this
Go to your .fxml file and there is red error element: the name of your handle function in my example.
Just push create it.
IntelliJ gives you possibilities to create your event:
FWIW, I am using IntelliJ, but this could be solved by other code viewers/editors, instead.
What I want is a way to scroll through Java code, and make the actual freaking NAMES of things in definitions stand out, de-emphasizing all the other "important" stuff in front of the names, all the modifiers, mile-long type names and multiple mile long type names inside generic type angle brackets.
#EvenMoreComplicated #Pinky(extended=true) private static final volatile UltimateUtility<Blah,Yak,Freaking,Enough> theName(...
vs
/.../ theName... *the definition would still show here*
I just want a way to easily see the bloody names of classes, properties, methods and local variables when I am trying to read this sludge :-(
I'm NOT asking for the feature that highlights instances of a selected identifier.
I'm losing the forest in the trees. It's distracting to have to look back and forth at the tree structure viewer, which doesn't show local variables (at least in Java, somewhat in JS)
Maybe I'm trying to solve the wrong problem? Well, they pay me (and my coworkers) to do large portions of my work in Java, so that's the gig.
As far as I know that's not currently possible in IJ or any other IDE for that matter (please correct me if you know otherwise). There are a few tricks you can do, but none of them is an exact match of what you're looking for. Either way, you should be having each annotation on a separate line, so this does not really add any value for method annotated parameters.
Please note that the key bindings used below are for Windows and IJ 2016.2. You can check/change your own shortcuts from File -> Settings -> Keymap.
1) "collapse by default" settings: go to File -> Settings -> Editor -> General -> Code folding and select what you'd like to be folded by default:
1) custom folding regions (blog & help): select a region and press CTRL + .
2) collapse everything (custom region included. it seems): CTRL + SHIFT + Numpad -
When refactoring code (e.g.: Refactor -> Rename), IntelliJ IDEA 14.x also rewraps (reformats) my code to fit into the 80 column limit.
Example: here's the code before the refactoring:
Refactoring in progress:
... and the code is re-wrapped once I press Enter:
What's most annoying about that, even Java classes which aren't currently open in the editor (but are affected by the refactoring) are reformatted, increasing the chance that formatting changes get propagated into my VCS unnoticed.
What I want to achieve is:
keep the original print margin at 80 columns, but still
have IDEA preserve my original formatting when renaming variables/classes/methods.
How do I achieve this?
Since I don't use any automatic formatting and mostly wrap my long lines manually, I figured out another solution.
Under "File -> Settings -> Editor -> Code Style -> Java -> Wrapping and Braces", I've disabled automatic wrapping entirely (i.e. set everything to "Do not wrap" where appropriate, except for class, method and field annotations, which are set to "Wrap always" by default).
The downside of this approach is that now IDEA sometimes unwraps long lines during refactoring, but those are easier to spot.
If you are doing an actual "Refactoring -> Rename", for example with SHIFT + F6 you are editing every file that has a reference to that variable name whether or not they are currently open in the editor is irrelevant if you change something all the files that are affected are edited and any VCS will consider them changed.
The behavior of reformatting the entire file on refactoring is been in Idea a long time and all bugs that have been filed against that behavior have been setting in an unassigned state forever. Here is one example.
I doubt that this behavior is going to change, I for one hope it does not.
If you want ridiculously long variable names then you need to either turn off the right margin or make it ridiculously long as well. Or change whatever configuration is causing things to be formatted differently.
Personally I set all the relevant things to ALWAYS whatever so I do not have somethings formatted one way and somethings formatted a different way. Consistency is more important than anything else in a large code base.
The VCS tools in Idea are extremely powerful and unmatched in any other IDE. You can easily see what has changed and exclude them from any commits or fix them up how you want.
Idea has a format on commit checkbox for all the various version control systems it supports as well.
I'm trying to do something weird, I'm trying to determine how many methods has my Java application.
This weird thing has a purpose, it is because I have to improve the logging in the application, and it will require to make a revision of every method and add the logging if it is missing, update the logging if it already has.
I'm in the estimation process, so knowing how many methods has the application will help me to provide a high level estimation with a reasonable basis for this.
Then, here is the question, is there any way to know how many methods has my Java application?
Thanks in advance.
Fer
PS: I'm using Eclipse
Using Eclipse you can do this:
Press Ctrl-H (Search), then select the "Java Search" tab (if it doesn't appear click on the "Customize..." button at the lower left corner)
Put * in the search box
Select "Method" in the "Search For" fieldset
Select "Declarations" in the "Limit To" fieldset
Select "Sources" in the "Search In" fieldset
Select "Workspace" in the "Scope" fieldset
Click on "Search"
After the search is complete you should see a "XXXX declarations in..." message in the search view and that will be your result.
Hope it helps!
I would prefer using Reflection.
Retrieve all the class from expected packages, where logging is necessary
Summing up all the method available to all those class
Try to use a static code analyzer; Source Monitor, for example, is free SW and has the count you're searching for.
Use sonar - http://www.sonarsource.org/ - it's great tool for analyzing code.
Or look here: What are the good static code analysis plugins?
If you are going to add logging to so many methods you might want to consider implementing an AOP solution. It will allow you to write consistent loggers, makes it easier to maintain and doesn't clutter your code with boilerplate stuff. There are countless examples in Google.
Metrics is a nice plugin for Eclipse: http://metrics.sourceforge.net/
Number of Methods (NOM): Total number of methods defined in the selected scope
For a specific class, it's easy just from the class outline panel in eclipse select all methods then right click and copy the fully qualified name to the editor of your choice then it's a simple count lines.
Please press CTRL+O in your respective Java Class in the Eclipse IDE - You will get the number of methods in the respective Java class.
Now you should be able to see the number of methods available in that class.
can I has fulltext autocompletion for Java # Eclipse? Let's demonstrate:
Final piece of code:
getVariants().add(new Variant(MediaType.TEXT_XML));
How do I code now:
getv[ctrl+space].a[Enter]new
V[ctrl+space, down arrow,
Enter]M[Ctrl+Space, Enter].text_x
Basically, Eclipse completes word "TEXT_XML" when I provide letters "TEXT_X".
How would I like to code:
getv[ctrl+space].a[Enter]new
V[ctrl+space, down arrow,
Enter]M[Ctrl+Space, Enter].xml
and Eclipse should realise I meant "TEXT_XML" (fulltext autocompletion).
As far as I'm aware, there is no way of enabling a full-text code completion in the Eclipse preferences view. This has been bugging me for a while, too. I did quite a bit of digging and I'm pretty certain there is no easy way of achieving this.
However,
there are two ways of implementing the desired, but I assume both of which are way to much work for fixing this little nuisance.
There is an Eclipse plug-in extension point for the JDT Java Completion Proposal Computer - reference page
A sample project which implements this extension point can be found in this repository.
This is fairly convenient, but still a lot of boilerplate and tedious coding.
You can change the findKeywords method in the internal org.eclipse.jdt.internal.codeassist.CompletionEngine class and compile your own JDT fork. But this is discouraged for so many reasons. First of all, this class is a 12000 line monster and hard to just jump in. And of course, if you'd only hack a kludge in, there is little chance of this becoming an official contribution, so you'd need to worry about every eclipse release.
Additionally, there might be a very chillaxed way in the future. Although this might exceed your requirements a bit.
Have a look at the Code Recommenders project. This blog has an outline of the project objectives
It doesn't mention full-text auto-completion specifically, but I'd assume its matching algorithms go even beyond that.
Edit: In the proper SO-spirit, I'll keep this answer up to date:
Apparently the feature is now implemented in the Code Recommenders plug-in. See this blog post and this forum thread. I'm quite surprised it only took 10 locs. To me the extension point appeared more complex.
If your MediaType class does not contain a large number of accessible fields/methods you could simply use
getv[ctrl+space].a[Enter]new V[ctrl+space, down arrow, Enter]M[Ctrl+Space, Enter].[Ctrl+Space, down arrow, Enter]
you may need to press the down arrow more than once, though to select the desired field.
Yes, you can using Templates. (Window -> Preferences -> Java -> Editor -> Templates)
The basic usage is you set the name to what you want to type and you set the pattern to what you want to appear.
In my testing I set the name to xml, the Context to Java, the Pattern to TEXT_XML and Automatically insert turned on. Then when I typed out your example I was able to follow a pattern like...
getv[ctrl+space].a[enter]new V[ctrl+space, down arrow, Enter]M[ctrl+Space, Enter].xml[ctrl+space]
and since Automatically insert was turned on poof TEXT_XML was inserted.
Templates have much more functionality than that and the one source I used for this answer was Effective Eclipse.
I hope this helps!