Search in sources :

Example 21 with CodeStyleManager

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

the class OverrideImplementUtil method decorateMethod.

private static PsiMethod decorateMethod(PsiClass aClass, PsiMethod method, boolean toCopyJavaDoc, boolean insertOverrideIfPossible, PsiMethod result) {
    PsiUtil.setModifierProperty(result, PsiModifier.ABSTRACT, aClass.isInterface() && method.hasModifierProperty(PsiModifier.ABSTRACT));
    PsiUtil.setModifierProperty(result, PsiModifier.NATIVE, false);
    if (!toCopyJavaDoc) {
        deleteDocComment(result);
    }
    //method type params are not allowed when overriding from raw type
    final PsiTypeParameterList list = result.getTypeParameterList();
    if (list != null) {
        final PsiClass containingClass = method.getContainingClass();
        if (containingClass != null) {
            for (PsiClassType classType : aClass.getSuperTypes()) {
                if (InheritanceUtil.isInheritorOrSelf(PsiUtil.resolveClassInType(classType), containingClass, true) && classType.isRaw()) {
                    list.replace(JavaPsiFacade.getElementFactory(aClass.getProject()).createTypeParameterList());
                    break;
                }
            }
        }
    }
    annotateOnOverrideImplement(result, aClass, method, insertOverrideIfPossible);
    if (CodeStyleSettingsManager.getSettings(aClass.getProject()).REPEAT_SYNCHRONIZED && method.hasModifierProperty(PsiModifier.SYNCHRONIZED)) {
        result.getModifierList().setModifierProperty(PsiModifier.SYNCHRONIZED, true);
    }
    final PsiCodeBlock body = JavaPsiFacade.getInstance(method.getProject()).getElementFactory().createCodeBlockFromText("{}", null);
    PsiCodeBlock oldBody = result.getBody();
    if (oldBody != null) {
        oldBody.replace(body);
    } else {
        result.add(body);
    }
    setupMethodBody(result, method, aClass);
    // probably, it's better to reformat the whole method - it can go from other style sources
    final Project project = method.getProject();
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
    CommonCodeStyleSettings javaSettings = CodeStyleSettingsManager.getSettings(project).getCommonSettings(JavaLanguage.INSTANCE);
    boolean keepBreaks = javaSettings.KEEP_LINE_BREAKS;
    javaSettings.KEEP_LINE_BREAKS = false;
    result = (PsiMethod) JavaCodeStyleManager.getInstance(project).shortenClassReferences(result);
    result = (PsiMethod) codeStyleManager.reformat(result);
    javaSettings.KEEP_LINE_BREAKS = keepBreaks;
    return result;
}
Also used : Project(com.intellij.openapi.project.Project) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) CommonCodeStyleSettings(com.intellij.psi.codeStyle.CommonCodeStyleSettings)

Example 22 with CodeStyleManager

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

the class GenerateConstructorHandler method generateConstructorPrototype.

