Search in sources :

Example 91 with CodeStyleManager

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

the class JavaWithNotSurrounder 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)", null);
    prefixExpr = (PsiPrefixExpression) codeStyleManager.reformat(prefixExpr);
    ((PsiParenthesizedExpression) prefixExpr.getOperand()).getExpression().replace(expr);
    expr = (PsiExpression) IntroduceVariableBase.replace(expr, prefixExpr, project);
    int offset = expr.getTextRange().getEndOffset();
    return new TextRange(offset, offset);
}
Also used : CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) TextRange(com.intellij.openapi.util.TextRange)

Example 92 with CodeStyleManager

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

the class JavaWithNullCheckSurrounder 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);
    @NonNls String text = "if(a != null){\nst;\n}";
    PsiIfStatement ifStatement = (PsiIfStatement) factory.createStatementFromText(text, null);
    ifStatement = (PsiIfStatement) codeStyleManager.reformat(ifStatement);
    ((PsiBinaryExpression) ifStatement.getCondition()).getLOperand().replace(expr);
    PsiExpressionStatement statement = PsiTreeUtil.getParentOfType(expr, PsiExpressionStatement.class);
    String oldText = statement.getText();
    ifStatement = (PsiIfStatement) statement.replace(ifStatement);
    PsiCodeBlock block = ((PsiBlockStatement) ifStatement.getThenBranch()).getCodeBlock();
    block = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(block);
    PsiElement replace = block.getStatements()[0].replace(factory.createStatementFromText(oldText, block));
    int offset = replace.getTextRange().getEndOffset();
    return new TextRange(offset, offset);
}
Also used : NonNls(org.jetbrains.annotations.NonNls) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) TextRange(com.intellij.openapi.util.TextRange)

Example 93 with CodeStyleManager

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

the class JavaWithParenthesesSurrounder 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);
    PsiParenthesizedExpression parenthExpr = (PsiParenthesizedExpression) factory.createExpressionFromText("(a)", null);
    parenthExpr = (PsiParenthesizedExpression) codeStyleManager.reformat(parenthExpr);
    parenthExpr.getExpression().replace(expr);
    expr = (PsiExpression) IntroduceVariableBase.replace(expr, parenthExpr, project);
    int offset = expr.getTextRange().getEndOffset();
    return new TextRange(offset, offset);
}
Also used : CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) TextRange(com.intellij.openapi.util.TextRange)

Example 94 with CodeStyleManager

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

the class JavaWithTryFinallySurrounder 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 = "try{\n}finally{\n\n}";
    PsiTryStatement tryStatement = (PsiTryStatement) factory.createStatementFromText(text, null);
    tryStatement = (PsiTryStatement) codeStyleManager.reformat(tryStatement);
    tryStatement = (PsiTryStatement) container.addAfter(tryStatement, statements[statements.length - 1]);
    PsiCodeBlock tryBlock = tryStatement.getTryBlock();
    if (tryBlock == null) {
        return null;
    }
    SurroundWithUtil.indentCommentIfNecessary(tryBlock, statements);
    tryBlock.addRange(statements[0], statements[statements.length - 1]);
    container.deleteChildRange(statements[0], statements[statements.length - 1]);
    PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock();
    if (finallyBlock == null) {
        return null;
    }
    Document document = editor.getDocument();
    PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document);
    TextRange finallyBlockRange = finallyBlock.getTextRange();
    int newLineOffset = finallyBlockRange.getStartOffset() + 2;
    editor.getCaretModel().moveToOffset(newLineOffset);
    editor.getSelectionModel().removeSelection();
    CodeStyleManager.getInstance(project).adjustLineIndent(document, newLineOffset);
    PsiDocumentManager.getInstance(project).commitDocument(document);
    return new TextRange(editor.getCaretModel().getOffset(), editor.getCaretModel().getOffset());
}
Also used : NonNls(org.jetbrains.annotations.NonNls) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) TextRange(com.intellij.openapi.util.TextRange) Document(com.intellij.openapi.editor.Document)

Example 95 with CodeStyleManager

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

the class ImportHelper method prepareOptimizeImportsResult.

