Search in sources :

Example 61 with CodeStyleManager

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

the class ReturnSeparatedFromComputationInspection method removeElementKeepComments.

private static void removeElementKeepComments(PsiElement removedElement) {
    List<PsiComment> keptComments = getComments(removedElement);
    if (!keptComments.isEmpty()) {
        PsiComment firstComment = keptComments.get(0);
        PsiElement lastComment = removedElement.replace(firstComment);
        PsiElement parent = lastComment.getParent();
        Project project = parent.getProject();
        CodeStyleManager styleManager = CodeStyleManager.getInstance(project);
        styleManager.reformat(lastComment, true);
        if (keptComments.size() > 1) {
            for (PsiComment comment : keptComments.subList(1, keptComments.size())) {
                lastComment = parent.addAfter(comment, lastComment);
                styleManager.reformat(lastComment, true);
            }
        }
    } else {
        removedElement.delete();
    }
}
Also used : Project(com.intellij.openapi.project.Project) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager)

Example 62 with CodeStyleManager

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

the class InitializeFinalFieldInConstructorFix method addFieldInitialization.

@NotNull
private static PsiExpression addFieldInitialization(@NotNull PsiMethod constructor, @NotNull LookupElement[] suggestedInitializers, @NotNull PsiField field, @NotNull Project project) {
    PsiCodeBlock methodBody = constructor.getBody();
    if (methodBody == null) {
        //incomplete code
        CreateFromUsageUtils.setupMethodBody(constructor);
        methodBody = constructor.getBody();
        LOG.assertTrue(methodBody != null);
    }
    final String fieldName = field.getName();
    String stmtText = fieldName + " = " + suggestedInitializers[0].getPsiElement().getText() + ";";
    if (methodContainsParameterWithName(constructor, fieldName)) {
        stmtText = "this." + stmtText;
    }
    final PsiManager psiManager = PsiManager.getInstance(project);
    final PsiElementFactory factory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory();
    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
    final PsiExpressionStatement addedStatement = (PsiExpressionStatement) methodBody.add(codeStyleManager.reformat(factory.createStatementFromText(stmtText, methodBody)));
    return ObjectUtils.notNull(((PsiAssignmentExpression) addedStatement.getExpression()).getRExpression());
}
Also used : CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) NotNull(org.jetbrains.annotations.NotNull)

Example 63 with CodeStyleManager

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

the class CreateConstructorMatchingSuperFix method chooseConstructor2Delegate.

