Search in sources :

Example 81 with JavaCodeStyleManager

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

the class PsiReplacementUtil method replaceStatementAndShortenClassNames.

public static void replaceStatementAndShortenClassNames(@NotNull PsiStatement statement, @NotNull @NonNls String newStatementText) {
    final Project project = statement.getProject();
    final CodeStyleManager styleManager = CodeStyleManager.getInstance(project);
    final JavaCodeStyleManager javaStyleManager = JavaCodeStyleManager.getInstance(project);
    if (FileTypeUtils.isInServerPageFile(statement)) {
        final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
        final PsiFile jspFile = PsiUtilCore.getTemplateLanguageFile(statement);
        if (jspFile == null) {
            return;
        }
        final Document document = documentManager.getDocument(jspFile);
        if (document == null) {
            return;
        }
        documentManager.doPostponedOperationsAndUnblockDocument(document);
        final TextRange textRange = statement.getTextRange();
        document.replaceString(textRange.getStartOffset(), textRange.getEndOffset(), newStatementText);
        documentManager.commitDocument(document);
        final FileViewProvider viewProvider = jspFile.getViewProvider();
        PsiElement elementAt = viewProvider.findElementAt(textRange.getStartOffset(), JavaLanguage.INSTANCE);
        if (elementAt == null) {
            return;
        }
        final int endOffset = textRange.getStartOffset() + newStatementText.length();
        while (elementAt.getTextRange().getEndOffset() < endOffset || !(elementAt instanceof PsiStatement)) {
            elementAt = elementAt.getParent();
            if (elementAt == null) {
                LOG.error("Cannot decode statement");
                return;
            }
        }
        final PsiStatement newStatement = (PsiStatement) elementAt;
        javaStyleManager.shortenClassReferences(newStatement);
        final TextRange newTextRange = newStatement.getTextRange();
        final Language baseLanguage = viewProvider.getBaseLanguage();
        final PsiFile element = viewProvider.getPsi(baseLanguage);
        if (element != null) {
            styleManager.reformatRange(element, newTextRange.getStartOffset(), newTextRange.getEndOffset());
        }
    } else {
        final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
        final PsiElementFactory factory = facade.getElementFactory();
        PsiStatement newStatement = factory.createStatementFromText(newStatementText, statement);
        newStatement = (PsiStatement) statement.replace(newStatement);
        javaStyleManager.shortenClassReferences(newStatement);
        styleManager.reformat(newStatement);
    }
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) TextRange(com.intellij.openapi.util.TextRange) Document(com.intellij.openapi.editor.Document) Project(com.intellij.openapi.project.Project) Language(com.intellij.lang.Language) JavaLanguage(com.intellij.lang.java.JavaLanguage) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager)

Example 82 with JavaCodeStyleManager

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

the class IncrementDecrementUsedAsExpressionInspection method extractPrefixPostfixExpressionToSeparateStatement.

