Java Code Examples for org.eclipse.jdt.internal.corext.util.CodeFormatterUtil#format2()

The following examples show how to use org.eclipse.jdt.internal.corext.util.CodeFormatterUtil#format2() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProjectResources.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Given a String containing the text of a Java source file, return the same
 * Java source, but reformatted by the Eclipse auto-format code, with the
 * user's current Java preferences.
 */
public static String reformatJavaSourceAsString(String source) {
  TextEdit reformatTextEdit = CodeFormatterUtil.format2(
      CodeFormatter.K_COMPILATION_UNIT, source, 0, (String) null,
      JavaCore.getOptions());
  if (reformatTextEdit != null) {
    Document document = new Document(source);
    try {
      reformatTextEdit.apply(document, TextEdit.NONE);
      source = document.get();
    } catch (BadLocationException ble) {
      CorePluginLog.logError(ble);
    }
  }
  return source;
}
 
Example 2
Source File: JavaFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void format(IDocument doc, CompilationUnitContext context) throws BadLocationException {
	Map<String, String> options;
	IJavaProject project= context.getJavaProject();
	if (project != null)
		options= project.getOptions(true);
	else
		options= JavaCore.getOptions();

	String contents= doc.get();
	int[] kinds= { CodeFormatter.K_EXPRESSION, CodeFormatter.K_STATEMENTS, CodeFormatter.K_UNKNOWN};
	TextEdit edit= null;
	for (int i= 0; i < kinds.length && edit == null; i++) {
		edit= CodeFormatterUtil.format2(kinds[i], contents, fInitialIndentLevel, fLineDelimiter, options);
	}

	if (edit == null)
		throw new BadLocationException(); // fall back to indenting

	edit.apply(doc, TextEdit.UPDATE_REGIONS);
}
 
Example 3
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static String asFormattedString(ASTNode node, int indent, String lineDelim, Map<String, String> options) {
	String unformatted= asString(node);
	TextEdit edit= CodeFormatterUtil.format2(node, unformatted, indent, lineDelim, options);
	if (edit != null) {
		Document document= new Document(unformatted);
		try {
			edit.apply(document, TextEdit.NONE);
		} catch (BadLocationException e) {
			JavaPlugin.log(e);
		}
		return document.get();
	}
	return unformatted; // unknown node
}