My problem with eclipse's auto format is that it's taking this:
public List<JSON> getIdentityQualifiers(String identity)
throws DatabaseException
{
//....code
}
to this:
public List<JSON> getIdentityQualifiers(String identity)
throws DatabaseException
{
//....code
}
Obviously, I want to keep the previous formatting, but I can't find where to control this.
Go to Project -> Properties -> Java Code Style -> Formatter and you will see the formatting options. There are a lot of different styles.
My company provides us with a custom XML which defines exactly how they want things formatted, which was created internally. Eclipse allows you to define your formatting exactly in this format. There will certainly be tutorials online if this is important to you. You may be able to write your own or find many examples in Eclipse marketplace and online.
You could also try like that , first select segment of code which one you want to indent for e.g
if(true)
{
System.out.println("INDENTED");
}
select and type Ctrl + Shift + F.
After that you get.
if (true) {
System.out.println("INDENTED");
}
For customization you can find from there *Project --> Properties --> Java Code Style --> *
I think basically it may have been my version of Eclipse or something obscure as this stopped happening a long time ago.
Related
I've got some Java code with SQL statements written as Java strings (please no OR/M flamewars, the embedded SQL is what it is - not my decision).
I've broken the SQL statements semantically into several concatenated strings over several lines of code for ease of maintenance. So instead of something like:
String query = "SELECT FOO, BAR, BAZ FROM ABC WHERE BAR > 4";
I have something like:
String query =
"SELECT FOO, BAR, BAZ" +
" FROM ABC " +
" WHERE BAR > 4 ";
This style makes the SQL much easier to read and maintain (IMHO), especially for larger queries. For example, I can put my editor into "overwrite" mode and modify the text in-place fairly easily.
Note that this issue generalizes beyond the particular example of SQL. Any code that is written with any vertical formatting, particularly tabular constructs, is susceptible to destruction by a pretty printer.
Now, some project members use the Eclipse editor and the semantic formatting is often destroyed when they format an entire source file.
Is there a way to instruct Eclipse to ignore certain lines of source with respect to formatting?
I'm looking for something like a special comment that toggles the Eclipse formatter. Ideally, such a comment could be configurable to be whatever we choose, and other formatters could be programmed to respect it as well:
// STOP-ECLIPSE-FORMATTING
String query =
"SELECT FOO, BAR, BAZ" +
" FROM ABC " +
" WHERE BAR > 4 ";
// START-ECLIPSE-FORMATTING
Obviously, one "solution" is to have our team members standardize on some external formatter like Jalopy or JIndent, but that's not what this question is about (also, not my decision on this project): I'm specifically looking for a way to avoid the Eclipse formatter on an ad-hoc basis.
Ideally, a solution will allow me to insert instructions for the Eclipse formatter without requiring team members using Eclipse to do any IDE reconfiguration (other than possibly choosing a formatter agnostic command comment: STOP-ECLIPSE-FORMATTING → STOP-FORMATTING).
Eclipse 3.6 allows you to turn off formatting by placing a special comment, like
// #formatter:off
...
// #formatter:on
The on/off features have to be turned "on" in Eclipse preferences: Java > Code Style > Formatter. Click on Edit, Off/On Tags, enable Enable Off/On tags.
It's also possible to change the magic strings in the preferences — check out the Eclipse 3.6 docs here.
More Information
Java
>
Code Style
>
Formatter
>
Edit
>
Off/On Tags
This preference allows you to define one tag to disable and one tag to enable the formatter (see the Off/On Tags tab in your formatter profile):
You also need to enable the flags from Java Formatting
AFAIK from Eclipse 3.5 M4 on the formatter has an option "Never Join Lines" which preserves user lines breaks. Maybe that does what you want.
Else there is this ugly hack
String query = //
"SELECT FOO, BAR, BAZ" + //
" FROM ABC" + //
" WHERE BAR > 4";
See this answer on SO.
There is another solution that you can use to suppress the formatting of specific block comments. Use /*- (note the hyphen) at the beginning of the block comment, and the formatting won't be affected if you format the rest of the file.
/*-
* Here is a block comment with some very special
* formatting that I want indent(1) to ignore.
*
* one
* two
* three
*/
Source: Documentation at Oracle.
Instead of turning the formatting off, you can configure it not to join already wrapped lines. Similar to Jitter's response, here's for Eclipse STS:
Properties → Java Code Style → Formatter → Enable project specific settings OR Configure Workspace Settings → Edit → Line Wrapping (tab) → check "Never join already wrapped lines"
Save, apply.
You have to turn on the ability to add the formatter tags. In the menubar go to:
Windows
→
Preferences
Java
→
Code Style
→
Formatter
Press the Edit button. Choose the last tab. Notice the On/Off box and enable them with a checkbox.
If you put the plus sign on the beginning of the line, it formats differently:
String query =
"SELECT FOO, BAR, BAZ"
+ " FROM ABC"
+ " WHERE BAR > 4";
End each of the lines with a double slash "//". That will keep eclipse from moving them all onto the same line.
I'm using fixed width string-parts (padded with whitespace) to avoid having the formatter mess up my SQL string indentation. This gives you mixed results, and won't work where whitespace is not ignored as it is in SQL, but can be helpful.
final String sql = "SELECT v.value FROM properties p "
+ "JOIN property_values v ON p.property_id = v.property_id "
+ "WHERE p.product_id = ? "
+ "AND v.value IS NOT NULL ";
Alternative method: In Eclipse 3.6, under "Line Wrapping" then "General Settings" there is an option to "Never join already wrapped lines." This means the formatter will wrap long lines but not undo any wrapping you already have.
#xpmatteo has the answer to disabling portions of code, but in addition to this, the default eclipse settings should be set to only format edited lines of code instead of the whole file.
Preferences->Java->Editor->Save Actions->Format Source Code->Format Edited Lines
This would have prevented it from happening in the first place since your coworkers are reformatting code they didn't actually change. This is a good practice to prevent mishaps that render diff on your source control useless (when an entire file is reformatted because of minor format setting differences).
It would also prevent the reformatting if the on/off tags option was turned off.
The phantom comments, adding // where you want new lines, are great!
The #formatter: off adds a reference from the code to the editor. The code should, in my opinion, never have such references.
The phantom comments (//) will work regardless of the formatting tool used. Regardless of Eclipse or InteliJ or whatever editor you use. This even works with the very nice Google Java Format
The phantom comments (//) will work all over your application. If you also have Javascript and perhaps use something like JSBeautifier. You can have similar code style also in the Javascript.
Actually, you probably DO want formatting right? You want to remove mixed tab/space and trailing spaces. You want to indent the lines according to the code standard. What you DONT want is a long line. That, and only that, is what the phantom comment gives you!
Not so pretty but works with default settings and for the first line as well:
String query = "" +
"SELECT FOO, BAR, BAZ" +
" FROM ABC " +
" WHERE BAR > 4 ";
This hack works:
String x = "s" + //Formatter Hack
"a" + //
"c" + //
"d";
I would suggest not to use the formatter. Bad code should look bad not artificially good. Good code takes time. You cannot cheat on quality. Formatting is part of source code quality.
According to the standard coding practice "Left curly braces should be located at the end of lines of code". e.g.,
/* Not a good coding practice*/
} else
{
}
/* Good coding practice */
} else {
}
Actually I ran Sonar on my Java project and because of the above mentioned Rule, I got more than 6000 errors. Is there any shortcut in eclipse or any other way to fix these errors(at a time)?
Open the java files(where errors occured) and use "Ctrl+Shift+F" key to format. Then code will be formatted according "Formatter" settings
I've started using Java again recently and I'm setting up my dev environment in eclipse which has a handy format function that formats the code for you. This is great cause I've been able to set the settings to fit my code standard almost perfectly except for local variable declaration. I like to keep my declarations lined up (there is even an option for class parameter declaration that does what I want)
Here is what I would like :
void jad()
{
int alpha = 1;
String beta = "jad";
MyOwnObject SomeReallyLongName = new MyOwnObject();
}
Instead, eclipse's format gives me :
void jad()
{
int alpha = 1;
String beta = "jad";
MyOwnObject SomeReallyLongName = new MyOwnObject();
}
I don't mind if it doesn't format it the way I want it too, I would just love it if it didn't remove the whitespaces that I put there myself >.< (if it can do it for me, that would be even better of course).
Anybody know how to get eclipse to do something like this? (couldn't find any option in the Code Style editor)
Actually the formatter will do this alignment for you. Go into Preference -> Java -> Code Style -> Formatter and Edit the profile. Look at the Indentation tab, there will be an option to Align Fields in Columns.
But it just aligns the class, not the method variables, so not what you want.
I'm tying to figure out how I can customize the Eclipse code formatter to break lines more to my liking. I'm trying to set the style for parameter lists, either in method declarations or calls. Looking for a mix of Wrap where necessary and Wrap all elements, every element on a new line. I want to Wrap where necessary, every element on a new line, which doesn't seem to exist. My logic is that no break is necessary for short lines, my eye can scan the parameter list horizontally:
public void myMethod(int p1, int p2, int p3) {
But for lists that do need to be broken, I would like every element on a new line, so I can scan vertically:
public void myMethodWithALotOfParams(
ReallyLongClassName param1,
AnotherLongName aLongParamName,
int p3) {
I can't seem to make this happen. I can wrap everything, including short lists. I can wrap only long lines, and continue stacking parameters on each line until I reach the margin. I can't trigger wrapping on long lines, then put each parameter on its own line.
This style can be seen in several places in Code Complete (2nd Ed).
UPDATE >>
I don't think there is anything built in to Eclipse to handle this, but I'm not afraid to write code. :) Eclipse is open source, so I tried to find the code that handles formatting, in hopes of building in the preferred behavior. Didn't have much luck on the first try, lots of abstraction, not much parsing and formatting. Hints?
look at this link
Window -> Preferences -> Java -> Code Style -> Formatter -> New (Profile) -> Edit -> Line Wrapping -> Never join already wrapped lines
Or change other parameters if you want to change line wrapping parameters.
I would like to have such a feature too, unfortunatly (as you already guessed) it's not possible, yet. If you like you can file a bug at the eclipse-bugzilla, here you will find some bugs about formatting in jdt: https://bugs.eclipse.org/bugs/buglist.cgi?quicksearch=jdt+formatter. Let us know if you file a new bug, so everyone interested can vote for it!
I was just wandering why is the prefix XXX ?
As far as I know its used for notes/reminders (or at least this is what I use it for and that is what the people on most of the links I googled use it for).
So does anyone know where the XXX prefix come from ?
From Sun/Oracle's Java code conventions, section 10.5.4:
Use XXX in a comment to flag something that is bogus but works. Use FIXME to flag something that is bogus and broken.
From the Hacker's Dictionary entry for "XXX":
A marker that attention is needed.
Commonly used in program comments to
indicate areas that are kluged up or
need to be. Some hackers liken `XXX'
to the notional heavy-porn movie
rating. Compare FIXME.
XXX, along with FIXME and TODO, is known in Eclipse as a task tag, and is indexed by the IDE to let you find the spots marked with those tags easily. You can edit such tags in the Eclipse Preferences -> Java -> Compiler -> Task Tags.
As to where it comes from: it probably emerged form the "tags" that programmers spontaneously wrote in their code to quickly mark a given line. While FIXME and TODO are explicit enough, the reason XXX was used could be a combination of these reasons:
The string "XXX" does not usually occur in regular source code and is easy to look for with tools such as grep or a simple text search in an editor;
Traditionally, "X marks the spot" which needs attention; triple X even more so;
The X key is very close to the Command/Alt/Windows keys and is easy to reach, being on the lower row of the keyboard.
I can't think of anything else...
Various reasons:
It's easy to search for.
No collision, as no sane person would use it as a variable.
It can used to mark code that needs e*X*tra special attention, dangerous code, not to be seen by underaged, etc.
I've worked with a team where XXX was used to point out a "bug or task that was not yet entered in Trac.". After it was entered in Trac the comment would be changed to TODO with the ID appended.
To Eclipse though, it's just a marker like TODO and FIXME. I imagine that it's originally used as a strong form of TODO. You usually see comments like this:
// TODO: Need to optimize this once n becomes greater than 1000.
But sometimes you'll have a comment like:
// TODO: Fix SQL injection bug before production release!
Unfortunately a quick grep wont make that SQL injection bug stand out among the 1000s of other TODOs. Using XXX here would help mark things that must be done before a milestone/release etc.
There's also a reference to it on Wikipedia:
XXX to warn other programmers of problematic or misguiding code.
It bugs me too, because XXX may also be used for masking input or format numbers,
Thus creating multi markers warning when you describe amount format:
/**
* #param amount (XXX or XXX.XX)
*/
public doSomething(String amount) {
Multiple markers at this line
-XXX or
-XXX.XX)
As #Jean-PhilippePellet suggested, you can remove it from
Preferences -> Java -> Compiler -> Task Tags