public static void extractPrefixPostfixExpressionToSeparateStatement(PsiElement element) {
    final PsiExpression operand;
    if (element instanceof PsiPostfixExpression) {
        final PsiPostfixExpression postfixExpression = (PsiPostfixExpression) element;
        operand = postfixExpression.getOperand();
    } else if (element instanceof PsiPrefixExpression) {
        final PsiPrefixExpression prefixExpression = (PsiPrefixExpression) element;
        operand = prefixExpression.getOperand();
    } else {
        assert false;
        return;
    }
    if (operand == null) {
        return;
    }
    final PsiStatement statement = PsiTreeUtil.getParentOfType(element, PsiStatement.class);
    if (statement == null) {
        return;
    }
    final PsiElement parent = statement.getParent();
    if (parent == null) {
        return;
    }
    final Project project = element.getProject();
    final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
    final String newStatementText = element.getText() + ';';
    final String operandText = operand.getText();
    if (parent instanceof PsiIfStatement || parent instanceof PsiLoopStatement) {
        // need to add braces because
        // in/decrement is inside braceless control statement body
        final StringBuilder text = new StringBuilder();
        text.append('{');
        final String elementText = PsiReplacementUtil.getElementText(statement, element, operandText);
        if (element instanceof PsiPostfixExpression) {
            text.append(elementText);
            text.append(newStatementText);
        } else {
            text.append(newStatementText);
            text.append(elementText);
        }
        text.append('}');
        final PsiCodeBlock codeBlock = factory.createCodeBlockFromText(text.toString(), parent);
        statement.replace(codeBlock);
        return;
    }
    final PsiStatement newStatement = factory.createStatementFromText(newStatementText, element);
    if (statement instanceof PsiReturnStatement) {
        if (element instanceof PsiPostfixExpression) {
            // special handling of postfix expression in return statement
            final PsiReturnStatement returnStatement = (PsiReturnStatement) statement;
            final PsiExpression returnValue = returnStatement.getReturnValue();
            if (returnValue == null) {
                return;
            }
            final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
            final String variableName = javaCodeStyleManager.suggestUniqueVariableName("result", returnValue, true);
            final PsiType type = returnValue.getType();
            if (type == null) {
                return;
            }
            final String newReturnValueText = PsiReplacementUtil.getElementText(returnValue, element, operandText);
            final String declarationStatementText = type.getCanonicalText() + ' ' + variableName + '=' + newReturnValueText + ';';
            final PsiStatement declarationStatement = factory.createStatementFromText(declarationStatementText, returnStatement);
            parent.addBefore(declarationStatement, statement);
            parent.addBefore(newStatement, statement);
            final PsiStatement newReturnStatement = factory.createStatementFromText("return " + variableName + ';', returnStatement);
            returnStatement.replace(newReturnStatement);
            return;
        } else {
            parent.addBefore(newStatement, statement);
        }
    } else if (statement instanceof PsiThrowStatement) {
        if (element instanceof PsiPostfixExpression) {
            // special handling of postfix expression in throw statement
            final PsiThrowStatement returnStatement = (PsiThrowStatement) statement;
            final PsiExpression exception = returnStatement.getException();
            if (exception == null) {
                return;
            }
            final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
            final String variableName = javaCodeStyleManager.suggestUniqueVariableName("e", exception, true);
            final PsiType type = exception.getType();
            if (type == null) {
                return;
            }
            final String newReturnValueText = PsiReplacementUtil.getElementText(exception, element, operandText);
            final String declarationStatementText = type.getCanonicalText() + ' ' + variableName + '=' + newReturnValueText + ';';
            final PsiStatement declarationStatement = factory.createStatementFromText(declarationStatementText, returnStatement);
            parent.addBefore(declarationStatement, statement);
            parent.addBefore(newStatement, statement);
            final PsiStatement newReturnStatement = factory.createStatementFromText("throw " + variableName + ';', returnStatement);
            returnStatement.replace(newReturnStatement);
            return;
        } else {
            parent.addBefore(newStatement, statement);
        }
    } else if (!(statement instanceof PsiForStatement)) {
        if (element instanceof PsiPostfixExpression) {
            parent.addAfter(newStatement, statement);
        } else {
            parent.addBefore(newStatement, statement);
        }
    } else if (operand instanceof PsiReferenceExpression) {
        final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) operand;
        final PsiElement target = referenceExpression.resolve();
        if (target != null) {
            final SearchScope useScope = target.getUseScope();
            if (!new LocalSearchScope(statement).equals(useScope)) {
                if (element instanceof PsiPostfixExpression) {
                    parent.addAfter(newStatement, statement);
                } else {
                    parent.addBefore(newStatement, statement);
                }
            }
        }
    }
    if (statement instanceof PsiLoopStatement) {
        // in/decrement inside loop statement condition
        final PsiLoopStatement loopStatement = (PsiLoopStatement) statement;
        final PsiStatement body = loopStatement.getBody();
        if (body instanceof PsiBlockStatement) {
            final PsiBlockStatement blockStatement = (PsiBlockStatement) body;
            final PsiCodeBlock codeBlock = blockStatement.getCodeBlock();
            if (element instanceof PsiPostfixExpression) {
                final PsiElement firstElement = codeBlock.getFirstBodyElement();
                codeBlock.addBefore(newStatement, firstElement);
            } else {
                codeBlock.add(newStatement);
            }
        } else {
            final StringBuilder blockText = new StringBuilder();
            blockText.append('{');
            if (element instanceof PsiPostfixExpression) {
                blockText.append(newStatementText);
                if (body != null) {
                    blockText.append(body.getText());
                }
            } else {
                if (body != null) {
                    blockText.append(body.getText());
                }
                blockText.append(newStatementText);
            }
            blockText.append('}');
            final PsiStatement blockStatement = factory.createStatementFromText(blockText.toString(), statement);
            if (body == null) {
                loopStatement.add(blockStatement);
            } else {
                body.replace(blockStatement);
            }
        }
    }
    PsiReplacementUtil.replaceExpression((PsiExpression) element, operandText);
}
Also used : LocalSearchScope(com.intellij.psi.search.LocalSearchScope) Project(com.intellij.openapi.project.Project) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) SearchScope(com.intellij.psi.search.SearchScope) LocalSearchScope(com.intellij.psi.search.LocalSearchScope)

