Java Code Examples for org.eclipse.text.edits.TextEdit#apply()

The following examples show how to use org.eclipse.text.edits.TextEdit#apply() . 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: JavascriptFormatter.java    From formatter-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public String doFormat(String code, LineEnding ending) throws IOException, BadLocationException {
    TextEdit te = this.formatter.format(CodeFormatter.K_JAVASCRIPT_UNIT, code, 0, code.length(), 0,
            ending.getChars());
    if (te == null) {
        this.log.debug(
                "Code cannot be formatted. Possible cause " + "is unmatched source/target/compliance version.");
        return null;
    }

    IDocument doc = new Document(code);
    te.apply(doc);
    String formattedCode = doc.get();

    if (code.equals(formattedCode)) {
        return null;
    }
    return formattedCode;
}
 
Example 2
Source File: FixedContentFormatter.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * This method makes sure that no changes are applied (no dirty state), if there are no changes. This fixes bug
 * GHOLD-272
 */
@Override
public void format(IDocument document, IRegion region) {
	IXtextDocument doc = (IXtextDocument) document;
	TextEdit e = doc.priorityReadOnly(new FormattingUnitOfWork(doc, region));

	if (e == null)
		return;
	if (e instanceof ReplaceEdit) {
		ReplaceEdit r = (ReplaceEdit) e;
		if ((r.getOffset() == 0) && (r.getLength() == 0) && (r.getText().isEmpty())) {
			return;
		}
	}
	try {
		e.apply(document);
	} catch (BadLocationException ex) {
		throw new RuntimeException(ex);
	}

}
 
Example 3
Source File: JavaCodeFormatter.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
public String apply(String contents) {
    TextEdit edit = codeFormatter.format(
            CodeFormatter.K_COMPILATION_UNIT
            | CodeFormatter.F_INCLUDE_COMMENTS, contents, 0,
            contents.length(), 0, System.lineSeparator());

    if (edit == null) {
        // TODO log a fatal or warning here. Throwing an exception is causing the actual freemarker error to be lost
        return contents;
    }

    IDocument document = new Document(contents);

    try {
        edit.apply(document);
    } catch (Exception e) {
        throw new RuntimeException(
                "Failed to format the generated source code.", e);
    }

    return document.get();
}
 
Example 4
Source File: JavaCodeFormatter.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
public String apply(String contents) {
    TextEdit edit = codeFormatter.format(
            CodeFormatter.K_COMPILATION_UNIT
            | CodeFormatter.F_INCLUDE_COMMENTS, contents, 0,
            contents.length(), 0, Constant.LF);

    if (edit == null) {
        // TODO log a fatal or warning here. Throwing an exception is causing the actual freemarker error to be lost
        return contents;
    }

    IDocument document = new Document(contents);

    try {
        edit.apply(document);
    } catch (Exception e) {
        throw new RuntimeException(
                "Failed to format the generated source code.", e);
    }

    return document.get();
}
 
Example 5
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 6
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 7
Source File: ContentFormatterFactory.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void format(IDocument document, IRegion region) {
	IXtextDocument doc = xtextDocumentUtil.getXtextDocument(document);
	ReplaceRegion r = doc.priorityReadOnly(new FormattingUnitOfWork(region));
	try {
		if (r != null) {
			TextEdit edit = createTextEdit(doc, r);
			if (edit != null) {
				edit.apply(doc);
			}
			
		}
	} catch (BadLocationException e) {
		throw new RuntimeException(e);
	}
}
 
Example 8
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 9
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 10
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 11
Source File: BugResolution.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private IRegion rewriteCompilationUnit(ASTRewrite rewrite, IDocument doc, ICompilationUnit originalUnit)
        throws JavaModelException, BadLocationException {
    TextEdit edits = rewrite.rewriteAST(doc, originalUnit.getJavaProject().getOptions(true));
    edits.apply(doc);

    originalUnit.getBuffer().setContents(doc.get());
    originalUnit.commitWorkingCopy(false, monitor);
    return edits.getRegion();
}
 
