Search in sources :

Example 11 with CodeStyleManager

use of com.intellij.psi.codeStyle.CodeStyleManager in project intellij-community by JetBrains.

the class JsonFormattingTest method doTest.

private void doTest() {
    myFixture.configureByFile(getTestName(false) + ".json");
    WriteCommandAction.runWriteCommandAction(null, () -> {
        CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myFixture.getProject());
        codeStyleManager.reformat(myFixture.getFile());
    });
    myFixture.checkResultByFile(getTestName(false) + "_after.json");
}
Also used : CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager)

Example 12 with CodeStyleManager

use of com.intellij.psi.codeStyle.CodeStyleManager in project intellij-community by JetBrains.

the class PsiReplacementUtil method replaceStatement.

public static PsiElement replaceStatement(@NotNull PsiStatement statement, @NotNull @NonNls String newStatementText) {
    final Project project = statement.getProject();
    final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
    final PsiElementFactory factory = psiFacade.getElementFactory();
    final PsiStatement newStatement = factory.createStatementFromText(newStatementText, statement);
    final PsiElement replacementExp = statement.replace(newStatement);
    final CodeStyleManager styleManager = CodeStyleManager.getInstance(project);
    return styleManager.reformat(replacementExp);
}
Also used : Project(com.intellij.openapi.project.Project) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager)

Example 13 with CodeStyleManager

use of com.intellij.psi.codeStyle.CodeStyleManager in project intellij-community by JetBrains.

the class MakeCallChainIntoCallSequenceIntention method processIntention.

@Override
public void processIntention(@NotNull PsiElement element) throws IncorrectOperationException {
    final List<String> callTexts = new ArrayList<>();
    PsiExpression root = (PsiExpression) element;
    while (root instanceof PsiMethodCallExpression) {
        final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) root;
        final PsiExpressionList arguments = methodCallExpression.getArgumentList();
        final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression();
        callTexts.add(methodExpression.getReferenceName() + arguments.getText());
        root = methodExpression.getQualifierExpression();
        if (root == null) {
            return;
        }
    }
    final PsiType rootType = root.getType();
    if (rootType == null) {
        return;
    }
    final String targetText;
    final PsiStatement appendStatement;
    @NonNls final String firstStatement;
    final String variableDeclaration;
    final boolean showRenameTemplate;
    final PsiElement parent = element.getParent();
    if (parent instanceof PsiExpressionStatement) {
        targetText = root.getText();
        appendStatement = (PsiStatement) parent;
        firstStatement = null;
        variableDeclaration = null;
        showRenameTemplate = false;
    } else {
        final PsiElement grandParent = parent.getParent();
        appendStatement = (PsiStatement) grandParent;
        if (parent instanceof PsiAssignmentExpression && grandParent instanceof PsiExpressionStatement) {
            final PsiAssignmentExpression assignment = (PsiAssignmentExpression) parent;
            final PsiExpression lhs = assignment.getLExpression();
            if (!(lhs instanceof PsiReferenceExpression)) {
                return;
            }
            final PsiReferenceExpression expression = (PsiReferenceExpression) lhs;
            final PsiElement target = expression.resolve();
            if (!(target instanceof PsiVariable)) {
                return;
            }
            final PsiVariable variable = (PsiVariable) target;
            final PsiType variableType = variable.getType();
            if (variableType.equals(rootType)) {
                targetText = lhs.getText();
                final PsiJavaToken token = assignment.getOperationSign();
                firstStatement = targetText + token.getText() + root.getText() + ';';
                showRenameTemplate = false;
            } else {
                targetText = "x";
                showRenameTemplate = true;
                final Project project = element.getProject();
                final CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(project);
                if (codeStyleSettings.GENERATE_FINAL_LOCALS) {
                    firstStatement = "final " + rootType.getCanonicalText() + ' ' + targetText + '=' + root.getText() + ';';
                } else {
                    firstStatement = rootType.getCanonicalText() + ' ' + targetText + '=' + root.getText() + ';';
                }
            }
            variableDeclaration = null;
        } else {
            final PsiDeclarationStatement declaration = (PsiDeclarationStatement) appendStatement;
            final PsiVariable variable = (PsiVariable) declaration.getDeclaredElements()[0];
            final PsiType variableType = variable.getType();
            if (variableType.equals(rootType)) {
                targetText = variable.getName();
                if (variable.hasModifierProperty(PsiModifier.FINAL)) {
                    firstStatement = "final " + variableType.getCanonicalText() + ' ' + variable.getName() + '=' + root.getText() + ';';
                } else {
                    firstStatement = variableType.getCanonicalText() + ' ' + variable.getName() + '=' + root.getText() + ';';
                }
                variableDeclaration = null;
                showRenameTemplate = false;
            } else {
                if (variable.hasModifierProperty(PsiModifier.FINAL)) {
                    variableDeclaration = "final " + variableType.getCanonicalText() + ' ' + variable.getName() + '=';
                } else {
                    variableDeclaration = variableType.getCanonicalText() + ' ' + variable.getName() + '=';
                }
                targetText = "x";
                showRenameTemplate = true;
                final Project project = element.getProject();
                final CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(project);
                if (codeStyleSettings.GENERATE_FINAL_LOCALS) {
                    firstStatement = "final " + rootType.getCanonicalText() + " x=" + root.getText() + ';';
                } else {
                    firstStatement = rootType.getCanonicalText() + " x=" + root.getText() + ';';
                }
            }
        }
    }
    final StringBuilder builder = new StringBuilder("{\n");
    if (firstStatement != null) {
        builder.append(firstStatement);
    }
    Collections.reverse(callTexts);
    for (int i = 0, size = callTexts.size(); i < size; i++) {
        final String callText = callTexts.get(i);
        if (i == size - 1 && variableDeclaration != null) {
            builder.append(variableDeclaration);
        }
        builder.append(targetText).append('.').append(callText).append(";\n");
    }
    builder.append('}');
    final PsiManager manager = element.getManager();
    final Project project = manager.getProject();
    final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
    final PsiElement appendStatementParent = appendStatement.getParent();
    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());
    final PsiCodeBlock codeBlock = factory.createCodeBlockFromText(builder.toString(), appendStatement);
    if (appendStatementParent instanceof PsiLoopStatement || appendStatementParent instanceof PsiIfStatement) {
        final PsiElement insertedCodeBlock = appendStatement.replace(codeBlock);
        final PsiCodeBlock reformattedCodeBlock = (PsiCodeBlock) codeStyleManager.reformat(insertedCodeBlock);
        if (showRenameTemplate) {
            final PsiStatement[] statements = reformattedCodeBlock.getStatements();
            final PsiVariable variable = (PsiVariable) ((PsiDeclarationStatement) statements[0]).getDeclaredElements()[0];
            HighlightUtil.showRenameTemplate(appendStatementParent, variable);
        }
    } else {
        final PsiStatement[] statements = codeBlock.getStatements();
        PsiVariable variable = null;
        for (int i = 0, length = statements.length; i < length; i++) {
            final PsiElement insertedStatement = appendStatementParent.addBefore(statements[i], appendStatement);
            if (i == 0 && showRenameTemplate) {
                variable = (PsiVariable) ((PsiDeclarationStatement) insertedStatement).getDeclaredElements()[0];
            }
            codeStyleManager.reformat(insertedStatement);
        }
        appendStatement.delete();
        if (variable != null) {
            HighlightUtil.showRenameTemplate(appendStatementParent, variable);
        }
    }
}
Also used : ArrayList(java.util.ArrayList) NonNls(org.jetbrains.annotations.NonNls) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) Project(com.intellij.openapi.project.Project) CodeStyleSettings(com.intellij.psi.codeStyle.CodeStyleSettings)