Example 83 with JavaCodeStyleManager

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

the class GrMainCompletionProvider method suggestVariableNames.

private static void suggestVariableNames(PsiElement context, CompletionResultSet result) {
    final PsiElement parent = context.getParent();
    if (GroovyCompletionUtil.isWildcardCompletion(context))
        return;
    if (parent instanceof GrVariable) {
        final GrVariable variable = (GrVariable) parent;
        if (context.equals(variable.getNameIdentifierGroovy())) {
            final PsiType type = variable.getTypeGroovy();
            if (type != null) {
                final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(context.getProject());
                VariableKind kind = variable instanceof GrParameter ? VariableKind.PARAMETER : variable instanceof GrField ? VariableKind.FIELD : VariableKind.LOCAL_VARIABLE;
                SuggestedNameInfo suggestedNameInfo = codeStyleManager.suggestVariableName(kind, null, null, type);
                String[] names = suggestedNameInfo.names;
                if (names.length > 0) {
                    String name = names[0];
                    String newName = InlineMethodConflictSolver.suggestNewName(name, null, parent);
                    if (!name.equals(newName)) {
                        result.addElement(LookupElementBuilder.create(newName));
                        return;
                    }
                }
                for (String name : names) {
                    result.addElement(LookupElementBuilder.create(name));
                }
            }
            GrExpression initializer = variable.getInitializerGroovy();
            if (initializer != null) {
                for (String name : GroovyNameSuggestionUtil.suggestVariableNames(initializer, new DefaultGroovyVariableNameValidator(variable), variable.hasModifierProperty(PsiModifier.STATIC))) {
                    result.addElement(LookupElementBuilder.create(name));
                }
            }
        }
    }
}
Also used : GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) GrField(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) DefaultGroovyVariableNameValidator(org.jetbrains.plugins.groovy.refactoring.DefaultGroovyVariableNameValidator) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) VariableKind(com.intellij.psi.codeStyle.VariableKind)

Example 84 with JavaCodeStyleManager

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

the class JavaCompletionSorting method getLookupObjectName.

@Nullable
private static String getLookupObjectName(Object o) {
    if (o instanceof PsiVariable) {
        final PsiVariable variable = (PsiVariable) o;
        JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(variable.getProject());
        VariableKind variableKind = codeStyleManager.getVariableKind(variable);
        return codeStyleManager.variableNameToPropertyName(variable.getName(), variableKind);
    }
    if (o instanceof PsiMethod) {
        return ((PsiMethod) o).getName();
    }
    return null;
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) VariableKind(com.intellij.psi.codeStyle.VariableKind) Nullable(org.jetbrains.annotations.Nullable)

Example 85 with JavaCodeStyleManager

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

the class JavaMemberNameCompletionContributor method completeLocalVariableName.

