Pooya
Pooya

Reputation: 4481

How to insert new line just after method and type annotations using Eclipse JDT code formatter?

I'm using Eclipse JDT API to format my generated java source files. With which options I can force formatter to make the output as like below:

@Annotation1 
@Annotation2
@Annotation3
@Annotation4 
public class TheClass {

    private static final int PAGE_SIZE = 10;

    @Annotation5 
    private Object o1;

    @Annotation5 
    private Object o2;


    @Annotation6
    @Annotation7 
    public void doSomething(@Annotation8 @Annotation Object dto) {
         // some works
    }
}

As I know the DefaultCodeFormatterOptions has insert_new_line_after_annotation field that adds new line after all annotations, Even the method parameter annotations. But I want to add new-line just after type method or type annotations

Edit:

this is the formatter code :

public String format(String code)
        throws MalformedTreeException, BadLocationException {
    Map options = new java.util.HashMap();
    options.put(JavaCore.COMPILER_SOURCE, "1.5");
    options.put(JavaCore.COMPILER_COMPLIANCE, "1.5");
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, "1.5");

    DefaultCodeFormatterOptions cfOptions =
            DefaultCodeFormatterOptions.getDefaultSettings();
    cfOptions.insert_new_line_after_annotation = false;
    cfOptions.comment_insert_new_line_for_parameter = true;

    cfOptions.blank_lines_before_method = 1;
    cfOptions.number_of_empty_lines_to_preserve= 1;

    cfOptions.tab_char = DefaultCodeFormatterOptions.SPACE;

    CodeFormatter cf = new DefaultCodeFormatter(cfOptions, options);

    TextEdit te = cf.format(CodeFormatter.K_UNKNOWN, code, 0,
            code.length(), 0, null);
    IDocument dc = new Document(code);

    te.apply(dc);
    return dc.get();
}

Upvotes: 1

Views: 1253

Answers (1)

Adam
Adam

Reputation: 36703

DefaultCodeFormatterOptions has separate fields for new line after annotations for every possible context of the annotation

public boolean insert_new_line_after_annotation_on_type;
public boolean insert_new_line_after_annotation_on_field;
public boolean insert_new_line_after_annotation_on_method;
public boolean insert_new_line_after_annotation_on_package;
public boolean insert_new_line_after_annotation_on_parameter;
public boolean insert_new_line_after_annotation_on_local_variable;

So I'm guessing insert_new_line_after_annotation_on_type is the answer... I've checked this behaves as expected with the IDE itself rather than the API.

This is a relatively new addition added by this commit in February 2014 to fix bug/feature 425040. It's available in the eclipse in front of me 4.4.0

Upvotes: 1

Related Questions