@Nullable("null means no need to replace the import list because they are the same")
PsiImportList prepareOptimizeImportsResult(@NotNull final PsiJavaFile file) {
    PsiImportList oldList = file.getImportList();
    if (oldList == null)
        return null;
    // Java parser works in a way that comments may be included to the import list, e.g.:
    //     import a;
    //     /* comment */
    //     import b;
    // We want to preserve those comments then.
    List<PsiElement> nonImports = new ArrayList<>();
    // Note: this array may contain "<packageOrClassName>.*" for unresolved imports!
    List<Pair<String, Boolean>> names = new ArrayList<>(collectNamesToImport(file, nonImports));
    Collections.sort(names, Comparator.comparing(o -> o.getFirst()));
    List<Pair<String, Boolean>> resultList = sortItemsAccordingToSettings(names, mySettings);
    final Map<String, Boolean> classesOrPackagesToImportOnDemand = new THashMap<>();
    collectOnDemandImports(resultList, mySettings, classesOrPackagesToImportOnDemand);
    MultiMap<String, String> conflictingMemberNames = new MultiMap<>();
    for (Pair<String, Boolean> pair : resultList) {
        if (pair.second) {
            conflictingMemberNames.putValue(StringUtil.getShortName(pair.first), StringUtil.getPackageName(pair.first));
        }
    }
    for (String methodName : conflictingMemberNames.keySet()) {
        Collection<String> collection = conflictingMemberNames.get(methodName);
        if (!classesOrPackagesToImportOnDemand.keySet().containsAll(collection)) {
            for (String name : collection) {
                classesOrPackagesToImportOnDemand.remove(name);
            }
        }
    }
    Set<String> classesToUseSingle = findSingleImports(file, resultList, classesOrPackagesToImportOnDemand.keySet());
    Set<String> toReimport = new THashSet<>();
    calcClassesConflictingViaOnDemandImports(file, classesOrPackagesToImportOnDemand, file.getResolveScope(), toReimport);
    classesToUseSingle.addAll(toReimport);
    try {
        StringBuilder text = buildImportListText(resultList, classesOrPackagesToImportOnDemand.keySet(), classesToUseSingle);
        for (PsiElement nonImport : nonImports) {
            text.append("\n").append(nonImport.getText());
        }
        String ext = StdFileTypes.JAVA.getDefaultExtension();
        PsiFileFactory factory = PsiFileFactory.getInstance(file.getProject());
        final PsiJavaFile dummyFile = (PsiJavaFile) factory.createFileFromText("_Dummy_." + ext, StdFileTypes.JAVA, text);
        CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(file.getProject());
        codeStyleManager.reformat(dummyFile);
        PsiImportList newImportList = dummyFile.getImportList();
        assert newImportList != null : dummyFile.getText();
        PsiImportList result = (PsiImportList) newImportList.copy();
        if (oldList.isReplaceEquivalent(result))
            return null;
        if (!nonImports.isEmpty()) {
            PsiElement firstPrevious = newImportList.getPrevSibling();
            while (firstPrevious != null && firstPrevious.getPrevSibling() != null) {
                firstPrevious = firstPrevious.getPrevSibling();
            }
            for (PsiElement element = firstPrevious; element != null && element != newImportList; element = element.getNextSibling()) {
                result.add(element.copy());
            }
            for (PsiElement element = newImportList.getNextSibling(); element != null; element = element.getNextSibling()) {
                result.add(element.copy());
            }
        }
        return result;
    } catch (IncorrectOperationException e) {
        LOG.error(e);
        return null;
    }
}
Also used : ImportFilter(com.intellij.codeInsight.ImportFilter) java.util(java.util) ArrayUtil(com.intellij.util.ArrayUtil) IElementType(com.intellij.psi.tree.IElementType) TObjectIntHashMap(gnu.trove.TObjectIntHashMap) NonNls(org.jetbrains.annotations.NonNls) THashSet(gnu.trove.THashSet) PackageEntry(com.intellij.psi.codeStyle.PackageEntry) ContainerUtil(com.intellij.util.containers.ContainerUtil) THashMap(gnu.trove.THashMap) TObjectIntProcedure(gnu.trove.TObjectIntProcedure) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) Comparing(com.intellij.openapi.util.Comparing) JavaJspElementType(com.intellij.psi.impl.source.tree.JavaJspElementType) Project(com.intellij.openapi.project.Project) Logger(com.intellij.openapi.diagnostic.Logger) CodeStyleSettings(com.intellij.psi.codeStyle.CodeStyleSettings) JavaClassReference(com.intellij.psi.impl.source.resolve.reference.impl.providers.JavaClassReference) JspFile(com.intellij.psi.jsp.JspFile) JavaLanguage(com.intellij.lang.java.JavaLanguage) MultiMap(com.intellij.util.containers.MultiMap) Collectors.toSet(java.util.stream.Collectors.toSet) SourceTreeToPsiMap(com.intellij.psi.impl.source.SourceTreeToPsiMap) ReferencesSearch(com.intellij.psi.search.searches.ReferencesSearch) JspSpiUtil(com.intellij.psi.jsp.JspSpiUtil) StdFileTypes(com.intellij.openapi.fileTypes.StdFileTypes) IncorrectOperationException(com.intellij.util.IncorrectOperationException) StringUtil(com.intellij.openapi.util.text.StringUtil) PsiJavaCodeReferenceElementImpl(com.intellij.psi.impl.source.PsiJavaCodeReferenceElementImpl) JspxImportStatement(com.intellij.psi.impl.source.jsp.jspJava.JspxImportStatement) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) PackageEntryTable(com.intellij.psi.codeStyle.PackageEntryTable) Collectors(java.util.stream.Collectors) ASTNode(com.intellij.lang.ASTNode) Nullable(org.jetbrains.annotations.Nullable) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) ElementType(com.intellij.psi.impl.source.tree.ElementType) ClassUtil(com.intellij.psi.util.ClassUtil) Pair(com.intellij.openapi.util.Pair) ObjectUtils(com.intellij.util.ObjectUtils) com.intellij.psi(com.intellij.psi) NotNull(org.jetbrains.annotations.NotNull) ResolveClassUtil(com.intellij.psi.impl.source.resolve.ResolveClassUtil) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) THashSet(gnu.trove.THashSet) MultiMap(com.intellij.util.containers.MultiMap) THashMap(gnu.trove.THashMap) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Pair(com.intellij.openapi.util.Pair) Nullable(org.jetbrains.annotations.Nullable)

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