Example usage for org.eclipse.jdt.internal.formatter DefaultCodeFormatter format

List of usage examples for org.eclipse.jdt.internal.formatter DefaultCodeFormatter format

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.formatter DefaultCodeFormatter format.

Prototype

@Override
public TextEdit format(int kind, String source, int offset, int length, int indentationLevel,
        String lineSeparator) 

Source Link

Usage

From source file:com.google.googlejavaformat.java.EclipseJavadocFormatter.java

License:Apache License

private static String formatJavadocInternal(String input, int indent, JavaFormatterOptions options) {

    ImmutableMap.Builder<String, String> optionBuilder = ImmutableMap.<String, String>builder();
    optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT, "true");
    optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE);
    optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE,
            Integer.toString(options.indentationMultiplier()));
    optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH,
            Integer.toString(options.maxLineLength() - indent));
    optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT,
            Integer.toString(options.maxLineLength()));
    optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_INDENT_PARAMETER_DESCRIPTION,
            DefaultCodeFormatterConstants.FALSE);
    optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_INSERT_NEW_LINE_FOR_PARAMETER,
            JavaCore.DO_NOT_INSERT);// w w w  .  java  2 s.c  o  m
    optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_JAVADOC_COMMENT,
            DefaultCodeFormatterConstants.FALSE);
    optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_JOIN_LINES_IN_COMMENTS,
            DefaultCodeFormatterConstants.TRUE);
    optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_JOIN_WRAPPED_LINES,
            DefaultCodeFormatterConstants.TRUE);
    // Disable indenting root tags for now since it indents more than 4 spaces
    optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_INDENT_ROOT_TAGS,
            DefaultCodeFormatterConstants.FALSE);
    optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_SOURCE,
            DefaultCodeFormatterConstants.FALSE);
    optionBuilder.put(JavaCore.COMPILER_COMPLIANCE, "1.8");
    optionBuilder.put(JavaCore.COMPILER_SOURCE, "1.8");
    optionBuilder.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, "1.8");
    DefaultCodeFormatter codeFormatter = new DefaultCodeFormatter(
            new DefaultCodeFormatterOptions(optionBuilder.build()));

    TextEdit edit = codeFormatter.format(CodeFormatter.K_JAVA_DOC, input, /*offset*/ 0, input.length(),
            // eclipse doesn't indent comments reliably, so always request no indent and fix it
            // up later in JavaCommentsHelper
            /*indent*/ 0, /*lineSeparator*/ null);
    if (edit == null) {
        throw new RuntimeException("error formatting javadoc");
    }
    Document document = new Document(input);
    try {
        edit.apply(document);
    } catch (BadLocationException e) {
        throw new RuntimeException("error formatting javadoc", e);
    }
    return document.get();
}

From source file:org.eclim.plugin.jdt.command.format.FormatCommand.java

License:Open Source License

/**
 * {@inheritDoc}//  www .  java2s .c  o m
 * @see org.eclim.command.Command#execute(CommandLine)
 */
public String execute(CommandLine commandLine) throws Exception {
    String project = commandLine.getValue(Options.PROJECT_OPTION);
    String file = commandLine.getValue(Options.FILE_OPTION);
    int bByteOffset = commandLine.getIntValue(Options.BOFFSET_OPTION);
    int eByteOffset = commandLine.getIntValue(Options.EOFFSET_OPTION);
    ICompilationUnit src = JavaUtils.getCompilationUnit(project, file);

    IJavaProject myProject = JavaUtils.getJavaProject(project);
    DefaultCodeFormatter formatter = new DefaultCodeFormatter(myProject.getOptions(false));

    int kind = CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS;

    String source = src.getBuffer().getContents();
    String vimEncoding = "UTF-8";
    byte[] byteSource = source.getBytes(vimEncoding);
    ByteArrayOutputStream outStream = null;

    outStream = new ByteArrayOutputStream();
    outStream.write(byteSource, 0, bByteOffset);
    String sourcePrefix = outStream.toString(vimEncoding);

    outStream = new ByteArrayOutputStream();
    outStream.write(byteSource, bByteOffset, eByteOffset - bByteOffset);
    String sourceRoot = outStream.toString(vimEncoding);

    int bCharOffset = sourcePrefix.length();
    int eCharOffset = bCharOffset + sourceRoot.length();
    int charLength = eCharOffset - bCharOffset;

    String lineDelimiter = StubUtility.getLineDelimiterUsed(src);
    TextEdit edits = formatter.format(kind, source, bCharOffset, charLength, 0, lineDelimiter);
    if (edits == null) {
        return "no edits returned on attempt to format the source.";
    }
    Document document = new Document(src.getBuffer().getContents());
    edits.apply(document);
    src.getBuffer().setContents(document.get());
    src.save(null, false);

    return StringUtils.EMPTY;
}

From source file:org.eclim.plugin.jdt.util.JavaUtils.java

License:Open Source License

/**
 * Format a region in the supplied source file.
 *
 * @param src The ICompilationUnit.//from   ww  w .  j ava  2s  .c  o m
 * @param kind The kind of code snippet to format.
 * @param offset The starting offset of the region to format.
 * @param length The length of the region to format.
 */
public static void format(ICompilationUnit src, int kind, int offset, int length) throws Exception {
    IBuffer buffer = src.getBuffer();
    String contents = buffer.getContents();
    String delimiter = StubUtility.getLineDelimiterUsed(src);
    DefaultCodeFormatter formatter = new DefaultCodeFormatter(src.getJavaProject().getOptions(true));

    // when the eclipse indent settings differ from vim (tabs vs spaces) then
    // the inserted method's indent may be a bit off. this is a workaround to
    // force reformatting of the code from the start of the line to the start of
    // the next set of code following the new method. Doesn't quite fix indent
    // formatting of methods in nested classes.
    while (offset > 0 && !IndentManipulation.isLineDelimiterChar(buffer.getChar(offset - 1))) {
        offset--;
        length++;
    }
    while ((offset + length) < contents.length()
            && IndentManipulation.isLineDelimiterChar(buffer.getChar(offset + length))) {
        length++;
    }

    TextEdit edits = formatter.format(kind, contents, offset, length, 0, delimiter);
    if (edits != null) {
        int oldLength = contents.length();
        Document document = new Document(contents);
        edits.apply(document);

        String formatted = document.get();

        // jdt formatter can introduce trailing whitespace (javadoc comments), so
        // we'll remove all trailing whitespace from the formatted section (unless
        // the user has configured eclim not to do so).
        length += formatted.length() - oldLength;
        if (offset < (offset + length)) {
            String stripTrailingWhitespace = Preferences.getInstance().getValue(
                    src.getJavaProject().getProject(), "org.eclim.java.format.strip_trialing_whitespace");
            if ("true".equals(stripTrailingWhitespace)) {
                String pre = formatted.substring(0, offset);
                StringBuffer section = new StringBuffer(formatted.substring(offset, offset + length));
                StringBuffer post = new StringBuffer(formatted.substring(offset + length));
                // account for section not ending at a line delimiter
                while (!section.toString().endsWith(delimiter) && post.length() > 0) {
                    section.append(post.charAt(0));
                    post.deleteCharAt(0);
                }

                Matcher matcher = TRAILING_WHITESPACE.matcher(section);
                String stripped = matcher.replaceAll(StringUtils.EMPTY);

                src.getBuffer().setContents(pre + stripped + post);
            } else {
                src.getBuffer().setContents(formatted);
            }
        } else {
            src.getBuffer().setContents(formatted);
        }

        if (src.isWorkingCopy()) {
            src.commitWorkingCopy(true, null);
        }
        src.save(null, false);
    }
}