Example 12
Source File: DelegateCreator.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Performs the actual rewriting and adds an edit to the ASTRewrite set with
 * {@link #setSourceRewrite(CompilationUnitRewrite)}.
 *
 * @throws JavaModelException
 */
public void createEdit() throws JavaModelException {
	try {
		IDocument document= new Document(fDelegateRewrite.getCu().getBuffer().getContents());
		TextEdit edit= fDelegateRewrite.getASTRewrite().rewriteAST(document, fDelegateRewrite.getCu().getJavaProject().getOptions(true));
		edit.apply(document, TextEdit.UPDATE_REGIONS);

		int tabWidth = CodeFormatterUtil.getTabWidth(fOriginalRewrite.getCu().getJavaProject());
		int identWidth = CodeFormatterUtil.getIndentWidth(fOriginalRewrite.getCu().getJavaProject());

		String newSource= Strings.trimIndentation(document.get(fTrackedPosition.getStartPosition(), fTrackedPosition.getLength()),
				tabWidth, identWidth, false);

		ASTNode placeholder= fOriginalRewrite.getASTRewrite().createStringPlaceholder(newSource, fDeclaration.getNodeType());

		CategorizedTextEditGroup groupDescription= fOriginalRewrite.createCategorizedGroupDescription(getTextEditGroupLabel(), CATEGORY_DELEGATE);
		ListRewrite bodyDeclarationsListRewrite= fOriginalRewrite.getASTRewrite().getListRewrite(fDeclaration.getParent(), getTypeBodyDeclarationsProperty());
		if (fCopy) {
			if (fInsertBefore) {
				bodyDeclarationsListRewrite.insertBefore(placeholder, fDeclaration, groupDescription);
			} else {
				bodyDeclarationsListRewrite.insertAfter(placeholder, fDeclaration, groupDescription);
			}
		} else {
			bodyDeclarationsListRewrite.replace(fDeclaration, placeholder, groupDescription);
		}

	} catch (BadLocationException e) {
		//JavaPlugin.log(e);
	}
}
 
Example 13
Source File: CopyrightManager.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Rewrites compilation unit with new source
 *
 * @param unit
 *            compilation unit to be rewritten
 * @param source
 *            new source of compilation unit
 */
private void rewriteCompilationUnit(final ICompilationUnit unit, final String source) {
	try {
		final TextEdit edits = rewriter.rewriteAST();
		final Document document = new Document(source);
		edits.apply(document);
		unit.getBuffer().setContents(document.get());
		change.setEdit(edits);
	} catch (final JavaModelException | MalformedTreeException | BadLocationException e) {
		ConsoleUtils.printError(e.getMessage());
	}
}
 
Example 14
Source File: CompilationUnitSourceSetter.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
public void commitCodeChange(ICompilationUnit iCompilationUnit, ASTRewrite rewriter) {
    try {
        Document document = new Document(iCompilationUnit.getSource());
        TextEdit edits = rewriter.rewriteAST(document, null);
        edits.apply(document);
        iCompilationUnit.getBuffer().setContents(document.get());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 15
Source File: CodeUtils.java    From minnal with Apache License 2.0 5 votes vote down vote up
public static String format(String code, Map<String, String> options) {
    DefaultCodeFormatterOptions cfOptions = DefaultCodeFormatterOptions.getJavaConventionsSettings();
    cfOptions.tab_char = DefaultCodeFormatterOptions.TAB;
    CodeFormatter cf = new DefaultCodeFormatter(cfOptions, options);
    TextEdit te = cf.format(CodeFormatter.K_UNKNOWN, code, 0, code.length(), 0, null);
    IDocument dc = new Document(code);

    try {
        te.apply(dc);
    } catch (Exception e) {
        throw new MinnalGeneratorException("Failed while formatting the code", e);
    }
    return dc.get();
}
 
Example 16
Source File: ImportOrganizeTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void test1() throws Exception {
	requireJUnitSources();
	ICompilationUnit cu= (ICompilationUnit) javaProject.findElement(new Path("junit/runner/BaseTestRunner.java"));
	assertNotNull("BaseTestRunner.java", cu);
	IPackageFragmentRoot root= (IPackageFragmentRoot)cu.getParent().getParent();
	IPackageFragment pack= root.createPackageFragment("mytest", true, null);
	ICompilationUnit colidingCU= pack.getCompilationUnit("TestListener.java");
	colidingCU.createType("public abstract class TestListener {\n}\n", null, true, null);
	String[] order= new String[0];
	IChooseImportQuery query= createQuery("BaseTestRunner", new String[] { "junit.framework.TestListener" }, new int[] { 2 });
	OrganizeImportsOperation op = createOperation(cu, order, false, true, true, query);
	TextEdit edit = op.createTextEdit(new NullProgressMonitor());
	IDocument document = new Document(cu.getSource());
	edit.apply(document);
	try {
		cu.becomeWorkingCopy(new NullProgressMonitor());
		cu.getBuffer().setContents(document.get());
		cu.reconcile(ICompilationUnit.NO_AST, true, null, new NullProgressMonitor());
		//@formatter:off
		assertImports(cu, new String[] {
			"java.io.BufferedReader",
			"java.io.File",
			"java.io.FileInputStream",
			"java.io.FileOutputStream",
			"java.io.IOException",
			"java.io.InputStream",
			"java.io.PrintWriter",
			"java.io.StringReader",
			"java.io.StringWriter",
			"java.lang.reflect.InvocationTargetException",
			"java.lang.reflect.Method",
			"java.lang.reflect.Modifier",
			"java.text.NumberFormat",
			"java.util.Properties",
			"junit.framework.AssertionFailedError",
			"junit.framework.Test",
			"junit.framework.TestListener",
			"junit.framework.TestSuite"
		});
		//@formatter:on
	} finally {
		cu.discardWorkingCopy();
	}
}
 
Example 17
Source File: ImportOrganizeTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void test1WithOrder() throws Exception {
	requireJUnitSources();
	ICompilationUnit cu = (ICompilationUnit) javaProject.findElement(new Path("junit/runner/BaseTestRunner.java"));
	assertNotNull("BaseTestRunner.java is missing", cu);
	IPackageFragmentRoot root= (IPackageFragmentRoot)cu.getParent().getParent();
	IPackageFragment pack= root.createPackageFragment("mytest", true, null);
	ICompilationUnit colidingCU= pack.getCompilationUnit("TestListener.java");
	colidingCU.createType("public abstract class TestListener {\n}\n", null, true, null);
	String[] order= new String[] { "junit", "java.text", "java.io", "java" };
	IChooseImportQuery query= createQuery("BaseTestRunner", new String[] { "junit.framework.TestListener" }, new int[] { 2 });
	OrganizeImportsOperation op = createOperation(cu, order, false, true, true, query);
	TextEdit edit = op.createTextEdit(new NullProgressMonitor());
	IDocument document = new Document(cu.getSource());
	edit.apply(document);
	try {
		cu.becomeWorkingCopy(new NullProgressMonitor());
		cu.getBuffer().setContents(document.get());
		cu.reconcile(ICompilationUnit.NO_AST, true, null, new NullProgressMonitor());
		//@formatter:off
		assertImports(cu, new String[] {
			"junit.framework.AssertionFailedError",
			"junit.framework.Test",
			"junit.framework.TestListener",
			"junit.framework.TestSuite",
			"java.text.NumberFormat",
			"java.io.BufferedReader",
			"java.io.File",
			"java.io.FileInputStream",
			"java.io.FileOutputStream",
			"java.io.IOException",
			"java.io.InputStream",
			"java.io.PrintWriter",
			"java.io.StringReader",
			"java.io.StringWriter",
			"java.lang.reflect.InvocationTargetException",
			"java.lang.reflect.Method",
			"java.lang.reflect.Modifier",
			"java.util.Properties"
		});
		//@formatter:on
	} finally {
		cu.discardWorkingCopy();
	}
}
 
Example 18
Source File: FormatterTests.java    From spring-javaformat with Apache License 2.0 4 votes vote down vote up
private String format(String sourceContent) throws Exception {
	IDocument document = new Document(sourceContent);
	TextEdit textEdit = new Formatter().format(sourceContent);
	textEdit.apply(document);
	return document.get();
}
 
Example 19
Source File: ImportOrganizeTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testStaticImports2() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("pack1", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package pack1;\n");
	buf.append("\n");
	buf.append("import static java.io.File.*;\n");
	buf.append("\n");
	buf.append("public class C {\n");
	buf.append("    public String foo() {\n");
	buf.append("        return pathSeparator + separator + File.separator;\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
	String[] order= new String[] { "#java.io.File", "java", "pack" };
	IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
	OrganizeImportsOperation op = createOperation(cu, order, false, true, true, query);
	TextEdit edit = op.createTextEdit(new NullProgressMonitor());
	IDocument document = new Document(cu.getSource());
	edit.apply(document);
	try {
		cu.becomeWorkingCopy(new NullProgressMonitor());
		cu.getBuffer().setContents(document.get());
		cu.reconcile(ICompilationUnit.NO_AST, true, null, new NullProgressMonitor());
		buf = new StringBuilder();
		buf.append("package pack1;\n");
		buf.append("\n");
		buf.append("import static java.io.File.pathSeparator;\n");
		buf.append("import static java.io.File.separator;\n");
		buf.append("\n");
		buf.append("import java.io.File;\n");
		buf.append("\n");
		buf.append("public class C {\n");
		buf.append("    public String foo() {\n");
		buf.append("        return pathSeparator + separator + File.separator;\n");
		buf.append("    }\n");
		buf.append("}\n");
		assertTrue(cu.getSource().equals(buf.toString()));
	} finally {
		cu.discardWorkingCopy();
	}
}
 
Example 20
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;
  }
}