Explain Codes LogoExplain Codes Logo

How to turn off the Eclipse code formatter for certain sections of Java code?

java
best-practices
code-formatting
eclipse
Anton ShumikhinbyAnton ShumikhinยทDec 14, 2024
โšกTLDR

Eclipse auto-formatter can be controlled using special comments // @formatter:off and // @formatter:on. The code between these comments will not be formatted.

// Allow chaos in code, enjoy! ๐ŸŽ‰ @formatter:off public void unleashChaos() { // Code within this will evoke the spirit of anti-formatter! } // Bring back discipline, Phew! ๐Ÿ˜“ @formatter:on

To use this feature, first, activate it in Eclipse by clicking Enable Off/On tags in following setting in Preferences: Preferences > Java > Code Style > Formatter > Edit > Off/On Tags.

One for all: shared Formatter Profiles

In collaborative projects, having uniform formatting is important to maintain code consistency. By enabling @formatter:off and @formatter:on tags, the team can share a common formatter setting which remains consistent across different IDE configurations.

One-shot setup: Shared Formatter Profile

Create a Formatter Profile with predefined settings and share it amongst your team through your version control system. This one-time setup ensures uniformity in formatting without each developer adjusting their individual formatter settings.

Line Break preservation: the "Never Join Lines" plea

Eclipse respects line breaks ensuring the readability of complex or sizeable chunks of code. To enable this, use the "Never Join Lines" preference available in Eclipse 3.5 M4 and onwards. Your SQL queries in Java code can breathe easy now!

Project to the rescue: Project-specific settings

Set up project-specific formatter settings under Project Properties > Java Code Style > Formatter. With these settings, the formatter preferences of a project adapt automatically for every developer working on it, avoiding manual setups.

Code-specific Formatting

Keep Blocks wild

Just like line comments, block comments can also enjoy the freedom of unformatted text. Just initiate a block of code with /*- and the code formatter would leave it unformatted, preserving the wildness!

SQL within your Java code

For the SQL queries peppered across your Java code, turn off the auto-formatting to improve readability and to make it easier for your SQL fan-club to understand. Your code will remain as eye-soothing as SQL allows ๐Ÿ˜‹.

Concatenated String Literals and the Formatter

Working with concatenated string literals can be a tricky affair when dealing with auto-formatter. In such cases, Eclipse bestows upon you the power to control how these literals are formatted.