Eclipse has a wonderful feature that formats according to your coding standards. It handles things like indentation, where curly braces are placed, if blank lines should occur between field declaration and hundreds of other options.
However, to invoke this formatting, you have to tell Eclipse to do this every time you’ve edited the code. You can do this using Ctrl+Shift+F but (1) you have to do that every time and (2) you have to remember to do it in the first place (and we all know how good developers are at remembering things).
Eclipse sports a feature called Save Actions that makes formatting code easy. With this feature enabled, every time you save the file, Eclipse formats the code to your formatting preferences and does some cleanup of the code (eg. remove unused imports). All done automatically and for free.
How to enable automatic formatting and cleanup
By default automatic formatting and cleanup is disabled. To enable it, do the following:
- Go to Window > Preferences > Java > Editor > Save Actions.
- Select Perform the selected actions on save.
- Select Format Source code. Make sure Format all lines is selected. Below I discuss when to use the other option.
- Make sure Organize imports is selected.
- Select Additional actions.
- Click Ok, edit some code, save it and watch Eclipse format it automatically.
Here’s what the settings should look like.
How does Eclipse “clean up” the code
With “Format source code” enabled, the code is formatted according to the formatting rules you’ve specified under Java > Code Style > Formatter (or project-specific formatting if enabled).
With “Organize imports” enabled, Eclipse will automatically reorder imports, prompt for imports to unresolved classes and remove unused imports. It basically does a Ctrl+Shift+O whenever you save.
When you enabled the option “Additional actions”, you told Eclipse to do more cleanups. You can see what they are and what you want done by clicking Configure on the same preference page. Make sure that Additional actions is ticked.
Eclipse can clean up a lot of things, but here’s a list of some of the more useful ones I have enabled:
- Add @Override and @Deprecated tags: Nice for compile-time checking. Under the Missing Code tab.
- Use final modifier where possible: A nice thing if you want final variables to be marked as final automatically. Can get annoying sometimes, but mostly worth the trouble. Under the Code Style tab.
- Convert for loops to enhanced: Replaces an index-based loop with an enhanced for loop. It just reads better. Under the Code Style tab.
- Use blocks in if/while/for/do statements: Forget religious wars, I’ve programmed long enough to know that you always use braces even for single line blocks. Eclipse can do this automatically. Under the Code Style tab.
- Remove trailing whitespace: Nice one if you’re obsessive about those blanks at the end of lines. Under the Code Organizing tab.
Why should I enable Save Actions?
Many reasons. You don’t have to remember to ask Eclipse to organise imports or format code, ie. more chance of standardised code in your team. You save time by not having to invoke these actions as well, ie. individual developer time saved.
Your version history comparisons become a lot easier as well because any developer working on the code would have done the same formatting and cleanup.
But it could mess up SCM/VCS diffs with earlier versions of the class
Yes, you could lose diff-ability with earlier versions of the class because Eclipse might reformat the whole file, especially if it’s not in your current coding standards. But I would rather take the hit the first time and reformat a class to the team standards rather than have it in an inconsistent format.
However, to address this complaint, there is also an option to only format/clean up only the parts of the code that you’ve recently worked on. On the same page you enabled the Save Actions, select Format edited lines instead of Format all lines. This will ensure that the new code conforms to the standards but the older code still stays relatively comparable from earlier versions.
Related Tips
- Generate static imports in Eclipse on autocomplete for JUnit Assert, StringUtils and others
- Add comments and Javadocs in Eclipse with a single keystroke
- Automatically place a semicolon at the end of Java statements in Eclipse
Byron,
Thanks for these tips. This is a real time saver and it keeps my code automatically formatted.
Jim
It is useful post. Thank you.
@Jim, @sheff – I’m glad I could help. This feature does make life a lot easier.
Great tips đ Thanks
how 2 do 4 PHP
Thanks
Thanks for your tips…..Helped me……
Thanks a lot for the tips.
Nice description, thanks !
I have 2 questions:
1) How does this relate to the option Java -> Code Style -> Clean Up? It seems to me that there is some duplication of configuration options, and I’m not sure how to go about it.
2) Is it possible to have this one nicely exported as we can do with the above Clean Up (for other team members to import)?
Thanks for the compliment, Tanja.
1) From my understanding, the option under Java > Code Style > Clean Up is only invoked if you manually ask for a clean up. So you have to click Source > Clean Up… on a Java class and that will open a Clean Up wizard with the configured options. OTOH, the options under Save Actions happen whenever you save, so it’s automatic.
I think you’re right that there’s duplication between the two. Not sure why the one doesn’t pick up config from the other.
2) Although you can’t export an individual clean up config like you can from Code Style > Clean Up, you can export all the Java Code Style options to share amongst the team.
So go to File > Export > Preferences, deselect Export All and then select the option Java Code Style Preferences. This will export code style related settings like Formatter, Clean Up and Save Actions settings. Team members can then import these without touching any of their other workspace/workbench settings.
Alternatively, export *all* preferences (select Export All on the Preferences dialog) and edit the exported file manually to only include cleanup options (the start with “/instance/org.eclipse.jdt.ui/cleanup.”).
However, I’d recommend the first option as you get all formatting related settings in one export file.
Hope that helps.
Hey Byron… Thank you so much. You save my lots of time. Really useful tip. Great job. đ
Auto-formatting code according to your own personal preferences is not a good thing when you are part of a larger team. Imagine the fun when each developer has their own personal style of indentations, import arrangements, etc. Every code check-in would end up being a change to nearly every line of code so that a change to a single line looks like a massive recoding.
I agree, that’s why it’s important for your team to share the same formatter settings, which you can do by exporting and importing into individual workspaces. If your team members don’t agree on a single style then you’re going to have issues anyway, aside from autoformatting.
Also check out the section on using it with an SCM and setting “Format edited lines only”.