Java Code Examples for org.eclipse.jface.text.Document#get()

The following examples show how to use org.eclipse.jface.text.Document#get() . 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: TextEditConverter.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean visit(CopySourceEdit edit) {
	try {
		if (edit.getTargetEdit() != null) {
			org.eclipse.lsp4j.TextEdit te = new org.eclipse.lsp4j.TextEdit();
			te.setRange(JDTUtils.toRange(compilationUnit, edit.getOffset(), edit.getLength()));
			Document doc = new Document(compilationUnit.getSource());
			edit.apply(doc, TextEdit.UPDATE_REGIONS);
			String content = doc.get(edit.getOffset(), edit.getLength());
			if (edit.getSourceModifier() != null) {
				content = applySourceModifier(content, edit.getSourceModifier());
			}
			te.setNewText(content);
			converted.add(te);
		}
		return false;
	} catch (JavaModelException | MalformedTreeException | BadLocationException e) {
		JavaLanguageServerPlugin.logException("Error converting TextEdits", e);
	}
	return super.visit(edit);
}
 
Example 2
Source File: CommentFormatterUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Evaluates the edit on the given string.
 *
 * @throws IllegalArgumentException if the positions are not inside the
 *                 string
 */
public static String evaluateFormatterEdit(String string, TextEdit edit, Position[] positions) {
	try {
		Document doc= createDocument(string, positions);
		edit.apply(doc, 0);
		if (positions != null) {
			for (int i= 0; i < positions.length; i++) {
				Assert.isTrue(!positions[i].isDeleted, "Position got deleted"); //$NON-NLS-1$
			}
		}
		return doc.get();
	} catch (BadLocationException e) {
		log(e); // bug in the formatter
		Assert.isTrue(false, "Formatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$
	}
	return null;
}
 
Example 3
Source File: TypeCreator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
private String formatJava(IType type) throws JavaModelException {
  String source = type.getCompilationUnit().getSource();
  CodeFormatter formatter = ToolFactory.createCodeFormatter(type.getJavaProject().getOptions(true));
  TextEdit formatEdit = formatter.format(CodeFormatterFlags.getFlagsForCompilationUnitFormat(), source, 0,
      source.length(), 0, lineDelimiter);
  if (formatEdit == null) {
    CorePluginLog.logError("Could not format source for " + type.getCompilationUnit().getElementName());
    return source;
  }

  Document document = new Document(source);
  try {
    formatEdit.apply(document);
    source = document.get();
  } catch (BadLocationException e) {
    CorePluginLog.logError(e);
  }

  source = Strings.trimLeadingTabsAndSpaces(source);
  return source;
}
 
Example 4
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 5
Source File: FormatterPreview.java    From xds-ide with Eclipse Public License 1.0 6 votes vote down vote up
public void setProfile(FormatterProfile fp) {
     try {
         int top = styledText.getTopPixel();
         int hor = styledText.getHorizontalPixel();
         ModulaTextFormatter m2f = new ModulaTextFormatter(fp);
         Document doc = new Document(initialText);
         BuildSettings buildSettings = DefaultBuildSettingsHolder.DefaultBuildSettings;
         ParserCriticalErrorReporter errorReporter = ParserCriticalErrorReporter.getInstance();
IImportResolver defaultImportResolver = new DefaultImportResolver(buildSettings, errorReporter, null);
         XdsParser parser = new XdsParser(null, doc.get(), new XdsSettings(buildSettings, xdsSourceType), defaultImportResolver, errorReporter);
         ModulaAst ast = parser.parseModule();
         m2f.doFormat(doc, ast, 0, doc.getLength(), false);
         styledText.setText(doc.get());
         styledText.setHorizontalPixel(hor);
         styledText.setTopPixel(top);
         if (fMarginPainter != null) {
             fMarginPainter.setMarginRulerColumn(fp.getWrappingWidth());
         }
     } catch (Exception e) {e.printStackTrace();}
     colorIt();
 }
 
Example 6
Source File: TextEditUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static String apply(Document doc, Collection<? extends TextEdit> edits) throws BadLocationException {
	Assert.isNotNull(doc);
	Assert.isNotNull(edits);
	List<TextEdit> sortedEdits = new ArrayList<>(edits);
	sortByLastEdit(sortedEdits);
	String text = doc.get();
	for (int i = sortedEdits.size() - 1; i >= 0; i--) {
		TextEdit te = sortedEdits.get(i);
		Range r = te.getRange();
		if (r != null && r.getStart() != null && r.getEnd() != null) {
			int start = getOffset(doc, r.getStart());
			int end = getOffset(doc, r.getEnd());
			text = text.substring(0, start)
					+ te.getNewText()
					+ text.substring(end, text.length());
		}
	}
	return text;
}
 
Example 7
Source File: ASTRewriteFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Evaluates the edit on the given string.
 * @param string The string to format
 * @param edit The edit resulted from the code formatter
 * @param positions Positions to update or <code>null</code>.
 * @return The formatted string
 * @throws IllegalArgumentException If the positions are not inside the string, a
 *  IllegalArgumentException is thrown.
 */
public static String evaluateFormatterEdit(String string, TextEdit edit, Position[] positions) {
	try {
		Document doc= createDocument(string, positions);
		edit.apply(doc, 0);
		if (positions != null) {
			for (int i= 0; i < positions.length; i++) {
				Assert.isTrue(!positions[i].isDeleted, "Position got deleted"); //$NON-NLS-1$
			}
		}
		return doc.get();
	} catch (BadLocationException e) {
		//JavaPlugin.log(e); // bug in the formatter
		Assert.isTrue(false, "Fromatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$
	}
	return null;
}
 
Example 8
Source File: FieldToContractInputMappingExpressionBuilderTest.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private String format(String initialValue) {
    final Document document = new Document(initialValue);
    try {
        new DefaultGroovyFormatter(document, new DefaultFormatterPreferences(), 0).format().apply(document);
    } catch (MalformedTreeException | BadLocationException e) {
        BonitaStudioLog.error("Failed to format generated script", e);
    }
    return document.get();
}
 
Example 9
Source File: TypeScriptAutoIndentStrategy.java    From typescript.java with MIT License 5 votes vote down vote up
/**
 * Returns the indentation of the line <code>line</code> in <code>document</code>.
 * The returned string may contain pairs of leading slashes that are considered
 * part of the indentation. The space before the asterisk in a javadoc-like
 * comment is not considered part of the indentation.
 *
 * @param document the document
 * @param line the line
 * @return the indentation of <code>line</code> in <code>document</code>
 * @throws BadLocationException if the document is changed concurrently
 */
private static String getCurrentIndent(Document document, int line) throws BadLocationException {
	IRegion region= document.getLineInformation(line);
	int from= region.getOffset();
	int endOffset= region.getOffset() + region.getLength();

	// go behind line comments
	int to= from;
	while (to < endOffset - 2 && document.get(to, 2).equals(LINE_COMMENT))
		to += 2;

	while (to < endOffset) {
		char ch= document.getChar(to);
		if (!Character.isWhitespace(ch))
			break;
		to++;
	}

	// don't count the space before javadoc like, asterisk-style comment lines
	if (to > from && to < endOffset - 1 && document.get(to - 1, 2).equals(" *")) { //$NON-NLS-1$
		String type= TextUtilities.getContentType(document, IJavaScriptPartitions.JAVA_PARTITIONING, to, true);
		if (type.equals(IJavaScriptPartitions.JAVA_DOC) || type.equals(IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT))
			to--;
	}

	return document.get(from, to - from);
}
 
Example 10
Source File: RefactoringLocalTestBase.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
protected void checkRename(String strDoc, int line, int col, String initialName, boolean expectError,
        boolean onlyOnLocalScope, String newName) throws CoreException {
    Document doc = new Document(
            StringUtils.format(strDoc, getSame(initialName)));
    PySelection ps = new PySelection(doc, line, col);

    RefactoringRequest request = new RefactoringRequest(null, ps, nature);
    request.setAdditionalInfo(RefactoringRequest.FIND_REFERENCES_ONLY_IN_LOCAL_SCOPE,
            onlyOnLocalScope);
    request.moduleName = "foo";
    request.inputName = newName;
    request.fillInitialNameAndOffset();

    applyRenameRefactoring(request, expectError);
    String refactored = doc.get();
    if (DEBUG) {
        System.out.println(refactored);
    }
    if (!expectError) {
        assertEquals(initialName, request.initialName);
        assertEquals(StringUtils.format(strDoc, getSame("bb")), refactored);
    } else {
        //cannot have changed
        assertEquals(StringUtils.format(strDoc, getSame(initialName)),
                refactored);
    }
}
 
Example 11
Source File: ContractConstraintExpressionWizardPageTest.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void should_documentChanged_set_expression_value() throws Exception {
    wizardPage.createControl(composite);
    final Document document = new Document("name.length() > 25");
    final DocumentEvent event = new DocumentEvent(document, 0, document.getLength(), document.get());
    wizardPage.documentChanged(event);
    assertThat(constraint.getExpression()).isEqualTo(document.get());
}
 
Example 12
Source File: JavaCodeFormatterImpl.java    From jenerate with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public String formatCode(IType objectClass, String source) throws JavaModelException, BadLocationException {
    String lineDelim = getLineDelimiterUsed(objectClass);
    int indent = getUsedIndentation(objectClass) + 1;
    TextEdit textEdit = ToolFactory.createCodeFormatter(null).format(CodeFormatter.K_CLASS_BODY_DECLARATIONS,
            source, 0, source.length(), indent, lineDelim);
    if (textEdit == null) {
        return source;
    }
    Document document = new Document(source);
    textEdit.apply(document);
    return document.get();
}
 
Example 13
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
}
 
Example 14
Source File: JavaAutoIndentStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the indentation of the line <code>line</code> in <code>document</code>.
 * The returned string may contain pairs of leading slashes that are considered
 * part of the indentation. The space before the asterisk in a javadoc-like
 * comment is not considered part of the indentation.
 *
 * @param document the document
 * @param line the line
 * @return the indentation of <code>line</code> in <code>document</code>
 * @throws BadLocationException if the document is changed concurrently
 */
private static String getCurrentIndent(Document document, int line) throws BadLocationException {
	IRegion region= document.getLineInformation(line);
	int from= region.getOffset();
	int endOffset= region.getOffset() + region.getLength();

	// go behind line comments
	int to= from;
	while (to < endOffset - 2 && document.get(to, 2).equals(LINE_COMMENT))
		to += 2;

	while (to < endOffset) {
		char ch= document.getChar(to);
		if (!Character.isWhitespace(ch))
			break;
		to++;
	}

	// don't count the space before javadoc like, asterisk-style comment lines
	if (to > from && to < endOffset - 1 && document.get(to - 1, 2).equals(" *")) { //$NON-NLS-1$
		String type= TextUtilities.getContentType(document, IJavaPartitions.JAVA_PARTITIONING, to, true);
		if (type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT))
			to--;
	}

	return document.get(from, to - from);
}
 
