Example usage for org.eclipse.jdt.core.formatter IndentManipulation changeIndent

List of usage examples for org.eclipse.jdt.core.formatter IndentManipulation changeIndent

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.formatter IndentManipulation changeIndent.

Prototype

public static String changeIndent(String code, int indentUnitsToRemove, int tabWidth, int indentWidth,
        String newIndentString, String lineDelim) 

Source Link

Document

Change the indent of a, possible multiple line, code string.

Usage

From source file:jmockit.assist.MockMethodCompletionProposal.java

License:Open Source License

private String generateMethodDeclaration(final IDocument document, final Document recoveredDocument,
        final ASTNode node, final ASTRewrite rewrite, final CodeGenerationSettings settings,
        final MethodDeclaration stub) throws BadLocationException {
    ChildListPropertyDescriptor descriptor = getPropDescriptor(node);
    ListRewrite rewriter = rewrite.getListRewrite(node, descriptor);
    rewriter.insertFirst(stub, null);//from ww w. jav a2s .c  o  m

    ITrackedNodePosition position = rewrite.track(stub);

    rewrite.rewriteAST(recoveredDocument, fJavaProject.getOptions(true)).apply(recoveredDocument);

    String generatedCode = recoveredDocument.get(position.getStartPosition(), position.getLength());

    int generatedIndent = IndentManipulation.measureIndentUnits(
            getIndentAt(recoveredDocument, position.getStartPosition(), settings), settings.tabWidth,
            settings.indentWidth);

    String indent = getIndentAt(document, getReplacementOffset(), settings);
    String methodDeclarationText = IndentManipulation.changeIndent(generatedCode, generatedIndent,
            settings.tabWidth, settings.indentWidth, indent, TextUtilities.getDefaultLineDelimiter(document));

    return methodDeclarationText;
}

From source file:org.eclipse.objectteams.otdt.internal.ui.assist.CompletionAdaptor.OverrideRoleCompletionProposal.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
    @Override/*from  w ww.  j a va2s  .c  o  m*/
    protected boolean updateReplacementString(IDocument document, char trigger, int offset,
            ImportRewrite importRewrite) throws CoreException, BadLocationException {
        Document recoveredDocument = new Document();
        CompilationUnit unit = getRecoveredAST(document, offset, recoveredDocument);

        // find enclosing team type:
        ASTNode node = NodeFinder.perform(unit, fReplaceStart, 0);
        while (node != null && !(node instanceof AbstractTypeDeclaration)) {
            node = node.getParent();
        }

        if (node != null) {
            AbstractTypeDeclaration teamDecl = ((AbstractTypeDeclaration) node);

            // create and setup the rewrite:
            AST ast = unit.getAST();
            ASTRewrite rewrite = ASTRewrite.create(ast);
            rewrite.setToOTJ();

            // create type
            TypeDeclaration newType = ast.newTypeDeclaration();
            newType.setName(ast.newSimpleName(this.fRoleName));
            newType.setInterface(Flags.isInterface(this.fModifiers));
            newType.setTeam(Flags.isTeam(this.fModifiers));
            // add @Override:
            Annotation overrideAnnotation = ast.newMarkerAnnotation();
            overrideAnnotation.setTypeName(ast.newSimpleName("Override")); //$NON-NLS-1$
            List modifiers = newType.modifiers();
            modifiers.add(overrideAnnotation);
            // add protected or public
            modifiers.add(ast.newModifier(Flags.isPublic(this.fModifiers) ? ModifierKeyword.PUBLIC_KEYWORD
                    : ModifierKeyword.PROTECTED_KEYWORD));
            // add team keyword?
            if (Flags.isTeam(this.fModifiers))
                modifiers.add(ast.newModifier(ModifierKeyword.TEAM_KEYWORD));

            insertStub(rewrite, teamDecl, teamDecl.getBodyDeclarationsProperty(), this.fReplaceStart, newType);

            // create the replacementString from the rewrite:
            ITrackedNodePosition position = rewrite.track(newType);
            try {
                rewrite.rewriteAST(recoveredDocument, fJavaProject.getOptions(true)).apply(recoveredDocument);

                String generatedCode = recoveredDocument.get(position.getStartPosition(), position.getLength());
                CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(fJavaProject);
                int generatedIndent = IndentManipulation.measureIndentUnits(
                        getIndentAt(recoveredDocument, position.getStartPosition(), settings), settings.tabWidth,
                        settings.indentWidth);

                String indent = getIndentAt(document, getReplacementOffset(), settings);
                setReplacementString(
                        IndentManipulation.changeIndent(generatedCode, generatedIndent, settings.tabWidth,
                                settings.indentWidth, indent, TextUtilities.getDefaultLineDelimiter(document)));

            } catch (MalformedTreeException exception) {
                JavaPlugin.log(exception);
            } catch (BadLocationException exception) {
                JavaPlugin.log(exception);
            }
        }
        return true;
    }

From source file:org.jboss.tools.websockets.ui.internal.ca.MethodCompletionProposal.java

License:Open Source License