public static PsiMethod generateConstructorPrototype(PsiClass aClass, PsiMethod baseConstructor, boolean copyJavaDoc, PsiField[] fields) throws IncorrectOperationException {
    PsiManager manager = aClass.getManager();
    Project project = aClass.getProject();
    JVMElementFactory factory = JVMElementFactories.requireFactory(aClass.getLanguage(), project);
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());
    String className = aClass.getName();
    assert className != null : aClass;
    PsiMethod constructor = factory.createConstructor(className, aClass);
    GenerateMembersUtil.setVisibility(aClass, constructor);
    if (baseConstructor != null) {
        PsiJavaCodeReferenceElement[] throwRefs = baseConstructor.getThrowsList().getReferenceElements();
        for (PsiJavaCodeReferenceElement ref : throwRefs) {
            constructor.getThrowsList().add(ref);
        }
        if (copyJavaDoc) {
            final PsiDocComment docComment = ((PsiMethod) baseConstructor.getNavigationElement()).getDocComment();
            if (docComment != null) {
                constructor.addAfter(docComment, null);
            }
        }
    }
    boolean isNotEnum = false;
    if (baseConstructor != null) {
        PsiClass superClass = aClass.getSuperClass();
        LOG.assertTrue(superClass != null);
        if (!CommonClassNames.JAVA_LANG_ENUM.equals(superClass.getQualifiedName())) {
            isNotEnum = true;
            if (baseConstructor instanceof PsiCompiledElement) {
                // to get some parameter names
                PsiClass dummyClass = JVMElementFactories.requireFactory(baseConstructor.getLanguage(), project).createClass("Dummy");
                baseConstructor = (PsiMethod) dummyClass.add(baseConstructor);
            }
            PsiParameter[] params = baseConstructor.getParameterList().getParameters();
            for (PsiParameter param : params) {
                String name = param.getName();
                assert name != null : param;
                PsiParameter newParam = factory.createParameter(name, param.getType(), aClass);
                GenerateMembersUtil.copyOrReplaceModifierList(param, aClass, newParam);
                constructor.getParameterList().add(newParam);
            }
        }
    }
    JavaCodeStyleManager javaStyle = JavaCodeStyleManager.getInstance(project);
    final PsiMethod dummyConstructor = factory.createConstructor(className);
    dummyConstructor.getParameterList().replace(constructor.getParameterList().copy());
    List<PsiParameter> fieldParams = new ArrayList<>();
    for (PsiField field : fields) {
        String fieldName = field.getName();
        assert fieldName != null : field;
        String name = javaStyle.variableNameToPropertyName(fieldName, VariableKind.FIELD);
        String parmName = javaStyle.propertyNameToVariableName(name, VariableKind.PARAMETER);
        parmName = javaStyle.suggestUniqueVariableName(parmName, dummyConstructor, true);
        PsiParameter parm = factory.createParameter(parmName, field.getType(), aClass);
        NullableNotNullManager.getInstance(project).copyNotNullAnnotation(field, parm);
        if (constructor.isVarArgs()) {
            final PsiParameterList parameterList = constructor.getParameterList();
            parameterList.addBefore(parm, parameterList.getParameters()[parameterList.getParametersCount() - 1]);
            final PsiParameterList dummyParameterList = dummyConstructor.getParameterList();
            dummyParameterList.addBefore(parm.copy(), dummyParameterList.getParameters()[dummyParameterList.getParametersCount() - 1]);
        } else {
            constructor.getParameterList().add(parm);
            dummyConstructor.getParameterList().add(parm.copy());
        }
        fieldParams.add(parm);
    }
    ConstructorBodyGenerator generator = ConstructorBodyGenerator.INSTANCE.forLanguage(aClass.getLanguage());
    if (generator != null) {
        StringBuilder buffer = new StringBuilder();
        generator.start(buffer, constructor.getName(), PsiParameter.EMPTY_ARRAY);
        if (isNotEnum) {
            generator.generateSuperCallIfNeeded(buffer, baseConstructor.getParameterList().getParameters());
        }
        final PsiParameter[] parameters = fieldParams.toArray(new PsiParameter[fieldParams.size()]);
        final List<String> existingNames = ContainerUtil.map(dummyConstructor.getParameterList().getParameters(), parameter -> parameter.getName());
        if (generator instanceof ConstructorBodyGeneratorEx) {
            ((ConstructorBodyGeneratorEx) generator).generateFieldInitialization(buffer, fields, parameters, existingNames);
        } else {
            generator.generateFieldInitialization(buffer, fields, parameters);
        }
        generator.finish(buffer);
        PsiMethod stub = factory.createMethodFromText(buffer.toString(), aClass);
        PsiCodeBlock original = constructor.getBody(), replacement = stub.getBody();
        assert original != null : constructor;
        assert replacement != null : stub;
        original.replace(replacement);
    }
    constructor = (PsiMethod) codeStyleManager.reformat(constructor);
    return constructor;
}
Also used : PsiDocComment(com.intellij.psi.javadoc.PsiDocComment) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) ArrayList(java.util.ArrayList) Project(com.intellij.openapi.project.Project) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager)

Example 23 with CodeStyleManager

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

the class JavaWithNotInstanceofSurrounder method surroundExpression.

@Override
public TextRange surroundExpression(Project project, Editor editor, PsiExpression expr) throws IncorrectOperationException {
    PsiManager manager = expr.getManager();
    PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
    PsiPrefixExpression prefixExpr = (PsiPrefixExpression) factory.createExpressionFromText("!(a instanceof Type)", null);
    prefixExpr = (PsiPrefixExpression) codeStyleManager.reformat(prefixExpr);
    PsiParenthesizedExpression parenthExpr = (PsiParenthesizedExpression) prefixExpr.getOperand();
    PsiInstanceOfExpression instanceofExpr = (PsiInstanceOfExpression) parenthExpr.getExpression();
    instanceofExpr.getOperand().replace(expr);
    prefixExpr = (PsiPrefixExpression) expr.replace(prefixExpr);
    parenthExpr = (PsiParenthesizedExpression) prefixExpr.getOperand();
    instanceofExpr = (PsiInstanceOfExpression) parenthExpr.getExpression();
    instanceofExpr = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(instanceofExpr);
    TextRange range = instanceofExpr.getCheckType().getTextRange();
    editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
    return new TextRange(range.getStartOffset(), range.getStartOffset());
}
Also used : CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) TextRange(com.intellij.openapi.util.TextRange)

