Example usage for org.eclipse.jdt.core ToolFactory createCodeFormatter

List of usage examples for org.eclipse.jdt.core ToolFactory createCodeFormatter

Introduction

In this page you can find the example usage for org.eclipse.jdt.core ToolFactory createCodeFormatter.

Prototype

public static CodeFormatter createCodeFormatter(Map options, int mode) 

Source Link

Document

Creates an instance of a code formatter.

Usage

From source file:com.diffplug.gradle.spotless.java.eclipse.EclipseFormatterStepImpl.java

License:Apache License

public EclipseFormatterStepImpl(Properties settings) {
    this.codeFormatter = ToolFactory.createCodeFormatter(settings, ToolFactory.M_FORMAT_EXISTING);
}

From source file:com.diffplug.spotless.extra.eclipse.java.EclipseJdtFormatterStepImpl.java

License:Apache License

public EclipseJdtFormatterStepImpl(Properties settings) throws Exception {
    SpotlessEclipseFramework.setup(plugins -> {
        plugins.applyDefault();/*  w  ww .j  a  va 2  s .  c o m*/
        plugins.add(new JavaCore());
    });
    this.codeFormatter = ToolFactory.createCodeFormatter(settings, ToolFactory.M_FORMAT_EXISTING);
}

From source file:com.salesforce.ide.ui.editors.formatter.ApexCodeFormatterUtil.java

License:Open Source License

@SuppressWarnings("rawtypes")
public static TextEdit reformat(int kind, String source, int offset, int length, int indentationLevel,
        String lineSeparator, Map options) {
    logger.info("JEROME ApexCodeFormatterUtil.reformat");
    if (offset < 0 || length < 0 || offset + length > source.length()) {
        throw new IllegalArgumentException("offset or length outside of string. offset: " + offset //$NON-NLS-1$
                + ", length: " + length + ", string size: " + source.length()); //$NON-NLS-1$//$NON-NLS-2$
    }/*w w w  .  j  a  v  a  2 s  .  co  m*/
    return ToolFactory.createCodeFormatter(options, ToolFactory.M_FORMAT_EXISTING).format(kind, source, offset,
            length, indentationLevel, lineSeparator);
}

From source file:com.worldline.awltech.i18ntools.wizard.core.modules.ResourceBundleWrapper.java

License:Open Source License

/**
 * Loads the currently selected compilation unit.
 *//*  w w  w .  j a  v  a 2  s .  co m*/
private void loadCompilationUnit() {
    final IProject project = this.javaProject.getProject();
    final IResource sourceFolderResource = project
            .getFolder(new Path(this.configuration.getJavaSourceFolder()));
    final IPackageFragmentRoot ipfr = this.javaProject.getPackageFragmentRoot(sourceFolderResource);

    IPackageFragment ipf = ipfr.getPackageFragment(this.packageName);
    if (!ipf.exists()) {
        try {
            ipf = ipfr.createPackageFragment(this.packageName, false, new NullProgressMonitor());
        } catch (final JavaModelException e) {
            Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
                    RefactoringWizardMessages.ERROR_CREATE_PACKAGE.value(), e));
        }
    }

    final String javaUnitName = this.resourceBundleName.concat(".java");
    this.enumJavaCompilationUnit = ipf.getCompilationUnit(javaUnitName);
    if (!this.enumJavaCompilationUnit.exists()) {
        final String contents = this.createJavaUnitContents();

        // Format the source code before trying to set it to the compilation unit.
        CodeFormatter formatter = ToolFactory.createCodeFormatter(this.javaProject.getOptions(true),
                ToolFactory.M_FORMAT_EXISTING);
        IDocument document = new Document(contents);

        TextEdit textEdit = formatter.format(
                CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, contents, 0,
                contents.length(), 0, null);
        try {
            textEdit.apply(document);
        } catch (MalformedTreeException e1) {
            Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
                    RefactoringWizardMessages.ERROR_REFACTOR_TEMPLATE.value(), e1));
        } catch (BadLocationException e1) {
            Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
                    RefactoringWizardMessages.ERROR_REFACTOR_TEMPLATE.value(), e1));
        }
        try {
            // Set the source into the compilation unit.
            this.enumJavaCompilationUnit = ipf.createCompilationUnit(javaUnitName, document.get(), false,
                    new NullProgressMonitor());
        } catch (final JavaModelException e) {
            Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
                    RefactoringWizardMessages.ERROR_CREATE_CU.value(), e));
        }
    }

    final ASTParser enumSourceParser = ASTParser.newParser(AST.JLS4);
    enumSourceParser.setProject(this.javaProject);
    enumSourceParser.setBindingsRecovery(true);
    enumSourceParser.setResolveBindings(true);
    enumSourceParser.setKind(ASTParser.K_COMPILATION_UNIT);
    enumSourceParser.setSource(this.enumJavaCompilationUnit);

    this.enumDomCompilationUnit = (CompilationUnit) enumSourceParser.createAST(new NullProgressMonitor());
    this.enumDomCompilationUnit.recordModifications();
}