@Override
protected boolean updateReplacementString(IDocument document, char trigger, int offset,
        ImportRewrite importRewrite) throws CoreException, BadLocationException {
    Document recoveredDocument = new Document();
    CompilationUnit unit = getRecoveredAST(document, offset, recoveredDocument);
    if (importRewrite == null) {
        importRewrite = StubUtility.createImportRewrite(unit, true); // create a dummy import rewriter to have one
    }//from   w  ww  .j av  a2 s .c  o m

    ITypeBinding declaringType = null;
    ChildListPropertyDescriptor descriptor = null;
    ASTNode node = NodeFinder.perform(unit, position, 1);
    if (node instanceof SimpleName || node instanceof Modifier) {
        node = node.getParent();
        if (node instanceof MarkerAnnotation) {
            node = node.getParent();
        }
    }
    if (node instanceof MethodDeclaration || node instanceof FieldDeclaration) {
        node = node.getParent();
    }
    if (node instanceof AnonymousClassDeclaration) {
        declaringType = ((AnonymousClassDeclaration) node).resolveBinding();
        descriptor = AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY;
    } else if (node instanceof AbstractTypeDeclaration) {
        AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) node;
        descriptor = declaration.getBodyDeclarationsProperty();
        declaringType = declaration.resolveBinding();
    }
    if (declaringType != null) {
        ASTRewrite rewrite = ASTRewrite.create(unit.getAST());
        CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(fJavaProject);

        String delimiter = StubUtility.getLineDelimiterUsed(unit.getTypeRoot());

        StringBuffer content = new StringBuffer();
        if (methodInfo.annotation != null) {
            importRewrite.addImport(methodInfo.annotation);
            int dot = methodInfo.annotation.lastIndexOf('.');
            String simpleName = methodInfo.annotation.substring(dot + 1);
            content.append("@").append(simpleName).append(delimiter); //$NON-NLS-1$
        }
        content.append("public void " + methodInfo.methodName + "("); //$NON-NLS-1$ //$NON-NLS-2$
        boolean first = true;
        for (int i = 0; i < methodInfo.paramTypes.length; i++) {
            String paramType = methodInfo.paramTypes[i];
            if (!first) {
                content.append(", "); //$NON-NLS-1$
            } else {
                first = false;
            }
            importRewrite.addImport(paramType);
            String simpleName = paramType.substring(paramType.lastIndexOf('.') + 1);
            String name = methodInfo.paramNames != null ? methodInfo.paramNames[i]
                    : simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1);
            content.append(simpleName).append(" ").append(name); //$NON-NLS-1$
        }
        content.append(") {").append(delimiter).append("\t\t"); //$NON-NLS-1$ //$NON-NLS-2$
        String body = StubUtility.getMethodBodyContent(false, fJavaProject, declaringType.getName(),
                declaringType.getName(), "", delimiter); //$NON-NLS-1$
        if (body == null || body.length() == 0) {
            body = delimiter;
        }
        content.append(body);
        content.append("}").append(delimiter); //$NON-NLS-1$

        MethodDeclaration stub = (MethodDeclaration) rewrite.createStringPlaceholder(
                CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, content.toString(), 0,
                        delimiter, unit.getTypeRoot().getJavaProject()),
                ASTNode.METHOD_DECLARATION);

        ListRewrite rewriter = rewrite.getListRewrite(node, descriptor);
        rewriter.insertFirst(stub, null);

        ITrackedNodePosition position = rewrite.track(stub);
        try {
            rewrite.rewriteAST(recoveredDocument, fJavaProject.getOptions(true)).apply(recoveredDocument);

            String generatedCode = recoveredDocument.get(position.getStartPosition(), position.getLength());
            int generatedIndent = IndentManipulation.measureIndentUnits(
                    getIndentAt(recoveredDocument, position.getStartPosition(), settings), settings.tabWidth,
                    settings.indentWidth);

            String indent = getIndentAt(document, getReplacementOffset(), settings);
            if (this.position > offset && indent.length() == 0) {
                indent = "\t"; //$NON-NLS-1$
            }
            String replacementString = IndentManipulation.changeIndent(generatedCode, generatedIndent,
                    settings.tabWidth, settings.indentWidth, indent,
                    TextUtilities.getDefaultLineDelimiter(document));
            if (this.position > offset) {
                replacementString = "\t" + replacementString + delimiter; //$NON-NLS-1$
                setReplacementLength(getReplacementLength());
                setReplacementOffset(getReplacementOffset() + this.position - offset);
            } else if (prefixLength > 0) {
                setReplacementLength(getReplacementLength() + prefixLength);
                setReplacementOffset(getReplacementOffset() - prefixLength);
            }
            setReplacementString(replacementString);
        } catch (MalformedTreeException exception) {
            JavaPlugin.log(exception);
        } catch (BadLocationException exception) {
            JavaPlugin.log(exception);
        }
    }
    return true;
}

From source file:org.limy.eclipse.code.javadoc.LimyAddJavadocOperation.java

License:Open Source License

/**
 * R?gCfg?B//w  ww .  ja v  a2  s.  c  om
 * @param javaElement JavaNX
 * @param member ?o
 * @param document hL?g
 * @param lineDelim f~^
 * @param comment R?g
 * @return Cfg
 * @throws BadLocationException hL?gO
 * @throws CoreException RAO
 */
private String createIndentedComment(IJavaElement javaElement, IMember member, IDocument document,
        String lineDelim) throws BadLocationException, CoreException {

    // JavadocR?g??
    String comment = createComment(member, lineDelim);

    // v?WFNgL^u?
    int tabWidth = LimyJavaUtils.getTabWidth(javaElement.getJavaProject());

    // ?o`u?se
    IRegion region = document.getLineInformationOfOffset(LimyJavaUtils.getMemberStartOffset(member, document));
    String line = document.get(region.getOffset(), region.getLength());

    String indentString = IndentManipulation.extractIndentString(line, tabWidth, tabWidth);

    // R?gCfg
    return IndentManipulation.changeIndent(comment, 0, tabWidth, tabWidth, indentString, lineDelim);
}