Example 24 with CodeStyleManager

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

the class JavaWithRunnableSurrounder method surroundStatements.

@Override
public TextRange surroundStatements(Project project, final Editor editor, PsiElement container, PsiElement[] statements) throws IncorrectOperationException {
    PsiManager manager = container.getManager();
    PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
    final String baseName = "runnable";
    final String uniqueName = JavaCodeStyleManager.getInstance(project).suggestUniqueVariableName(baseName, container, false);
    @NonNls String text = "Runnable runnable = new Runnable(){\npublic void run(){\n}};";
    PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement) factory.createStatementFromText(text, null);
    declarationStatement = (PsiDeclarationStatement) codeStyleManager.reformat(declarationStatement);
    declarationStatement = (PsiDeclarationStatement) container.addAfter(declarationStatement, statements[statements.length - 1]);
    final PsiVariable variable = (PsiVariable) declarationStatement.getDeclaredElements()[0];
    if (!Comparing.strEqual(uniqueName, baseName)) {
        variable.setName(uniqueName);
    }
    PsiNewExpression newExpression = (PsiNewExpression) variable.getInitializer();
    PsiElement[] children = newExpression.getChildren();
    PsiAnonymousClass anonymousClass = (PsiAnonymousClass) children[children.length - 1];
    PsiMethod method = anonymousClass.getMethods()[0];
    PsiCodeBlock body = method.getBody();
    body.addRange(statements[0], statements[statements.length - 1]);
    container.deleteChildRange(statements[0], statements[statements.length - 1]);
    makeVariablesFinal(body, body);
    final int textOffset = variable.getNameIdentifier().getTextOffset();
    PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument());
    editor.getCaretModel().moveToOffset(textOffset);
    editor.getSelectionModel().removeSelection();
    new VariableInplaceRenamer(variable, editor) {

        @Override
        protected boolean shouldSelectAll() {
            return true;
        }

        @Override
        protected void moveOffsetAfter(boolean success) {
            super.moveOffsetAfter(success);
            if (success) {
                final PsiNamedElement renamedVariable = getVariable();
                if (renamedVariable != null) {
                    editor.getCaretModel().moveToOffset(renamedVariable.getTextRange().getEndOffset());
                }
            }
        }
    }.performInplaceRename();
    return null;
}
Also used : NonNls(org.jetbrains.annotations.NonNls) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) VariableInplaceRenamer(com.intellij.refactoring.rename.inplace.VariableInplaceRenamer)

Example 25 with CodeStyleManager

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

the class JavaWithSynchronizedSurrounder method surroundStatements.

@Override
public TextRange surroundStatements(Project project, Editor editor, PsiElement container, PsiElement[] statements) throws IncorrectOperationException {
    PsiManager manager = PsiManager.getInstance(project);
    PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
    statements = SurroundWithUtil.moveDeclarationsOut(container, statements, false);
    if (statements.length == 0) {
        return null;
    }
    @NonNls String text = "synchronized(a){\n}";
    PsiSynchronizedStatement synchronizedStatement = (PsiSynchronizedStatement) factory.createStatementFromText(text, null);
    synchronizedStatement = (PsiSynchronizedStatement) codeStyleManager.reformat(synchronizedStatement);
    synchronizedStatement = (PsiSynchronizedStatement) container.addAfter(synchronizedStatement, statements[statements.length - 1]);
    PsiCodeBlock synchronizedBlock = synchronizedStatement.getBody();
    if (synchronizedBlock == null) {
        return null;
    }
    SurroundWithUtil.indentCommentIfNecessary(synchronizedBlock, statements);
    synchronizedBlock.addRange(statements[0], statements[statements.length - 1]);
    container.deleteChildRange(statements[0], statements[statements.length - 1]);
    synchronizedStatement = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(synchronizedStatement);
    PsiExpression lockExpression = synchronizedStatement.getLockExpression();
    if (lockExpression == null) {
        return null;
    }
    TextRange range = lockExpression.getTextRange();
    editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
    return new TextRange(range.getStartOffset(), range.getStartOffset());
}
Also used : NonNls(org.jetbrains.annotations.NonNls) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) TextRange(com.intellij.openapi.util.TextRange)

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