Example 15
Source File: XbaseEditor.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected int getStartOffsetOfContentsInJava(Document document, int line) throws BadLocationException {
	IRegion lineInformation = document.getLineInformation(line);
	String lineText = document.get(lineInformation.getOffset(), lineInformation.getLength());
	String contents = lineText.trim();
	if (contents.length() == 0) {
		log.warn("selection points to an empty line!", new IllegalStateException());
		return -1;
	}
	int contentsStarts = lineText.indexOf(contents);
	return lineInformation.getOffset() + contentsStarts;
}
 
Example 16
Source File: SortElementsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Method processElement.
 * @param unit
 * @param source
 */
private String processElement(ICompilationUnit unit, char[] source) {
	Document document = new Document(new String(source));
	CompilerOptions options = new CompilerOptions(unit.getJavaProject().getOptions(true));
	ASTParser parser = ASTParser.newParser(this.apiLevel);
	parser.setCompilerOptions(options.getMap());
	parser.setSource(source);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setResolveBindings(false);
	org.eclipse.jdt.core.dom.CompilationUnit ast = (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(null);

	ASTRewrite rewriter= sortCompilationUnit(ast, null);
	if (rewriter == null)
		return document.get();

	TextEdit edits = rewriter.rewriteAST(document, unit.getJavaProject().getOptions(true));

	RangeMarker[] markers = null;
	if (this.positions != null) {
		markers = new RangeMarker[this.positions.length];
		for (int i = 0, max = this.positions.length; i < max; i++) {
			markers[i]= new RangeMarker(this.positions[i], 0);
			insert(edits, markers[i]);
		}
	}
	try {
		edits.apply(document, TextEdit.UPDATE_REGIONS);
		if (this.positions != null) {
			for (int i= 0, max = markers.length; i < max; i++) {
				this.positions[i]= markers[i].getOffset();
			}
		}
	} catch (BadLocationException e) {
		// ignore
	}
	return document.get();
}
 
Example 17
Source File: FormatterPreview.java    From xds-ide with Eclipse Public License 1.0 4 votes vote down vote up
private void colorIt() {
     try {
         if (pstToTokenMap == null) {
             initTokenMap();
         }
         // Parse text:
         Document doc = new Document(styledText.getText());
         BuildSettings buildSettings = DefaultBuildSettingsHolder.DefaultBuildSettings;
         ParserCriticalErrorReporter errorReporter = ParserCriticalErrorReporter.getInstance();
IImportResolver defaultImportResolver = new DefaultImportResolver(buildSettings, errorReporter, null);
         XdsParser parser = new XdsParser(null, doc.get(), new XdsSettings(buildSettings, xdsSourceType), defaultImportResolver, errorReporter);
         ModulaAst ast = parser.parseModule();
         leafsNodes = new ArrayList<PstLeafNode>();
         // Fill Leaf array:
         collectLeafs(ast);
         Collections.sort(leafsNodes, new Comparator<PstLeafNode>() {
             public int compare(PstLeafNode a, PstLeafNode b) {
                 return a.getOffset() - b.getOffset();
             }
         });
         // Search matched M2Token for elements in the leaf array and collect style ranges for them:
         ArrayList<StyleRange> asr = new ArrayList<StyleRange>(); 
         for (PstLeafNode pln : leafsNodes) {
             ModulaTokens mt = pstToTokenMap.get(pln.getElementType());
             if (mt == null) {
                 mt = ModulaTokens.Default; 
             }
             int style = mt.getToken().getStyleWhenEnabled();
             StyleRange sr = new StyleRange();
             sr.fontStyle = (style & (SWT.BOLD | SWT.ITALIC));
             sr.underline = (style & TextAttribute.UNDERLINE) != 0;
             sr.strikeout = (style & TextAttribute.STRIKETHROUGH) != 0;
             sr.foreground = new Color(Display.getDefault(), mt.getToken().getRgbWhenEnabled());
             sr.background = defBackgroundColor;
             sr.start = pln.getOffset();
             sr.length = pln.getLength();
             asr.add(sr);
         }
         if (asr.size() > 0) {
             styledText.setStyleRanges(asr.toArray(new StyleRange[asr.size()]));
         }
     } catch (Exception e) {}
 }
 
Example 18
Source File: JsniFormattingUtil.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
public static TextEdit format(IDocument document, TypedPosition partition,
    Map<String, String> javaFormattingPrefs,
    Map<String, String> javaScriptFormattingPrefs, String original) {
  try {
    // Extract the JSNI block out of the document
    int offset = partition.getOffset();
    int length = partition.getLength();

    // Determine the line delimiter, indent string, and tab/indent widths
    String lineDelimiter = TextUtilities.getDefaultLineDelimiter(document);
    int tabWidth = IndentManipulation.getTabWidth(javaFormattingPrefs);
    int indentWidth = IndentManipulation.getIndentWidth(javaFormattingPrefs);

    // Get indentation level of the first line of the JSNI block (this should
    // be the line containing the JSNI method declaration)
    int methodDeclarationOffset = getMethodDeclarationOffset(document, offset);
    int jsniLine1 = document.getLineOfOffset(methodDeclarationOffset);
    int methodIndentLevel = getLineIndentLevel(document, jsniLine1, tabWidth,
        indentWidth);
    DefaultCodeFormatter defaultCodeFormatter = new DefaultCodeFormatter(
        javaFormattingPrefs);
    String indentLine = defaultCodeFormatter.createIndentationString(methodIndentLevel);

    // Extract the JSNI body out of the block and split it up by line
    String jsniSource = document.get(offset, length);
    String body = JsniParser.extractMethodBody(jsniSource);

    String formattedJs;

    // JSNI Java references mess up the JS formatter, so replace them
    // with place holder values
    JsniJavaRefReplacementResult replacementResults = replaceJsniJavaRefs(body);
    body = replacementResults.getJsni();

    TextEdit formatEdit = CodeFormatterUtil.format2(
        CodeFormatter.K_STATEMENTS, body, methodIndentLevel + 1,
        lineDelimiter, javaScriptFormattingPrefs);

    if (formatEdit != null) {

      body = restoreJsniJavaRefs(replacementResults);

      Document d = new Document(body);
      formatEdit.apply(d);

      formattedJs = d.get();

      if (!formattedJs.startsWith(lineDelimiter)) {
        formattedJs = lineDelimiter + formattedJs;
      }

      if (!formattedJs.endsWith(lineDelimiter)) {
        formattedJs = formattedJs + lineDelimiter;
      }

      formattedJs = formattedJs + indentLine;

      formattedJs = "/*-{" + formattedJs + "}-*/";

    } else {

      if (original == null) {
        return null;
      }

      formattedJs = original; // formatting failed, use the original string
    }

    return new ReplaceEdit(offset, length, formattedJs);

  } catch (Exception e) {
    GWTPluginLog.logError(e);
    return null;
  }
}
 
Example 19
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public List<ResourceChange> createTopLevelParameterObject(IPackageFragmentRoot packageFragmentRoot, CreationListener listener) throws CoreException {
	List<ResourceChange> changes= new ArrayList<ResourceChange>();
	IPackageFragment packageFragment= packageFragmentRoot.getPackageFragment(getPackage());
	if (!packageFragment.exists()) {
		changes.add(new CreatePackageChange(packageFragment));
	}
	ICompilationUnit unit= packageFragment.getCompilationUnit(getClassName() + JavaModelUtil.DEFAULT_CU_SUFFIX);
	Assert.isTrue(!unit.exists());
	IJavaProject javaProject= unit.getJavaProject();
	ICompilationUnit workingCopy= unit.getWorkingCopy(null);

	try {
		// create stub with comments and dummy type
		String lineDelimiter= StubUtility.getLineDelimiterUsed(javaProject);
		String fileComment= getFileComment(workingCopy, lineDelimiter);
		String typeComment= getTypeComment(workingCopy, lineDelimiter);
		String content= CodeGeneration.getCompilationUnitContent(workingCopy, fileComment, typeComment, "class " + getClassName() + "{}", lineDelimiter); //$NON-NLS-1$ //$NON-NLS-2$
		workingCopy.getBuffer().setContents(content);

		CompilationUnitRewrite cuRewrite= new CompilationUnitRewrite(workingCopy);
		ASTRewrite rewriter= cuRewrite.getASTRewrite();
		CompilationUnit root= cuRewrite.getRoot();
		AST ast= cuRewrite.getAST();
		ImportRewrite importRewrite= cuRewrite.getImportRewrite();

		// retrieve&replace dummy type with real class
		ListRewrite types= rewriter.getListRewrite(root, CompilationUnit.TYPES_PROPERTY);
		ASTNode dummyType= (ASTNode) types.getOriginalList().get(0);
		String newTypeName= JavaModelUtil.concatenateName(getPackage(), getClassName());
		TypeDeclaration classDeclaration= createClassDeclaration(newTypeName, cuRewrite, listener);
		classDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
		Javadoc javadoc= (Javadoc) dummyType.getStructuralProperty(TypeDeclaration.JAVADOC_PROPERTY);
		rewriter.set(classDeclaration, TypeDeclaration.JAVADOC_PROPERTY, javadoc, null);
		types.replace(dummyType, classDeclaration, null);

		// Apply rewrites and discard workingcopy
		// Using CompilationUnitRewrite.createChange() leads to strange
		// results
		String charset= ResourceUtil.getFile(unit).getCharset(false);
		Document document= new Document(content);
		try {
			rewriter.rewriteAST().apply(document);
			TextEdit rewriteImports= importRewrite.rewriteImports(null);
			rewriteImports.apply(document);
		} catch (BadLocationException e) {
			throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), RefactoringCoreMessages.IntroduceParameterObjectRefactoring_parameter_object_creation_error, e));
		}
		String docContent= document.get();
		CreateCompilationUnitChange compilationUnitChange= new CreateCompilationUnitChange(unit, docContent, charset);
		changes.add(compilationUnitChange);
	} finally {
		workingCopy.discardWorkingCopy();
	}
	return changes;
}
 