public static void chooseConstructor2Delegate(final Project project, final Editor editor, PsiSubstitutor substitutor, List<PsiMethodMember> baseConstructors, PsiMethod[] baseConstrs, final PsiClass targetClass) {
    PsiMethodMember[] constructors = baseConstructors.toArray(new PsiMethodMember[baseConstructors.size()]);
    if (constructors.length == 0) {
        constructors = new PsiMethodMember[baseConstrs.length];
        for (int i = 0; i < baseConstrs.length; i++) {
            constructors[i] = new PsiMethodMember(baseConstrs[i], substitutor);
        }
    }
    // Otherwise we won't have been messing with all this stuff
    LOG.assertTrue(constructors.length >= 1);
    boolean isCopyJavadoc = true;
    if (constructors.length > 1 && !ApplicationManager.getApplication().isUnitTestMode()) {
        MemberChooser<PsiMethodMember> chooser = new MemberChooser<>(constructors, false, true, project);
        chooser.setTitle(QuickFixBundle.message("super.class.constructors.chooser.title"));
        chooser.show();
        if (chooser.getExitCode() != DialogWrapper.OK_EXIT_CODE)
            return;
        constructors = chooser.getSelectedElements(new PsiMethodMember[0]);
        isCopyJavadoc = chooser.isCopyJavadoc();
    }
    final PsiMethodMember[] constructors1 = constructors;
    final boolean isCopyJavadoc1 = isCopyJavadoc;
    ApplicationManager.getApplication().runWriteAction(() -> {
        try {
            if (targetClass.getLBrace() == null) {
                PsiClass psiClass = JavaPsiFacade.getInstance(targetClass.getProject()).getElementFactory().createClass("X");
                targetClass.addRangeAfter(psiClass.getLBrace(), psiClass.getRBrace(), targetClass.getLastChild());
            }
            JVMElementFactory factory = JVMElementFactories.getFactory(targetClass.getLanguage(), project);
            CodeStyleManager formatter = CodeStyleManager.getInstance(project);
            PsiMethod derived = null;
            for (PsiMethodMember candidate : constructors1) {
                PsiMethod base = candidate.getElement();
                derived = GenerateMembersUtil.substituteGenericMethod(base, candidate.getSubstitutor(), targetClass);
                if (!isCopyJavadoc1) {
                    final PsiDocComment docComment = derived.getDocComment();
                    if (docComment != null) {
                        docComment.delete();
                    }
                }
                final String targetClassName = targetClass.getName();
                LOG.assertTrue(targetClassName != null, targetClass);
                derived.setName(targetClassName);
                ConstructorBodyGenerator generator = ConstructorBodyGenerator.INSTANCE.forLanguage(derived.getLanguage());
                if (generator != null) {
                    StringBuilder buffer = new StringBuilder();
                    generator.start(buffer, derived.getName(), PsiParameter.EMPTY_ARRAY);
                    generator.generateSuperCallIfNeeded(buffer, derived.getParameterList().getParameters());
                    generator.finish(buffer);
                    PsiMethod stub = factory.createMethodFromText(buffer.toString(), targetClass);
                    derived.getBody().replace(stub.getBody());
                }
                derived = (PsiMethod) formatter.reformat(derived);
                derived = (PsiMethod) JavaCodeStyleManager.getInstance(project).shortenClassReferences(derived);
                PsiGenerationInfo<PsiMethod> info = OverrideImplementUtil.createGenerationInfo(derived);
                info.insert(targetClass, null, true);
                derived = info.getPsiMember();
            }
            if (derived != null) {
                editor.getCaretModel().moveToOffset(derived.getTextRange().getStartOffset());
                editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
            }
        } catch (IncorrectOperationException e) {
            LOG.error(e);
        }
        UndoUtil.markPsiFileForUndo(targetClass.getContainingFile());
    });
}
Also used : PsiDocComment(com.intellij.psi.javadoc.PsiDocComment) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) MemberChooser(com.intellij.ide.util.MemberChooser) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 64 with CodeStyleManager

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

the class CreateFromUsageUtils method setupMethodBody.

public static void setupMethodBody(final PsiMethod method, final PsiClass aClass, final FileTemplate template) throws IncorrectOperationException {
    PsiType returnType = method.getReturnType();
    if (returnType == null) {
        returnType = PsiType.VOID;
    }
    JVMElementFactory factory = JVMElementFactories.getFactory(aClass.getLanguage(), aClass.getProject());
    LOG.assertTrue(!aClass.isInterface() || PsiUtil.isLanguageLevel8OrHigher(method) || method.getLanguage() != JavaLanguage.INSTANCE, "Interface bodies should be already set up");
    FileType fileType = FileTypeManager.getInstance().getFileTypeByExtension(template.getExtension());
    Properties properties = new Properties();
    properties.setProperty(FileTemplate.ATTRIBUTE_RETURN_TYPE, returnType.getPresentableText());
    properties.setProperty(FileTemplate.ATTRIBUTE_DEFAULT_RETURN_VALUE, PsiTypesUtil.getDefaultValueOfType(returnType));
    JavaTemplateUtil.setClassAndMethodNameProperties(properties, aClass, method);
    @NonNls String methodText;
    CodeStyleManager csManager = CodeStyleManager.getInstance(method.getProject());
    try {
        String bodyText = template.getText(properties);
        if (!bodyText.isEmpty())
            bodyText += "\n";
        methodText = returnType.getPresentableText() + " foo () {\n" + bodyText + "}";
        methodText = FileTemplateUtil.indent(methodText, method.getProject(), fileType);
    } catch (ProcessCanceledException e) {
        throw e;
    } catch (Exception e) {
        throw new IncorrectOperationException("Failed to parse file template", (Throwable) e);
    }
    if (methodText != null) {
        PsiMethod m;
        try {
            m = factory.createMethodFromText(methodText, aClass);
        } catch (IncorrectOperationException e) {
            ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog(QuickFixBundle.message("new.method.body.template.error.text"), QuickFixBundle.message("new.method.body.template.error.title")));
            return;
        }
        PsiCodeBlock oldBody = method.getBody();
        PsiCodeBlock newBody = m.getBody();
        LOG.assertTrue(newBody != null);
        if (oldBody != null) {
            oldBody.replace(newBody);
        } else {
            method.addBefore(newBody, null);
        }
        csManager.reformat(method);
    }
}
Also used : NonNls(org.jetbrains.annotations.NonNls) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) IncorrectOperationException(com.intellij.util.IncorrectOperationException) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) FileType(com.intellij.openapi.fileTypes.FileType) IncorrectOperationException(com.intellij.util.IncorrectOperationException) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Example 65 with CodeStyleManager

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