From source file:de.ovgu.cide.importjak.CIDEAnnotationParser.java

License:Open Source License

private String prettyPrint(String content) {
    CodeFormatter formatter = ToolFactory.createCodeFormatter(JavaCore.getOptions(),
            ToolFactory.M_FORMAT_EXISTING);

    TextEdit edit = formatter.format(CodeFormatter.K_COMPILATION_UNIT, content, 0, content.length(), 0, null);
    IDocument document = new Document(content);
    try {/* w  ww.ja va  2s . com*/
        if (edit != null)
            edit.apply(document);
    } catch (MalformedTreeException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (BadLocationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return document.get();
}

From source file:net.atos.optimus.common.tools.jdt.XACodeFormatter.java

License:Open Source License

/**
 * Format a String . Use the default code formatter
 *
 * @param sourceToFormat/* w  ww . ja  v a  2  s . c o m*/
 *            String to format
 *
 */
public static String format(String inputSource, IJavaProject project) {

    Map<?, ?> options = project != null ? project.getOptions(true) : JavaCore.getOptions();

    String sourceToFormat = preformat(inputSource);

    CodeFormatter formatter = ToolFactory.createCodeFormatter(options, ToolFactory.M_FORMAT_EXISTING);
    IDocument document = new Document(sourceToFormat);

    TextEdit textEdit = formatter.format(CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS,
            sourceToFormat, 0, sourceToFormat.length(), 0, null);

    if (textEdit != null) {
        try {
            textEdit.apply(document);
            String destination = document.get();
            return destination;
        } catch (Exception e) {
            Activator.getDefault()
                    .logError("The compilation unit could not be" + " read because of thrown Exception.", e);
            // In this case, return initial content
            return sourceToFormat;
        }
    } else {
        // In this case, return initial content
        return sourceToFormat;
    }
}

From source file:org.eclipse.jet.internal.taglib.java.JavaFormatTag.java

License:Open Source License

private String invokeJavaFormatterOn(String bodyContent, Map options, int snippetKind, JET2Context context)
        throws MalformedTreeException, BadLocationException {
    CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(options, ToolFactory.M_FORMAT_EXISTING);

    TextEdit textEdit = codeFormatter.format(snippetKind, bodyContent, /* the whole body of the tag */
            0 /*from beginning */, bodyContent.length() /* till the end */, 0 /* initial indentation */,
            null /* use platform default */);

    if (textEdit == null) {
        context.logError(Messages.JavaFormatTag_CouldNotFormat);
        return bodyContent;
    }//  w  w  w.  j a v  a 2 s  .  c o m

    IDocument document = new Document(bodyContent);
    textEdit.apply(document);

    String result = document.get();
    return result;
}

From source file:org.nabucco.framework.mda.model.java.file.JavaCodeFormatter.java

License:Open Source License

/**
 * Formats code of a {@link CompilationUnitDeclaration} appropriate to the default eclipse code
 * formatter options./*from www.  j  a v  a 2  s .  c  o m*/
 * 
 * @see DefaultCodeFormatterOptions
 * 
 * @param unit
 *            the compilation unit to format.
 * @param configFile
 *            the formatter configuration file.
 * 
 * @return the formatter code string
 * 
 * @throws JavaModelException
 *             if the code formatting was not successful
 */
public String formatCode(CompilationUnitDeclaration unit, String configFile) throws JavaModelException {

    String sourceCode = JavaAstElementFactory.getInstance().getJavaAstCommon().getSourceCode(unit).toString();

    String typeName = new String(
            JavaAstElementFactory.getInstance().getJavaAstUnit().getPublicJavaClass(unit).name);

    CodeFormatter formatter;

    if (configFile != null) {
        formatter = ToolFactory.createCodeFormatter(this.readConfig(configFile), ToolFactory.M_FORMAT_EXISTING);
    } else {
        formatter = this.createDefaultCodeFormatter();
    }

    TextEdit edit = formatter.format(CodeFormatter.K_COMPILATION_UNIT, sourceCode, OFFSET, sourceCode.length(),
            INDENTATION, LINE_SEPARATOR);

    if (edit == null) {
        logger.warning("Cannot format Java File '", typeName, ".java'.");
        return sourceCode;
    }

    try {
        IDocument document = new SimpleDocument(sourceCode);
        edit.apply(document);

        return document.get();

    } catch (MalformedTreeException e) {
        throw new JavaModelException("Error formatting [" + typeName + "].", e);
    } catch (BadLocationException e) {
        throw new JavaModelException("Error formatting [" + typeName + "].", e);
    }

}