Example 20
Source File: CodeFormatterUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Old API. Consider to use format2 (TextEdit)
 *
 * @param kind
 *        Use to specify the kind of the code snippet to format.
 *        It can be any of the kind constants defined in {@link CodeFormatter}
 * @param source
 *        The source to format
 * @param indentationLevel
 *        The initial indentation level, used to shift left/right the entire source fragment.
 *        An initial indentation level of zero or below has no effect.
 * @param lineSeparator
 *        The line separator to use in formatted source,
 *        if set to <code>null</code>, then the platform default one will be used.
 * @param options
 *        The options map to use for formatting with the default code formatter.
 *        Recognized options are documented on {@link JavaCore#getDefaultOptions()}.
 *        If set to <code>null</code>, then use the current settings from {@link JavaCore#getOptions()}.
 * @return the formatted source string
 */
public static String format(int kind, String source, int indentationLevel, String lineSeparator, Map<String, String> options) {
	TextEdit edit= format2(kind, source, indentationLevel, lineSeparator, options);
	if (edit == null) {
		return source;
	} else {
		Document document= new Document(source);
		try {
			edit.apply(document, TextEdit.NONE);
		} catch (BadLocationException e) {
			JavaPlugin.log(e); // bug in the formatter
			Assert.isTrue(false, "Formatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$
		}
		return document.get();
	}
}