private static void completeLocalVariableName(Set<LookupElement> set, PrefixMatcher matcher, PsiVariable var, boolean includeOverlapped) {
    FeatureUsageTracker.getInstance().triggerFeatureUsed("editing.completion.variable.name");
    Project project = var.getProject();
    final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
    final VariableKind variableKind = codeStyleManager.getVariableKind(var);
    String propertyName = null;
    if (variableKind == VariableKind.PARAMETER) {
        final PsiMethod method = PsiTreeUtil.getParentOfType(var, PsiMethod.class);
        if (method != null) {
            propertyName = PropertyUtil.getPropertyName(method);
        }
        if (method != null && method.getName().startsWith("with")) {
            propertyName = StringUtil.decapitalize(method.getName().substring(4));
        }
    }
    final PsiType type = var.getType();
    SuggestedNameInfo suggestedNameInfo = codeStyleManager.suggestVariableName(variableKind, propertyName, null, type, StringUtil.isEmpty(matcher.getPrefix()));
    suggestedNameInfo = codeStyleManager.suggestUniqueVariableName(suggestedNameInfo, var, false);
    final String[] suggestedNames = suggestedNameInfo.names;
    addLookupItems(set, suggestedNameInfo, matcher, project, suggestedNames);
    if (!hasStartMatches(set, matcher)) {
        if (type.equalsToText(CommonClassNames.JAVA_LANG_OBJECT) && matcher.prefixMatches("object")) {
            set.add(withInsertHandler(suggestedNameInfo, LookupElementBuilder.create("object")));
        }
        if (type.equalsToText(CommonClassNames.JAVA_LANG_STRING) && matcher.prefixMatches("string")) {
            set.add(withInsertHandler(suggestedNameInfo, LookupElementBuilder.create("string")));
        }
    }
    if (!hasStartMatches(set, matcher) && includeOverlapped) {
        addLookupItems(set, null, matcher, project, getOverlappedNameVersions(matcher.getPrefix(), suggestedNames, ""));
    }
    PsiElement parent = PsiTreeUtil.getParentOfType(var, PsiCodeBlock.class);
    if (parent == null)
        parent = PsiTreeUtil.getParentOfType(var, PsiMethod.class, PsiLambdaExpression.class);
    addLookupItems(set, suggestedNameInfo, matcher, project, getUnresolvedReferences(parent, false));
    if (var instanceof PsiParameter && parent instanceof PsiMethod) {
        addSuggestionsInspiredByFieldNames(set, matcher, var, project, codeStyleManager);
    }
    PsiExpression initializer = var.getInitializer();
    if (initializer != null) {
        SuggestedNameInfo initializerSuggestions = IntroduceVariableBase.getSuggestedName(type, initializer);
        addLookupItems(set, initializerSuggestions, matcher, project, initializerSuggestions.names);
    }
}
Also used : Project(com.intellij.openapi.project.Project) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) VariableKind(com.intellij.psi.codeStyle.VariableKind)

Aggregations

JavaCodeStyleManager (com.intellij.psi.codeStyle.JavaCodeStyleManager)96 Project (com.intellij.openapi.project.Project)27 SuggestedNameInfo (com.intellij.psi.codeStyle.SuggestedNameInfo)21 VariableKind (com.intellij.psi.codeStyle.VariableKind)19 IncorrectOperationException (com.intellij.util.IncorrectOperationException)15 NotNull (org.jetbrains.annotations.NotNull)13 CodeStyleManager (com.intellij.psi.codeStyle.CodeStyleManager)12 Nullable (org.jetbrains.annotations.Nullable)12 ArrayList (java.util.ArrayList)10 NonNls (org.jetbrains.annotations.NonNls)8 StringUtil (com.intellij.openapi.util.text.StringUtil)3 UniqueNameGenerator (com.intellij.util.text.UniqueNameGenerator)3 HashSet (java.util.HashSet)3 JavaLanguage (com.intellij.lang.java.JavaLanguage)2 Logger (com.intellij.openapi.diagnostic.Logger)2 Editor (com.intellij.openapi.editor.Editor)2 Comparing (com.intellij.openapi.util.Comparing)2 com.intellij.psi (com.intellij.psi)2 CodeStyleSettings (com.intellij.psi.codeStyle.CodeStyleSettings)2 FunctionalInterfaceParameterizationUtil (com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil)2