Example 14 with CodeStyleManager

use of com.intellij.psi.codeStyle.CodeStyleManager in project intellij-community by JetBrains.

the class ReplaceConditionalWithIfIntention method replaceConditionalWithIf.

private static void replaceConditionalWithIf(PsiConditionalExpression expression) {
    final PsiElement expressionParent = expression.getParent();
    if (expressionParent instanceof PsiLambdaExpression) {
        final PsiElement codeBlock = ((PsiLambdaExpression) RefactoringUtil.expandExpressionLambdaToCodeBlock(expression)).getBody();
        LOG.assertTrue(codeBlock instanceof PsiCodeBlock, codeBlock);
        final PsiStatement statement = ((PsiCodeBlock) codeBlock).getStatements()[0];
        expression = (PsiConditionalExpression) (statement instanceof PsiReturnStatement ? ((PsiReturnStatement) statement).getReturnValue() : ((PsiExpressionStatement) statement).getExpression());
    }
    final PsiStatement statement = PsiTreeUtil.getParentOfType(expression, PsiStatement.class);
    if (statement == null) {
        return;
    }
    final PsiVariable variable;
    if (statement instanceof PsiDeclarationStatement) {
        variable = PsiTreeUtil.getParentOfType(expression, PsiVariable.class);
    } else {
        variable = null;
    }
    PsiExpression thenExpression = ParenthesesUtils.stripParentheses(expression.getThenExpression());
    PsiExpression elseExpression = ParenthesesUtils.stripParentheses(expression.getElseExpression());
    final PsiExpression condition = ParenthesesUtils.stripParentheses(expression.getCondition());
    final StringBuilder newStatement = new StringBuilder();
    newStatement.append("if(");
    if (condition != null) {
        newStatement.append(condition.getText());
    }
    newStatement.append(')');
    if (variable != null) {
        final String name = variable.getName();
        newStatement.append(name).append('=');
        PsiExpression initializer = variable.getInitializer();
        if (initializer == null) {
            return;
        }
        if (initializer instanceof PsiArrayInitializerExpression) {
            final int conditionIdx = ArrayUtilRt.find(((PsiArrayInitializerExpression) initializer).getInitializers(), expression);
            if (conditionIdx >= 0) {
                initializer = (PsiExpression) initializer.replace(RefactoringUtil.convertInitializerToNormalExpression(initializer, variable.getType()));
                final PsiArrayInitializerExpression arrayInitializer = ((PsiNewExpression) initializer).getArrayInitializer();
                LOG.assertTrue(arrayInitializer != null, initializer.getText());
                expression = (PsiConditionalExpression) arrayInitializer.getInitializers()[conditionIdx];
                thenExpression = expression.getThenExpression();
                elseExpression = expression.getElseExpression();
            }
        }
        appendElementTextWithoutParentheses(initializer, expression, thenExpression, newStatement);
        newStatement.append("; else ").append(name).append('=');
        appendElementTextWithoutParentheses(initializer, expression, elseExpression, newStatement);
        newStatement.append(';');
        initializer.delete();
        final PsiManager manager = statement.getManager();
        final Project project = manager.getProject();
        final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
        final PsiElementFactory factory = facade.getElementFactory();
        final PsiStatement ifStatement = factory.createStatementFromText(newStatement.toString(), statement);
        final PsiElement parent = statement.getParent();
        final PsiElement addedElement = parent.addAfter(ifStatement, statement);
        final CodeStyleManager styleManager = CodeStyleManager.getInstance(manager.getProject());
        styleManager.reformat(addedElement);
    } else {
        final boolean addBraces = PsiTreeUtil.getParentOfType(expression, PsiIfStatement.class, true, PsiStatement.class) != null;
        if (addBraces || thenExpression == null) {
            newStatement.append('{');
        }
        appendElementTextWithoutParentheses(statement, expression, thenExpression, newStatement);
        if (addBraces) {
            newStatement.append("} else {");
        } else {
            if (thenExpression == null) {
                newStatement.append('}');
            }
            newStatement.append(" else ");
            if (elseExpression == null) {
                newStatement.append('{');
            }
        }
        appendElementTextWithoutParentheses(statement, expression, elseExpression, newStatement);
        if (addBraces || elseExpression == null) {
            newStatement.append('}');
        }
        PsiReplacementUtil.replaceStatement(statement, newStatement.toString());
    }
}
Also used : CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) Project(com.intellij.openapi.project.Project)

