How to stop Eclipse from indenting extra spaces in this specific scenario? - java

When I am writing anonymous classes, I want my anonymous class to look like:
SaleTodayOnly sale = new SaleTodayOnly() // line 1
{ // line 2
some implementation
}
But when I hit enter after line 1, Eclipse will automatically position my cursor at | on line 2:
SaleTodayOnly sale = new SaleTodayOnly() // line 1
| // line 2
some implementation
And when I backspace my way to the front and write {, Eclipse will reposition this { to:
SaleTodayOnly sale = new SaleTodayOnly() // line 1
{ // line 2
some implementation
How can I set my own indentation preferences (for this specific scenario only)?
edit: I have my anonymous class set to next line. It's probably a wrapping issue.
edit2: I give up. I'll just use java conventions of { on the same line as the anonymous class declaration...
edit3: after hunting around the Preference window, toggling without much effect + seeing how Format produces the right output whereas the problem described still persists -- I'd agree that this is probably a bug and I will file a report when I have time.

Go into your preferences. (Window -> Preferences, probably; on mac it'll be under the leftmost menu option ('Eclipse')) - in the filter type 'formatter' to find the entry Java > Code Style > Formatter.
The behaviour you are witnessing is non-standard so you must already have a format defined; you picked this indent behavior, or somebody did who set this as default formatter.
edit this format. Alternatively, check if your project has a custom formatting rule in which case, this same answer applies, but instead go via your project's properties and update the formatting rules there.
The specific rule you are looking for is Brace positions, Anonymous class declaration. You have this set to Next line indented. Set it to something else. It sounds like you want Next line (not indented).

Related

Xtext 2.10 (AbstractFormatter2): Indentation for single or multiline comments is not always correct

Problem Description:
The default indentation for single or multiline comments does not always work properly. The following issues are being faced.
The indentation for single line comments never worked if there wasn’t already
at-least a space or a tab in-front of them.
The indentation for single or multi-line comments never worked if they were part of the IHiddenRegion for which a decrease of indentation was set. The current understanding is that the formatter for the respective IHiddenRegion will increase the indentation for the comments contained in it and will then set an overall decrease of indentation for the upcoming strictly alternating IHiddenRegion(s) or IsemanticRegion(s).
Important Note:
Kindly direct us to an already existing eclipse Xtext ticket, if this is a known issue. Or any stackoverflow threads that explain why this is happening. And what could possible be coded wrong within the formatters based on IFormmatter2. Else please read further, would appreciate useful hints, solutions that could help us reach to a solution.
Further Explanation:
By "default indentation" its meant that:
The methods applyHiddenRegionFormatting, createCommentReplacer or any other related methods to manipulate comments are not overridden.
The terminal rules for SL_COMMENT and ML_COMMENT are left unchanged and are as under (taken from Terminals.xtext):
terminal ML_COMMENT : '/*' -> '*/';
terminal SL_COMMENT : '//' !('\n'|'\r')* ('\r'? '\n')?;
There are also no other known changes made to manipulate comments in any form.
The current usage/behaviour understanding of AbstractFormatter2 w.r.t. indentation is as follows, please correct if its incorrect.
Given an EObject the following ways to set an indentation collectively for text of contained IHiddenRegion(s) and ISemanticRegion(s) are available:
EObject.interior().indent[]
Interior.(ISemanticRegion_Start, ISemanticRegion_End).indent[], where ISemanticRegion_Start & ISemanticRegion_End were taken for the keywords '{' and '}' respectively contained within the EObject.
Document.set(IHiddenRegion_Start, IHiddenRegion_End).indent[], where IHiddenRegion_Start was the next hidden region of ISemanticRegion_Start (as explained above) and IHiddenRegion_End was the previous hidden region of ISemanticRegion_End (as explained above).
For '2' and '3' above the current understanding is that the indentation will be increased for all the strictly alternating IHiddenRegion(s) and ISemanticRegion(s) that will be in between two ISemanticRegions (in case of '2') or between two IHiddenRegions (in case of '3', the two start and end boundary IHiddenRegions will be included) respectively.
The indentation of the comments showed exactly the same behaviour when using any of the above approaches. Please also advise if there is always a need to override certain methods to handle formatting of comments correctly. Or the default implementations provided for handling comments are sufficient.
As an example, the behaviour of the the formatters from our projects and the one from domain model example (org.eclipse.xtext.example.domainmodel) for the indentation of comments was identical. Hence providing below an example DSL with comments from the domain model example so that its easy to relate to it.
Example domain model DSL with comments:
package p1 {
/*
* ml one
*/
// sl 11
// sl 12
package p2 {
}
// sl two
package p3 {
}
// sl three
/*
* ml two
*/
/*
* ml three
*/
package p4 {
}
// sl four
/*
* ml four
*/
/*
* ml five
*/
}
In the example above comment "sl 12" is an example of the incorrect indentation case (1). And comments "sl four" and "ml four" are examples of case (2). As explained in the very beginning. Comment "sl 11" is an example of the right indentation of a single line comment when there was at-least a space or a tab in-front of it. The indentation of multi line comments works correctly also when there is no space or tab in-front of them.
Additional Points:
It was also tested if it makes a difference to use grammar access for aquiring access to the required ISemanticRegions, i.e. EObject.regionFor.ruleCall() instead of Eobject.regionFor.keyword(), but the results were the same.
Also in the domain model example the formatter extends XbaseFormatter while the formatter in our projects extends AbstractFormatter2, but the results of both formatters is also identical w.r.t. comments. The resulting DSL(s) and comments contained in them are in English language.
Thanks in advance.
you may try this workaround
class DomainmodelFormatter extends XbaseFormatter {
override ITextReplacer createCommentReplacer(IComment comment) {
var EObject grammarElement=comment.getGrammarElement()
if (grammarElement instanceof AbstractRule) {
var String ruleName=((grammarElement as AbstractRule)).getName()
if (ruleName.startsWith("ML")) return new MultilineCommentReplacer(comment,Character.valueOf('*').charValue)
if (ruleName.startsWith("SL")) {
if (comment.getLineRegions().get(0).getIndentation().getLength() > 0)
return new SinglelineDocCommentReplacer(comment,"//")
else
return new SinglelineCommentReplacer(comment,"//") {
override configureWhitespace(WhitespaceReplacer leading, WhitespaceReplacer trailing) {
// do nothing
}
override createReplacements(ITextReplacerContext context) {
return context
}
}
}
}
var String elementName=new GrammarElementTitleSwitch().showQualified().showRule().doSwitch(grammarElement)
throw new IllegalStateException('''No «ITextReplacer.getSimpleName()» configured for «elementName»''')
}
}

Eclipse Formatter Options for '.' Alignment (Java) [duplicate]

This question already has answers here:
Wrapping chained method calls on a separate line in Eclipse for Java
(7 answers)
Closed 7 years ago.
I would like Eclipse to format some code which calls a builder as follows:
final Item item = new Item.Builder()
.name("something")
.field("a value")
.build();
i.e. aligning on the '.' character from the first line. I can manually convince Eclipse to do this by aligning the second line (the .name("something")) by hand, but any auto-formatting destroys this.
I've played around with all of the various formatting options that I can find in Eclipse and none of them seem to do what I want. Any ideas on if there are format options to lay out the code in this way?
Aligning exactly at the dot position is not possible, but the linebreaks for each method call can be done automatically. I've created this output
void format() {
Test test = new Test()
.a() // this call can also be configured to be one line above
.b()
.c();
}
by selecting the Line Wrapping tab in the formatter settings, selecting Function Calls, Qualified invocations, switching the Line wrapping policy in the combo box to Wrap all elements, every element on a new line and finally checking the checkbox Force split, even if line shorter than maximum line width.
You can get the first method call into the first line by selecting the "...except first element" policy instead.
Create a new formater:
Properties -> Formater -> Configure Workspace Settings -> New
then on the tab Off/On Tags set Enable Off/On tags
And then just surround your code like this:
/* #formatter:off */
final Item item = new Item.Builder()
.name("something")
.field("a value")
.build();
/* #formatter:on */
I think, you can achieve this by using 'jalopy'. There is a plugin for Maven, if you use Maven.
In case, you would like to use jalopy then, the setting that you would be interested is <methodCallChain> in the alignment element whose value you should set to true.
Edited: maven jalopy plugin. Make sure you target the clean phase and use the goal format

Eclipse `sysout` snippet/expansion to System.out.printf?

I would like to configure my Eclipse preferences to allow me to type:
printf<CTRL+SPACE> (or ALT+/, or anything I use as a "Content Assist" sequence)
and get this:
System.out.printf("<BANANA>%n", <argument1>);
with the ability to TAB-jump between <BANANA> and <argument1>.
The last part is important, the TAB-jump/replace. Notice the selected text would not include the %n constant, that stays.
I guess to know this I would need to know how to specify snippets, how to use the built-in variables and convert that into an entry in an .epf file.
Also, Eclipse seems to be wicked smart in figuring out from the surrounding context which variable I may want in a certain place. Probably from the type, the line proximity, whatever. Do I have any control on that myself when defining a snippet? Example:
System.out.printf("<BANANA>%n", <argument1>);
// Make BANANA equal to the second public static final String from the top + " split"
// Make argument1 the closest Float in the current block or any other Double, anywhere
I needed something "like" this in an .epf file:
/instance/org.eclipse.jdt.ui/org.eclipse.jdt.ui.text.custom_templates=<?xml version\="1.0" encoding\="UTF-8" standalone\="no"?><templates><template autoinsert\="true" context\="java" deleted\="false" description\="System.out.printf" enabled\="true" name\="pf">System.out.printf("${Message}%n", ${argument1\:var}${cursor});</template></templates>
Cursor after first argument to easily add the eventual argument2, ...
What's missing is a way to specify choice among a set, e.g. "choose one of %s, %d, %f, ..."

Getting Eclipse to wrap the parenthetical of a for loop

I understand the importance of succinct, clear code and that code line wrapping should be avoided, if possible. However, the requirement for this project is that no line should go beyond column 80 and I'm being asked to use verbose variable naming. Therefore, something as simple as a for loop parenthetical will need to be wrapped and that's where I'm finding Eclipse falling short.
It doesn't appear that Eclipse is capable of wrapping the parenthetical of a for loop or preserving the wrapping set. For example, my initialization statement, expression and update/counter are on separate lines like so:
for (initialization;
expression;
update/counter;)
{
//code...
}
When pressing Ctrl+Shift+f, Eclipse makes it:
for (initialization; expression; update/counter;)
{
//code...
}
Is there a way to get Eclipse to preserve this formatting. I've created a custom Eclipse formatter, but can't find any setting that will wrap the for loop parenthetical. I did see one post that suggested using //, but that won't work inside of a for loop's parenthesis.
I do not remember of an option to preserve the line feeds after each of the for's "initialization", "expression", "update". The rest can be done, but not the wrapping inside the for loop's parenthesis.
If you really need to preserve such a wrapping, you may want to disable the formatter altogether on these lines? If you go to the formater settings (Window > preferences > java > code style > formatter, then click "edit..."), then on the "Off/On Tags" tab (appeared in Eclipse 3.6 IIRC), you can enable tags to disable the formatter on specific parts of the code.
With the default tags, that would give something like :
// #formatter:off
for (initialization;
expression;
update/counter)
// #formatter:on
{
//code...
}
You can also use this way:
for (/**/initialization;
/**/expression;
/**/update/counter;)
/**/{
//code...
}
This also works:
for (initialization; //
expression; //
update/counter) {
// code...
}

Can Eclipse Formatter Wrap Where Necessary, Every Element on a New Line?

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!

Categories