Java 类org.eclipse.jdt.core.formatter.CodeFormatter 实例源码

项目:aws-sdk-java-v2    文件:JavaCodeFormatter.java   
public String apply(String contents) {
    final TextEdit edit = codeFormatter.format(
            CodeFormatter.K_COMPILATION_UNIT
            | CodeFormatter.F_INCLUDE_COMMENTS, contents, 0,
            contents.length(), 0, Constants.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();
}
项目:meghanada-server    文件:JavaFormatter.java   
public static String formatEclipseStyle(final Properties prop, final String content) {
  final CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(prop);
  final IDocument document = new Document(content);
  try {
    final TextEdit textEdit =
        codeFormatter.format(
            CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS,
            content,
            0,
            content.length(),
            0,
            null);
    if (textEdit != null) {
      textEdit.apply(document);
    } else {
      return content;
    }
  } catch (final BadLocationException e) {
    return content;
  }

  return ensureCorrectNewLines(document.get());
}
项目:eclipse.jdt.ls    文件:GetterSetterCompletionProposal.java   
/**
 * @param document
 * @param offset
 * @param importRewrite
 * @param completionSnippetsSupported
 * @return
 * @throws CoreException
 * @throws BadLocationException
 */
public String updateReplacementString(IDocument document, int offset, ImportRewrite importRewrite, boolean completionSnippetsSupported) throws CoreException, BadLocationException {
    int flags= Flags.AccPublic | (fField.getFlags() & Flags.AccStatic);

    String stub;
    if (fIsGetter) {
        String getterName= GetterSetterUtil.getGetterName(fField, null);
        stub = GetterSetterUtil.getGetterStub(fField, getterName, true, flags);
    } else {
        String setterName= GetterSetterUtil.getSetterName(fField, null);
        stub = GetterSetterUtil.getSetterStub(fField, setterName, true, flags);
    }

    // use the code formatter
    String lineDelim= TextUtilities.getDefaultLineDelimiter(document);
    String replacement = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, stub, 0, lineDelim, fField.getJavaProject());

    if (replacement.endsWith(lineDelim)) {
        replacement = replacement.substring(0, replacement.length() - lineDelim.length());
    }

    return replacement;
}
项目:JSFLibraryGenerator    文件:JavaFormatter.java   
private static String formatCode(String contents, Object codeFormatter) {
    if (codeFormatter instanceof CodeFormatter) {
        IDocument doc = new Document(contents);
        TextEdit edit = ((CodeFormatter) codeFormatter).format(CodeFormatter.K_COMPILATION_UNIT, doc.get(), 0,
                doc.get().length(), 0, null);
        if (edit != null) {
            try {
                edit.apply(doc);
                contents = doc.get();
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
    return contents;
}
项目:che    文件:JavaFormatter.java   
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);
}
项目:che    文件:JavaMethodCompletionProposal.java   
/**
 * Appends everything up to the method name including the opening parenthesis.
 *
 * <p>In case of {@link org.eclipse.jdt.core.CompletionProposal#METHOD_REF_WITH_CASTED_RECEIVER}
 * it add cast.
 *
 * @param buffer the string buffer
 * @since 3.4
 */
protected void appendMethodNameReplacement(StringBuffer buffer) {
  if (fProposal.getKind() == CompletionProposal.METHOD_REF_WITH_CASTED_RECEIVER) {
    String coreCompletion = String.valueOf(fProposal.getCompletion());
    String lineDelimiter = TextUtilities.getDefaultLineDelimiter(getTextViewer().getDocument());
    String replacement =
        CodeFormatterUtil.format(
            CodeFormatter.K_EXPRESSION,
            coreCompletion,
            0,
            lineDelimiter,
            fInvocationContext.getProject());
    buffer.append(replacement.substring(0, replacement.lastIndexOf('.') + 1));
  }

  if (fProposal.getKind() != CompletionProposal.CONSTRUCTOR_INVOCATION)
    buffer.append(fProposal.getName());

  FormatterPrefs prefs = getFormatterPrefs();
  if (prefs.beforeOpeningParen) buffer.append(SPACE);
  buffer.append(LPAREN);
}
项目:gwt-eclipse-plugin    文件:ProjectResources.java   
/**
 * 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;
}
项目:gwt-eclipse-plugin    文件:TypeCreator.java   
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;
}
项目:Eclipse-Postfix-Code-Completion    文件:JavaFormatter.java   
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);
}
项目:Eclipse-Postfix-Code-Completion    文件:CompletionProposalCollector.java   
/**
 * Creates the Java completion proposal for the JDT Core
 * {@link CompletionProposal#FIELD_REF_WITH_CASTED_RECEIVER} proposal.
 *
 * @param proposal the JDT Core proposal
 * @return the Java completion proposal
 * @since 3.4
 */
private IJavaCompletionProposal createFieldWithCastedReceiverProposal(CompletionProposal proposal) {
    String completion= String.valueOf(proposal.getCompletion());
    completion= CodeFormatterUtil.format(CodeFormatter.K_EXPRESSION, completion, 0, "\n", fJavaProject); //$NON-NLS-1$
    int start= proposal.getReplaceStart();
    int length= getLength(proposal);
    StyledString label= fLabelProvider.createStyledLabel(proposal);
    Image image= getImage(fLabelProvider.createFieldImageDescriptor(proposal));
    int relevance= computeRelevance(proposal);

    JavaCompletionProposal javaProposal= new JavaFieldWithCastedReceiverCompletionProposal(completion, start, length, image, label, relevance, getContext().isInJavadoc(), getInvocationContext(), proposal);
    if (fJavaProject != null)
        javaProposal.setProposalInfo(new FieldProposalInfo(fJavaProject, proposal));

    javaProposal.setTriggerCharacters(VAR_TRIGGER);

    return javaProposal;
}
项目:Eclipse-Postfix-Code-Completion    文件:JavaMethodCompletionProposal.java   
/**
 * Appends everything up to the method name including
 * the opening parenthesis.
 * <p>
 * In case of {@link CompletionProposal#METHOD_REF_WITH_CASTED_RECEIVER}
 * it add cast.
 * </p>
 *
 * @param buffer the string buffer
 * @since 3.4
 */
protected void appendMethodNameReplacement(StringBuffer buffer) {
    if (fProposal.getKind() == CompletionProposal.METHOD_REF_WITH_CASTED_RECEIVER) {
        String coreCompletion= String.valueOf(fProposal.getCompletion());
        String lineDelimiter= TextUtilities.getDefaultLineDelimiter(getTextViewer().getDocument());
        String replacement= CodeFormatterUtil.format(CodeFormatter.K_EXPRESSION, coreCompletion, 0, lineDelimiter, fInvocationContext.getProject());
        buffer.append(replacement.substring(0, replacement.lastIndexOf('.') + 1));
    }

    if (fProposal.getKind() != CompletionProposal.CONSTRUCTOR_INVOCATION)
        buffer.append(fProposal.getName());

    FormatterPrefs prefs= getFormatterPrefs();
    if (prefs.beforeOpeningParen)
        buffer.append(SPACE);
    buffer.append(LPAREN);
}
项目:Eclipse-Postfix-Code-Completion    文件:Scribe.java   
public void printNextToken(int[] expectedTokenTypes, boolean considerSpaceIfAny){
    printComment(CodeFormatter.K_UNKNOWN, NO_TRAILING_COMMENT);
    try {
        this.currentToken = this.scanner.getNextToken();
        if (Arrays.binarySearch(expectedTokenTypes, this.currentToken) < 0) {
            StringBuffer expectations = new StringBuffer(5);
            for (int i = 0; i < expectedTokenTypes.length; i++){
                if (i > 0) {
                    expectations.append(',');
                }
                expectations.append(expectedTokenTypes[i]);
            }
            throw new AbortFormatting("unexpected token type, expecting:["+expectations.toString()+"], actual:"+this.currentToken);//$NON-NLS-1$//$NON-NLS-2$
        }
        print(this.scanner.currentPosition - this.scanner.startPosition, considerSpaceIfAny);
    } catch (InvalidInputException e) {
        throw new AbortFormatting(e);
    }
}
项目:Eclipse-Postfix-Code-Completion    文件:CodeFormatterVisitor.java   
private void format(ImportReference importRef, boolean isLast) {
    this.scribe.printNextToken(TerminalTokens.TokenNameimport);
    if (!isLast) this.scribe.blank_lines_between_import_groups = this.preferences.blank_lines_between_import_groups;
    this.scribe.space();
    if (importRef.isStatic()) {
        this.scribe.printNextToken(TerminalTokens.TokenNamestatic);
        this.scribe.space();
    }
    if ((importRef.bits & ASTNode.OnDemand) != 0) {
        this.scribe.printQualifiedReference(importRef.sourceEnd, false/*do not expect parenthesis*/);
        this.scribe.printNextToken(TerminalTokens.TokenNameDOT);
        this.scribe.printNextToken(TerminalTokens.TokenNameMULTIPLY);
        this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
    } else {
        this.scribe.printQualifiedReference(importRef.sourceEnd, false/*do not expect parenthesis*/);
        this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
    }
    if (isLast) {
        this.scribe.blank_lines_between_import_groups = -1;
        this.scribe.printComment(CodeFormatter.K_UNKNOWN, Scribe.IMPORT_TRAILING_COMMENT);
    } else {
        this.scribe.printComment(CodeFormatter.K_UNKNOWN, Scribe.NO_TRAILING_COMMENT);
        this.scribe.blank_lines_between_import_groups = -1;
    }
    this.scribe.printNewLine();
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:ASTRewriteFormatter.java   
public String[] getPrefixAndSuffix(int indent, ASTNode node, RewriteEventStore events) {
    String nodeString= ASTRewriteFlattener.asString(node, events);
    int nodeStart= this.prefix.length();
    int nodeEnd= nodeStart + nodeString.length() - 1;

    String str= this.prefix + nodeString + this.suffix;

    Position pos1= new Position(this.start, nodeStart + 1 - this.start);
    Position pos2= new Position(nodeEnd, 2);

    TextEdit res= formatString(CodeFormatter.K_STATEMENTS, str, 0, str.length(), indent);
    if (res != null) {
        str= evaluateFormatterEdit(str, res, new Position[] { pos1, pos2 });
    }
    return new String[] {
        str.substring(pos1.offset + 1, pos1.offset + pos1.length - 1),
        str.substring(pos2.offset + 1, pos2.offset + pos2.length - 1)
    };
}
项目:Eclipse-Postfix-Code-Completion    文件:CodeFormatterVisitor.java   
/**
 * @see org.eclipse.jdt.internal.compiler.ASTVisitor#visit(org.eclipse.jdt.internal.compiler.ast.AssertStatement, org.eclipse.jdt.internal.compiler.lookup.BlockScope)
 */
public boolean visit(AssertStatement assertStatement, BlockScope scope) {

    this.scribe.printNextToken(TerminalTokens.TokenNameassert);
    this.scribe.space();
    assertStatement.assertExpression.traverse(this, scope);

    if (assertStatement.exceptionArgument != null) {
        this.scribe.printNextToken(TerminalTokens.TokenNameCOLON, this.preferences.insert_space_before_colon_in_assert);
        if (this.preferences.insert_space_after_colon_in_assert) {
            this.scribe.space();
        }
        assertStatement.exceptionArgument.traverse(this, scope);
    }
    this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
    this.scribe.printComment(CodeFormatter.K_UNKNOWN, Scribe.BASIC_TRAILING_COMMENT);
    return false;
}
项目:Eclipse-Postfix-Code-Completion    文件:CodeFormatterVisitor.java   
/**
 * @see org.eclipse.jdt.internal.compiler.ASTVisitor#visit(org.eclipse.jdt.internal.compiler.ast.LabeledStatement, org.eclipse.jdt.internal.compiler.lookup.BlockScope)
 */
public boolean visit(LabeledStatement labeledStatement, BlockScope scope) {

    this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier);
    this.scribe.printNextToken(TerminalTokens.TokenNameCOLON, this.preferences.insert_space_before_colon_in_labeled_statement);
    if (this.preferences.insert_space_after_colon_in_labeled_statement) {
        this.scribe.space();
    }
    if (this.preferences.insert_new_line_after_label) {
        this.scribe.printNewLine();
    }
    final Statement statement = labeledStatement.statement;
    statement.traverse(this, scope);
    if (statement instanceof Expression) {
        this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
        this.scribe.printComment(CodeFormatter.K_UNKNOWN, Scribe.BASIC_TRAILING_COMMENT);
    }
    return false;
}
项目:Eclipse-Postfix-Code-Completion    文件:CodeFormatterVisitor.java   
/**
 * @see org.eclipse.jdt.internal.compiler.ASTVisitor#visit(org.eclipse.jdt.internal.compiler.ast.ThrowStatement, org.eclipse.jdt.internal.compiler.lookup.BlockScope)
 */
public boolean visit(ThrowStatement throwStatement, BlockScope scope) {

    this.scribe.printNextToken(TerminalTokens.TokenNamethrow);
    Expression expression = throwStatement.exception;
    final int numberOfParens = (expression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
    if ((numberOfParens > 0 && this.preferences.insert_space_before_parenthesized_expression_in_throw)
            || numberOfParens == 0) {
        this.scribe.space();
    }
    expression.traverse(this, scope);
    /*
     * Print the semi-colon
     */
    this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
    this.scribe.printComment(CodeFormatter.K_UNKNOWN, Scribe.BASIC_TRAILING_COMMENT);
    return false;
}
项目:Eclipse-Postfix-Code-Completion    文件:ASTRewriteFormatter.java   
public String[] getPrefixAndSuffix(int indent, ASTNode node, RewriteEventStore events) {
    String nodeString= ASTRewriteFlattener.asString(node, events);
    int nodeStart= this.prefix.length();
    int nodeEnd= nodeStart + nodeString.length() - 1;

    String str= this.prefix + nodeString + this.suffix;

    Position pos1= new Position(this.start, nodeStart + 1 - this.start);
    Position pos2= new Position(nodeEnd, 2);

    TextEdit res= formatString(CodeFormatter.K_STATEMENTS, str, 0, str.length(), indent);
    if (res != null) {
        str= evaluateFormatterEdit(str, res, new Position[] { pos1, pos2 });
    }
    return new String[] {
        str.substring(pos1.offset + 1, pos1.offset + pos1.length - 1),
        str.substring(pos2.offset + 1, pos2.offset + pos2.length - 1)
    };
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:JavaFormatter.java   
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);
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:CompletionProposalCollector.java   
/**
 * Creates the Java completion proposal for the JDT Core
 * {@link CompletionProposal#FIELD_REF_WITH_CASTED_RECEIVER} proposal.
 *
 * @param proposal the JDT Core proposal
 * @return the Java completion proposal
 * @since 3.4
 */
private IJavaCompletionProposal createFieldWithCastedReceiverProposal(CompletionProposal proposal) {
    String completion= String.valueOf(proposal.getCompletion());
    completion= CodeFormatterUtil.format(CodeFormatter.K_EXPRESSION, completion, 0, "\n", fJavaProject); //$NON-NLS-1$
    int start= proposal.getReplaceStart();
    int length= getLength(proposal);
    StyledString label= fLabelProvider.createStyledLabel(proposal);
    Image image= getImage(fLabelProvider.createFieldImageDescriptor(proposal));
    int relevance= computeRelevance(proposal);

    JavaCompletionProposal javaProposal= new JavaFieldWithCastedReceiverCompletionProposal(completion, start, length, image, label, relevance, getContext().isInJavadoc(), getInvocationContext(), proposal);
    if (fJavaProject != null)
        javaProposal.setProposalInfo(new FieldProposalInfo(fJavaProject, proposal));

    javaProposal.setTriggerCharacters(VAR_TRIGGER);

    return javaProposal;
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:JavaMethodCompletionProposal.java   
/**
 * Appends everything up to the method name including
 * the opening parenthesis.
 * <p>
 * In case of {@link CompletionProposal#METHOD_REF_WITH_CASTED_RECEIVER}
 * it add cast.
 * </p>
 *
 * @param buffer the string buffer
 * @since 3.4
 */
protected void appendMethodNameReplacement(StringBuffer buffer) {
    if (fProposal.getKind() == CompletionProposal.METHOD_REF_WITH_CASTED_RECEIVER) {
        String coreCompletion= String.valueOf(fProposal.getCompletion());
        String lineDelimiter= TextUtilities.getDefaultLineDelimiter(getTextViewer().getDocument());
        String replacement= CodeFormatterUtil.format(CodeFormatter.K_EXPRESSION, coreCompletion, 0, lineDelimiter, fInvocationContext.getProject());
        buffer.append(replacement.substring(0, replacement.lastIndexOf('.') + 1));
    }

    if (fProposal.getKind() != CompletionProposal.CONSTRUCTOR_INVOCATION)
        buffer.append(fProposal.getName());

    FormatterPrefs prefs= getFormatterPrefs();
    if (prefs.beforeOpeningParen)
        buffer.append(SPACE);
    buffer.append(LPAREN);
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:Scribe.java   
public void printNextToken(int[] expectedTokenTypes, boolean considerSpaceIfAny){
    printComment(CodeFormatter.K_UNKNOWN, NO_TRAILING_COMMENT);
    try {
        this.currentToken = this.scanner.getNextToken();
        if (Arrays.binarySearch(expectedTokenTypes, this.currentToken) < 0) {
            StringBuffer expectations = new StringBuffer(5);
            for (int i = 0; i < expectedTokenTypes.length; i++){
                if (i > 0) {
                    expectations.append(',');
                }
                expectations.append(expectedTokenTypes[i]);
            }
            throw new AbortFormatting("unexpected token type, expecting:["+expectations.toString()+"], actual:"+this.currentToken);//$NON-NLS-1$//$NON-NLS-2$
        }
        print(this.scanner.currentPosition - this.scanner.startPosition, considerSpaceIfAny);
    } catch (InvalidInputException e) {
        throw new AbortFormatting(e);
    }
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:CodeFormatterVisitor.java   
private void format(ImportReference importRef, boolean isLast) {
    this.scribe.printNextToken(TerminalTokens.TokenNameimport);
    if (!isLast) this.scribe.blank_lines_between_import_groups = this.preferences.blank_lines_between_import_groups;
    this.scribe.space();
    if (importRef.isStatic()) {
        this.scribe.printNextToken(TerminalTokens.TokenNamestatic);
        this.scribe.space();
    }
    if ((importRef.bits & ASTNode.OnDemand) != 0) {
        this.scribe.printQualifiedReference(importRef.sourceEnd, false/*do not expect parenthesis*/);
        this.scribe.printNextToken(TerminalTokens.TokenNameDOT);
        this.scribe.printNextToken(TerminalTokens.TokenNameMULTIPLY);
        this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
    } else {
        this.scribe.printQualifiedReference(importRef.sourceEnd, false/*do not expect parenthesis*/);
        this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
    }
    if (isLast) {
        this.scribe.blank_lines_between_import_groups = -1;
        this.scribe.printComment(CodeFormatter.K_UNKNOWN, Scribe.IMPORT_TRAILING_COMMENT);
    } else {
        this.scribe.printComment(CodeFormatter.K_UNKNOWN, Scribe.NO_TRAILING_COMMENT);
        this.scribe.blank_lines_between_import_groups = -1;
    }
    this.scribe.printNewLine();
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:CodeFormatterVisitor.java   
/**
 * @see org.eclipse.jdt.internal.compiler.ASTVisitor#visit(org.eclipse.jdt.internal.compiler.ast.AssertStatement, org.eclipse.jdt.internal.compiler.lookup.BlockScope)
 */
public boolean visit(AssertStatement assertStatement, BlockScope scope) {

    this.scribe.printNextToken(TerminalTokens.TokenNameassert);
    this.scribe.space();
    assertStatement.assertExpression.traverse(this, scope);

    if (assertStatement.exceptionArgument != null) {
        this.scribe.printNextToken(TerminalTokens.TokenNameCOLON, this.preferences.insert_space_before_colon_in_assert);
        if (this.preferences.insert_space_after_colon_in_assert) {
            this.scribe.space();
        }
        assertStatement.exceptionArgument.traverse(this, scope);
    }
    this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
    this.scribe.printComment(CodeFormatter.K_UNKNOWN, Scribe.BASIC_TRAILING_COMMENT);
    return false;
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:CodeFormatterVisitor.java   
/**
 * @see org.eclipse.jdt.internal.compiler.ASTVisitor#visit(org.eclipse.jdt.internal.compiler.ast.ThrowStatement, org.eclipse.jdt.internal.compiler.lookup.BlockScope)
 */
public boolean visit(ThrowStatement throwStatement, BlockScope scope) {

    this.scribe.printNextToken(TerminalTokens.TokenNamethrow);
    Expression expression = throwStatement.exception;
    final int numberOfParens = (expression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
    if ((numberOfParens > 0 && this.preferences.insert_space_before_parenthesized_expression_in_throw)
            || numberOfParens == 0) {
        this.scribe.space();
    }
    expression.traverse(this, scope);
    /*
     * Print the semi-colon
     */
    this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
    this.scribe.printComment(CodeFormatter.K_UNKNOWN, Scribe.BASIC_TRAILING_COMMENT);
    return false;
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:CodeFormatterVisitor.java   
/**
 * @see org.eclipse.jdt.internal.compiler.ASTVisitor#visit(org.eclipse.jdt.internal.compiler.ast.ReturnStatement, org.eclipse.jdt.internal.compiler.lookup.BlockScope)
 */
public boolean visit(ReturnStatement returnStatement, BlockScope scope) {

    this.scribe.printNextToken(TerminalTokens.TokenNamereturn);
    final Expression expression = returnStatement.expression;
    if (expression != null) {
        final int numberOfParens = (expression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
        if ((numberOfParens != 0 && this.preferences.insert_space_before_parenthesized_expression_in_return)
                || numberOfParens == 0) {
            this.scribe.space();
        }
        expression.traverse(this, scope);
    }
    /*
     * Print the semi-colon
     */
    this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
    this.scribe.printComment(CodeFormatter.K_UNKNOWN, Scribe.BASIC_TRAILING_COMMENT);
    return false;
}
项目:gw4e.project    文件:JDTManager.java   
/**
 * Format a Unit Source Code
 * 
 * @param testInterface
 * @param monitor
 * @throws CoreException 
 */
@SuppressWarnings("unchecked")
public static void formatUnitSourceCode(IFile file, IProgressMonitor monitor) throws CoreException {
    @SuppressWarnings("rawtypes")
    SubMonitor subMonitor = SubMonitor.convert(monitor, 100);
    ICompilationUnit unit = JavaCore.createCompilationUnitFrom(file);
    subMonitor.split(50);
    ICompilationUnit workingCopy = unit.getWorkingCopy(monitor);

    Map options = DefaultCodeFormatterConstants.getEclipseDefaultSettings();

    options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_7);
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_7);
    options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_7);

    options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS,
            DefaultCodeFormatterConstants.createAlignmentValue(true,
                    DefaultCodeFormatterConstants.WRAP_ONE_PER_LINE,
                    DefaultCodeFormatterConstants.INDENT_ON_COLUMN));

    final CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(options);
    ISourceRange range = unit.getSourceRange();
    TextEdit formatEdit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT, unit.getSource(),
            range.getOffset(), range.getLength(), 0, null);
    subMonitor.split(30);
    if (formatEdit != null /* && formatEdit.hasChildren()*/) {
        workingCopy.applyTextEdit(formatEdit, monitor);
        workingCopy.reconcile(ICompilationUnit.NO_AST, false, null, null);
        workingCopy.commitWorkingCopy(true, null);
        workingCopy.discardWorkingCopy();
    }
    file.refreshLocal(IResource.DEPTH_INFINITE, subMonitor);
    subMonitor.split(20);
}
项目:dacapobench    文件:FullSourceWorkspaceFormatterTests.java   
/**
 * Format files using code formatter default options.
 */
public void testFormatDefault() throws CoreException {
  for (int i = 0; i < FORMAT_FILES.length; i++) {
    if (DACAPO_PRINT)
      System.out.print(".");
    IJavaElement element = JDT_CORE_PROJECT.findType(FORMAT_FILES[i]);
    String source = ((ICompilationUnit) element.getParent()).getSource();
    for (int j = 0; j < 2; j++)
      new DefaultCodeFormatter().format(CodeFormatter.K_COMPILATION_UNIT, source, 0, source.length(), 0, null);
  }
}
项目:eclipse.jdt.ls    文件:AnonymousTypeCompletionProposal.java   
public String updateReplacementString(IDocument document, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException {
    String newBody = createNewBody(impRewrite);
    if (newBody == null) {
        return null;
    }
    StringBuffer buf = new StringBuffer("new A()"); //$NON-NLS-1$
    buf.append(newBody);
    // use the code formatter
    String lineDelim = TextUtilities.getDefaultLineDelimiter(document);
    final IJavaProject project = fCompilationUnit.getJavaProject();
    IRegion lineInfo = document.getLineInformationOfOffset(fReplacementOffset);
    Map<String, String> options = project != null ? project.getOptions(true) : JavaCore.getOptions();
    String replacementString = CodeFormatterUtil.format(CodeFormatter.K_EXPRESSION, buf.toString(), 0, lineDelim, options);
    int lineEndOffset = lineInfo.getOffset() + lineInfo.getLength();
    int p = offset;
    if (p < document.getLength()) {
        char ch = document.getChar(p);
        while (p < lineEndOffset) {
            if (ch == '(' || ch == ')' || ch == ';' || ch == ',') {
                break;
            }
            ch = document.getChar(++p);
        }
        if (ch != ';' && ch != ',' && ch != ')') {
            replacementString = replacementString + ';';
        }
    }
    int beginIndex = replacementString.indexOf('(');
    replacementString = replacementString.substring(beginIndex);
    return replacementString;
}
项目:che    文件:CompletionProposalCollector.java   
/**
 * Creates the Java completion proposal for the JDT Core {@link
 * org.eclipse.jdt.core.CompletionProposal#FIELD_REF_WITH_CASTED_RECEIVER} proposal.
 *
 * @param proposal the JDT Core proposal
 * @return the Java completion proposal
 * @since 3.4
 */
private IJavaCompletionProposal createFieldWithCastedReceiverProposal(
    CompletionProposal proposal) {
  String completion = String.valueOf(proposal.getCompletion());
  completion =
      CodeFormatterUtil.format(
          CodeFormatter.K_EXPRESSION, completion, 0, "\n", fJavaProject); // $NON-NLS-1$
  int start = proposal.getReplaceStart();
  int length = getLength(proposal);
  StyledString label = fLabelProvider.createStyledLabel(proposal);
  Image image = getImage(fLabelProvider.createFieldImageDescriptor(proposal));
  int relevance = computeRelevance(proposal);

  JavaCompletionProposal javaProposal =
      new JavaFieldWithCastedReceiverCompletionProposal(
          completion,
          start,
          length,
          image,
          label,
          relevance,
          getContext().isInJavadoc(),
          getInvocationContext(),
          proposal);
  if (fJavaProject != null)
    javaProposal.setProposalInfo(new FieldProposalInfo(fJavaProject, proposal));

  javaProposal.setTriggerCharacters(VAR_TRIGGER);

  return javaProposal;
}
项目:che    文件:Formatter.java   
/**
 * Creates edits that describe how to format the given string. Returns the changes required to
 * format source.
 *
 * @param formatter The file with custom formatter settings
 * @param content The content to format
 * @param offset The given offset to start recording the edits (inclusive).
 * @param length the given length to stop recording the edits (exclusive).
 * @return <code>List<Change></code> describing the changes required to format source
 * @throws IllegalArgumentException If the offset and length are not inside the string, a
 *     IllegalArgumentException is thrown.
 */
public List<Change> getFormatChanges(File formatter, String content, int offset, int length)
    throws BadLocationException, IllegalArgumentException {
  IDocument document = new Document(content);
  DocumentChangeListener documentChangeListener = new DocumentChangeListener(document);
  Map<String, String> options = null;
  if (formatter != null && formatter.exists()) {
    options = CheCodeFormatterOptions.getFormatSettingsFromFile(formatter);
  }
  TextEdit textEdit =
      CodeFormatterUtil.format2(
          CodeFormatter.K_COMPILATION_UNIT, content, offset, length, 0, null, options);
  textEdit.apply(document);
  return documentChangeListener.getChanges();
}
项目:spotless    文件:EclipseFormatterStepImpl.java   
public String format(String raw) throws Exception {
    TextEdit edit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, raw, 0, raw.length(), 0, UNIX);
    if (edit == null) {
        throw new IllegalArgumentException("Invalid java syntax for formatting.");
    } else {
        IDocument doc = new Document(raw);
        edit.apply(doc);
        return doc.get();
    }
}
项目:PDFReporter-Studio    文件:JDTUtils.java   
/**
    * Formats the specified compilation unit.
    * 
    * @param unit the compilation unit to format
    * @param monitor the monitor for the operation
    * @throws JavaModelException
    */
public static void formatUnitSourceCode(ICompilationUnit unit,
        IProgressMonitor monitor) throws JavaModelException {
    CodeFormatter formatter = ToolFactory.createCodeFormatter(null);
    ISourceRange range = unit.getSourceRange();
    TextEdit formatEdit = formatter.format(
            CodeFormatter.K_COMPILATION_UNIT, unit.getSource(),
            range.getOffset(), range.getLength(), 0, null);
    if (formatEdit != null && formatEdit.hasChildren()) {
        unit.applyTextEdit(formatEdit, monitor);
    } else {
        monitor.done();
    }
}
项目:jenerate    文件:JavaCodeFormatterImpl.java   
@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();
}
项目:google-java-format    文件:GoogleJavaFormatter.java   
/** Runs the Google Java formatter on the given source, with only the given ranges specified. */
private TextEdit formatInternal(int kind, String source, IRegion[] regions, int initialIndent) {
  try {
    boolean includeComments =
        (kind & CodeFormatter.F_INCLUDE_COMMENTS) == CodeFormatter.F_INCLUDE_COMMENTS;
    kind &= ~CodeFormatter.F_INCLUDE_COMMENTS;
    SnippetKind snippetKind;
    switch (kind) {
      case ASTParser.K_EXPRESSION:
        snippetKind = SnippetKind.EXPRESSION;
        break;
      case ASTParser.K_STATEMENTS:
        snippetKind = SnippetKind.STATEMENTS;
        break;
      case ASTParser.K_CLASS_BODY_DECLARATIONS:
        snippetKind = SnippetKind.CLASS_BODY_DECLARATIONS;
        break;
      case ASTParser.K_COMPILATION_UNIT:
        snippetKind = SnippetKind.COMPILATION_UNIT;
        break;
      default:
        throw new IllegalArgumentException(String.format("Unknown snippet kind: %d", kind));
    }
    List<Replacement> replacements =
        new SnippetFormatter()
            .format(
                snippetKind, source, rangesFromRegions(regions), initialIndent, includeComments);
    if (idempotent(source, regions, replacements)) {
      // Do not create edits if there's no diff.
      return null;
    }
    // Convert replacements to text edits.
    return editFromReplacements(replacements);
  } catch (IllegalArgumentException | FormatterException exception) {
    // Do not format on errors.
    return null;
  }
}
项目:Eclipse-Postfix-Code-Completion    文件:GetterSetterCompletionProposal.java   
@Override
protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException {

    CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(fField.getJavaProject());
    boolean addComments= settings.createComments;
    int flags= Flags.AccPublic | (fField.getFlags() & Flags.AccStatic);

    String stub;
    if (fIsGetter) {
        String getterName= GetterSetterUtil.getGetterName(fField, null);
        stub= GetterSetterUtil.getGetterStub(fField, getterName, addComments, flags);
    } else {
        String setterName= GetterSetterUtil.getSetterName(fField, null);
        stub= GetterSetterUtil.getSetterStub(fField, setterName, addComments, flags);
    }

    // use the code formatter
    String lineDelim= TextUtilities.getDefaultLineDelimiter(document);

    IRegion region= document.getLineInformationOfOffset(getReplacementOffset());
    int lineStart= region.getOffset();
    int indent= Strings.computeIndentUnits(document.get(lineStart, getReplacementOffset() - lineStart), settings.tabWidth, settings.indentWidth);

    String replacement= CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, stub, indent, lineDelim, fField.getJavaProject());

    if (replacement.endsWith(lineDelim)) {
        replacement= replacement.substring(0, replacement.length() - lineDelim.length());
    }

    setReplacementString(Strings.trimLeadingTabsAndSpaces(replacement));
    return true;
}
项目:Eclipse-Postfix-Code-Completion    文件:Scribe.java   
Scribe(CodeFormatterVisitor formatter, long sourceLevel, IRegion[] regions, CodeSnippetParsingUtil codeSnippetParsingUtil, boolean includeComments) {
    initializeScanner(sourceLevel, formatter.preferences);
    this.formatter = formatter;
    this.pageWidth = formatter.preferences.page_width;
    this.tabLength = formatter.preferences.tab_size;
    this.indentationLevel= 0; // initialize properly
    this.numberOfIndentations = 0;
    this.useTabsOnlyForLeadingIndents = formatter.preferences.use_tabs_only_for_leading_indentations;
    this.indentEmptyLines = formatter.preferences.indent_empty_lines;
    this.tabChar = formatter.preferences.tab_char;
    if (this.tabChar == DefaultCodeFormatterOptions.MIXED) {
        this.indentationSize = formatter.preferences.indentation_size;
    } else {
        this.indentationSize = this.tabLength;
    }
    this.lineSeparator = formatter.preferences.line_separator;
    this.lineSeparatorAndSpace = this.lineSeparator+' ';
    this.firstLS = this.lineSeparator.charAt(0);
    this.lsLength = this.lineSeparator.length();
    this.indentationLevel = formatter.preferences.initial_indentation_level * this.indentationSize;
    this.regions= regions;
    if (codeSnippetParsingUtil != null) {
        final RecordedParsingInformation information = codeSnippetParsingUtil.recordedParsingInformation;
        if (information != null) {
            this.lineEnds = information.lineEnds;
            this.commentPositions = information.commentPositions;
        }
    }
    if (formatter.preferences.comment_format_line_comment) this.formatComments |= CodeFormatter.K_SINGLE_LINE_COMMENT;
    if (formatter.preferences.comment_format_block_comment) this.formatComments |= CodeFormatter.K_MULTI_LINE_COMMENT;
    if (formatter.preferences.comment_format_javadoc_comment) this.formatComments |= CodeFormatter.K_JAVA_DOC;
    if (includeComments) this.formatComments |= CodeFormatter.F_INCLUDE_COMMENTS;
    reset();
}
项目:Eclipse-Postfix-Code-Completion    文件:Scribe.java   
void printComment(int kind, String source, int start, int end, int level) {

        // Set scanner
        resetScanner(source.toCharArray());
        this.scanner.resetTo(start, end);
        // Put back 3.4RC2 code => comment following line  as it has an impact on Linux tests
        // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=234336
        // TODO (frederic) Need more investigations and a better fix in
        // isAdaptableRegion(int) and adaptRegions()
        // this.scannerEndPosition = end;

        // Set indentation level
        this.numberOfIndentations = level;
        this.indentationLevel = level * this.indentationSize;
        this.column = this.indentationLevel + 1;

        // Print corresponding comment
        switch (kind) {
            case CodeFormatter.K_SINGLE_LINE_COMMENT:
                printComment(kind, NO_TRAILING_COMMENT);
                break;
            case CodeFormatter.K_MULTI_LINE_COMMENT:
                printComment(kind, NO_TRAILING_COMMENT);
                break;
            case CodeFormatter.K_JAVA_DOC:
                printJavadocComment(start, end);
                break;
        }
    }
项目:Eclipse-Postfix-Code-Completion    文件:Scribe.java   
public void printNextToken(int expectedTokenType, boolean considerSpaceIfAny, int emptyLineRules) {
    // Set brace flag, it's useful for the scribe while preserving line breaks
    printComment(CodeFormatter.K_UNKNOWN, NO_TRAILING_COMMENT, emptyLineRules);
    try {
        this.currentToken = this.scanner.getNextToken();
        if (expectedTokenType != this.currentToken) {
            throw new AbortFormatting("unexpected token type, expecting:"+expectedTokenType+", actual:"+this.currentToken);//$NON-NLS-1$//$NON-NLS-2$
        }
        print(this.scanner.currentPosition - this.scanner.startPosition, considerSpaceIfAny);
    } catch (InvalidInputException e) {
        throw new AbortFormatting(e);
    }
}
项目:Eclipse-Postfix-Code-Completion    文件:Scribe.java   
public void printQualifiedReference(int sourceEnd, boolean expectParenthesis) {
    int currentTokenStartPosition = this.scanner.currentPosition;
    try {
        do {
            printComment(CodeFormatter.K_UNKNOWN, NO_TRAILING_COMMENT);
            switch(this.currentToken = this.scanner.getNextToken()) {
                case TerminalTokens.TokenNameEOF :
                    return;
                case TerminalTokens.TokenNameWHITESPACE :
                    addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition());
                    currentTokenStartPosition = this.scanner.currentPosition;
                    break;
                case TerminalTokens.TokenNameCOMMENT_BLOCK :
                case TerminalTokens.TokenNameCOMMENT_JAVADOC :
                    printBlockComment(false);
                    currentTokenStartPosition = this.scanner.currentPosition;
                    break;
                case TerminalTokens.TokenNameCOMMENT_LINE :
                    printLineComment();
                    currentTokenStartPosition = this.scanner.currentPosition;
                    break;
                case TerminalTokens.TokenNameIdentifier :
                case TerminalTokens.TokenNameDOT :
                    print(this.scanner.currentPosition - this.scanner.startPosition, false);
                    currentTokenStartPosition = this.scanner.currentPosition;
                    break;
                case TerminalTokens.TokenNameRPAREN:
                    if (expectParenthesis) {
                        currentTokenStartPosition = this.scanner.startPosition;
                    }
                    // $FALL-THROUGH$ - fall through default case...
                default:
                    this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1);
                    return;
            }
        } while (this.scanner.currentPosition <= sourceEnd);
    } catch(InvalidInputException e) {
        throw new AbortFormatting(e);
    }
}