Example 15 with CodeStyleManager

use of com.intellij.psi.codeStyle.CodeStyleManager in project intellij-community by JetBrains.

the class ChangeToEndOfLineCommentIntention method processIntention.

public void processIntention(@NotNull PsiElement element) throws IncorrectOperationException {
    final PsiComment comment = (PsiComment) element;
    final Project project = comment.getProject();
    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
    final PsiElement parent = comment.getParent();
    assert parent != null;
    final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
    final String commentText = comment.getText();
    final PsiElement whitespace = comment.getNextSibling();
    final String text = commentText.substring(2, commentText.length() - 2);
    final String[] lines = text.split("\n");
    for (int i = lines.length - 1; i >= 1; i--) {
        final PsiComment nextComment = factory.createCommentFromText("//" + lines[i].trim(), parent);
        parent.addAfter(nextComment, comment);
        if (whitespace != null) {
            final PsiParserFacade parserFacade = PsiParserFacade.SERVICE.getInstance(project);
            final PsiElement newWhiteSpace = parserFacade.createWhiteSpaceFromText(whitespace.getText());
            parent.addAfter(newWhiteSpace, comment);
        }
    }
    final PsiComment newComment = factory.createCommentFromText("//" + lines[0], parent);
    final PsiElement replacedComment = comment.replace(newComment);
    codeStyleManager.reformat(replacedComment);
}
Also used : Project(com.intellij.openapi.project.Project) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager)

Aggregations

CodeStyleManager (com.intellij.psi.codeStyle.CodeStyleManager)97 JavaCodeStyleManager (com.intellij.psi.codeStyle.JavaCodeStyleManager)29 Project (com.intellij.openapi.project.Project)26 TextRange (com.intellij.openapi.util.TextRange)19 NonNls (org.jetbrains.annotations.NonNls)18 IncorrectOperationException (com.intellij.util.IncorrectOperationException)16 NotNull (org.jetbrains.annotations.NotNull)8 Document (com.intellij.openapi.editor.Document)6 PsiFile (com.intellij.psi.PsiFile)6 Module (com.intellij.openapi.module.Module)5 PsiElement (com.intellij.psi.PsiElement)4 PsiDocComment (com.intellij.psi.javadoc.PsiDocComment)4 Nullable (org.jetbrains.annotations.Nullable)4 CaretModel (com.intellij.openapi.editor.CaretModel)3 CodeStyleSettings (com.intellij.psi.codeStyle.CodeStyleSettings)3 JavaLanguage (com.intellij.lang.java.JavaLanguage)2 FileType (com.intellij.openapi.fileTypes.FileType)2 Comparing (com.intellij.openapi.util.Comparing)2 StringUtil (com.intellij.openapi.util.text.StringUtil)2 com.intellij.psi (com.intellij.psi)2