the class ReplaceIteratorForEachLoopWithIteratorForLoopFix method invoke.

@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
    final PsiExpression iteratedValue = myStatement.getIteratedValue();
    if (iteratedValue == null) {
        return;
    }
    final PsiType iteratedValueType = iteratedValue.getType();
    if (iteratedValueType == null) {
        return;
    }
    final PsiParameter iterationParameter = myStatement.getIterationParameter();
    final String iterationParameterName = iterationParameter.getName();
    if (iterationParameterName == null) {
        return;
    }
    final PsiStatement forEachBody = myStatement.getBody();
    final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();
    final JavaCodeStyleManager javaStyleManager = JavaCodeStyleManager.getInstance(project);
    final String name = javaStyleManager.suggestUniqueVariableName("it", myStatement, true);
    PsiForStatement newForLoop = (PsiForStatement) elementFactory.createStatementFromText("for (Iterator " + name + " = initializer; " + name + ".hasNext();) { Object next = " + name + ".next(); }", myStatement);
    final PsiDeclarationStatement newDeclaration = (PsiDeclarationStatement) newForLoop.getInitialization();
    if (newDeclaration == null)
        return;
    final PsiLocalVariable newIteratorVariable = (PsiLocalVariable) newDeclaration.getDeclaredElements()[0];
    final PsiTypeElement newIteratorTypeElement = elementFactory.createTypeElement(iteratedValueType);
    newIteratorVariable.getTypeElement().replace(newIteratorTypeElement);
    newIteratorVariable.setInitializer(iteratedValue);
    final PsiBlockStatement newBody = (PsiBlockStatement) newForLoop.getBody();
    if (newBody == null)
        return;
    final PsiCodeBlock newBodyBlock = newBody.getCodeBlock();
    final PsiDeclarationStatement newFirstStatement = (PsiDeclarationStatement) newBodyBlock.getStatements()[0];
    final PsiLocalVariable newItemVariable = (PsiLocalVariable) newFirstStatement.getDeclaredElements()[0];
    final PsiTypeElement newItemTypeElement = elementFactory.createTypeElement(iterationParameter.getType());
    newItemVariable.getTypeElement().replace(newItemTypeElement);
    newItemVariable.setName(iterationParameterName);
    final CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(project);
    if (codeStyleSettings.GENERATE_FINAL_LOCALS) {
        final PsiModifierList modifierList = newItemVariable.getModifierList();
        if (modifierList != null)
            modifierList.setModifierProperty(PsiModifier.FINAL, true);
    }
    final CodeStyleManager styleManager = CodeStyleManager.getInstance(project);
    newForLoop = (PsiForStatement) javaStyleManager.shortenClassReferences(newForLoop);
    newForLoop = (PsiForStatement) styleManager.reformat(newForLoop);
    if (forEachBody instanceof PsiBlockStatement) {
        final PsiCodeBlock bodyCodeBlock = ((PsiBlockStatement) forEachBody).getCodeBlock();
        final PsiElement firstBodyElement = bodyCodeBlock.getFirstBodyElement();
        final PsiElement lastBodyElement = bodyCodeBlock.getLastBodyElement();
        if (firstBodyElement != null && lastBodyElement != null) {
            newBodyBlock.addRangeAfter(firstBodyElement, lastBodyElement, newFirstStatement);
        }
    } else if (forEachBody != null && !(forEachBody instanceof PsiEmptyStatement)) {
        newBodyBlock.addAfter(forEachBody, newFirstStatement);
    }
    myStatement.replace(newForLoop);
}
Also used : CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleSettings(com.intellij.psi.codeStyle.CodeStyleSettings) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager)

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