com.xlrit.gears.runner.runnertarget.JavaFormatter Maven / Gradle / Ivy
package com.xlrit.gears.runner.runnertarget;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jdt.internal.formatter.DefaultCodeFormatter;
import org.eclipse.jdt.internal.formatter.DefaultCodeFormatterOptions;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.text.edits.TextEdit;
public class JavaFormatter {
public static String format(String source) throws BadLocationException {
DefaultCodeFormatterOptions options = new DefaultCodeFormatterOptions(null);
options.page_width = 180;
options.comment_line_length = 180;
options.continuation_indentation = 1;
// need to create a new formatter since it's not thread-safe
CodeFormatter fmt = new DefaultCodeFormatter(options);
int kind = CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS;
TextEdit edit = fmt.format(kind, source, 0, source.length(), 0, "\n");
if (edit == null) throw new IllegalArgumentException("Invalid java syntax for formatting.");
Document doc = new Document(source);
edit.apply(doc);
return doc.get();
}
}