Search in sources :

Example 66 with CodeStyleManager

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

the class ReplaceWithListAccessFix method invoke.

@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
    final PsiExpression arrayExpression = myArrayAccessExpression.getArrayExpression();
    final PsiExpression indexExpression = myArrayAccessExpression.getIndexExpression();
    if (indexExpression == null)
        return;
    final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
    final PsiElement parent = myArrayAccessExpression.getParent();
    if (parent instanceof PsiAssignmentExpression) {
        final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression) parent;
        final PsiExpression lExpression = assignmentExpression.getLExpression();
        final PsiExpression rExpression = assignmentExpression.getRExpression();
        if (lExpression.equals(myArrayAccessExpression) && parent.getParent() instanceof PsiExpressionStatement && rExpression != null) {
            replaceWithSet(factory, codeStyleManager, arrayExpression, indexExpression, rExpression, assignmentExpression);
            return;
        }
    }
    replaceWithGet(factory, codeStyleManager, arrayExpression, indexExpression, myArrayAccessExpression);
}
Also used : CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager)

Example 67 with CodeStyleManager

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

the class ExtractClassProcessor method buildDelegate.

private void buildDelegate() {
    final PsiManager manager = sourceClass.getManager();
    final PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());
    @NonNls final StringBuilder fieldBuffer = new StringBuilder();
    final String delegateVisibility = calculateDelegateVisibility();
    if (delegateVisibility.length() > 0)
        fieldBuffer.append(delegateVisibility).append(' ');
    fieldBuffer.append("final ");
    final String fullyQualifiedName = getQualifiedName();
    fieldBuffer.append(fullyQualifiedName);
    if (!typeParams.isEmpty()) {
        fieldBuffer.append('<');
        for (PsiTypeParameter typeParameter : typeParams) {
            fieldBuffer.append(typeParameter.getName());
        }
        fieldBuffer.append('>');
    }
    fieldBuffer.append(' ');
    fieldBuffer.append(delegateFieldName);
    fieldBuffer.append(" = new ").append(fullyQualifiedName);
    if (!typeParams.isEmpty()) {
        fieldBuffer.append('<');
        for (PsiTypeParameter typeParameter : typeParams) {
            fieldBuffer.append(typeParameter.getName());
        }
        fieldBuffer.append('>');
    }
    fieldBuffer.append('(');
    if (requiresBackpointer) {
        fieldBuffer.append("this");
    }
    fieldBuffer.append(");");
    try {
        final String fieldString = fieldBuffer.toString();
        final PsiField field = factory.createFieldFromText(fieldString, sourceClass);
        final PsiElement newField = sourceClass.add(field);
        codeStyleManager.reformat(JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(newField));
    } catch (IncorrectOperationException e) {
        logger.error(e);
    }
}
Also used : NonNls(org.jetbrains.annotations.NonNls) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 68 with CodeStyleManager

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

the class ExtractClassProcessor method buildClass.

private PsiClass buildClass(boolean normalizeDeclaration) {
    final PsiManager manager = sourceClass.getManager();
    final Project project = sourceClass.getProject();
    final ExtractedClassBuilder extractedClassBuilder = new ExtractedClassBuilder();
    extractedClassBuilder.setProject(myProject);
    extractedClassBuilder.setClassName(newClassName);
    extractedClassBuilder.setPackageName(newPackageName);
    extractedClassBuilder.setOriginalClassName(sourceClass.getQualifiedName());
    extractedClassBuilder.setRequiresBackPointer(requiresBackpointer);
    extractedClassBuilder.setExtractAsEnum(enumConstants);
    for (PsiField field : fields) {
        extractedClassBuilder.addField(field);
    }
    for (PsiMethod method : methods) {
        extractedClassBuilder.addMethod(method);
    }
    for (PsiClass innerClass : innerClasses) {
        extractedClassBuilder.addInnerClass(innerClass, innerClassesToMakePublic.contains(innerClass));
    }
    extractedClassBuilder.setTypeArguments(typeParams);
    final List<PsiClass> interfaces = calculateInterfacesSupported();
    extractedClassBuilder.setInterfaces(interfaces);
    if (myGenerateAccessors) {
        final NecessaryAccessorsVisitor visitor = checkNecessaryGettersSetters4ExtractedClass();
        sourceClass.accept(visitor);
        extractedClassBuilder.setFieldsNeedingGetters(visitor.getFieldsNeedingGetter());
        extractedClassBuilder.setFieldsNeedingSetters(visitor.getFieldsNeedingSetter());
    }
    final String classString = extractedClassBuilder.buildBeanClass(normalizeDeclaration);
    if (extractInnerClass) {
        final PsiFileFactory factory = PsiFileFactory.getInstance(project);
        final PsiJavaFile newFile = (PsiJavaFile) factory.createFileFromText(newClassName + ".java", JavaFileType.INSTANCE, classString);
        final PsiClass psiClass = newFile.getClasses()[0];
        if (!psiClass.isEnum()) {
            final PsiModifierList modifierList = psiClass.getModifierList();
            assert modifierList != null;
            modifierList.setModifierProperty(PsiModifier.STATIC, true);
        }
        final PsiElement addedClass = sourceClass.add(psiClass);
        return (PsiClass) CodeStyleManager.getInstance(manager).reformat(JavaCodeStyleManager.getInstance(project).shortenClassReferences(addedClass));
    }
    try {
        final PsiFile containingFile = sourceClass.getContainingFile();
        final PsiDirectory directory;
        final PsiDirectory containingDirectory = containingFile.getContainingDirectory();
        if (myMoveDestination != null) {
            directory = myMoveDestination.getTargetDirectory(containingDirectory);
        } else {
            final Module module = ModuleUtil.findModuleForPsiElement(containingFile);
            assert module != null;
            directory = PackageUtil.findOrCreateDirectoryForPackage(module, newPackageName, containingDirectory, false, true);
        }
        if (directory != null) {
            final PsiFileFactory factory = PsiFileFactory.getInstance(project);
            final PsiFile newFile = factory.createFileFromText(newClassName + ".java", JavaFileType.INSTANCE, classString);
            final PsiElement addedFile = directory.add(newFile);
            final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());
            final PsiElement shortenedFile = JavaCodeStyleManager.getInstance(project).shortenClassReferences(addedFile);
            return ((PsiJavaFile) codeStyleManager.reformat(shortenedFile)).getClasses()[0];
        } else {
            return null;
        }
    } catch (IncorrectOperationException e) {
        return null;
    }
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) Project(com.intellij.openapi.project.Project) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Module(com.intellij.openapi.module.Module)

Example 69 with CodeStyleManager

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

the class EndHandler method doExecute.

@Override
protected void doExecute(final Editor editor, Caret caret, DataContext dataContext) {
    CodeInsightSettings settings = CodeInsightSettings.getInstance();
    if (!settings.SMART_END_ACTION) {
        if (myOriginalHandler != null) {
            myOriginalHandler.execute(editor, caret, dataContext);
        }
        return;
    }
    final Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(editor.getComponent()));
    if (project == null) {
        if (myOriginalHandler != null) {
            myOriginalHandler.execute(editor, caret, dataContext);
        }
        return;
    }
    final Document document = editor.getDocument();
    final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
    if (file == null) {
        if (myOriginalHandler != null) {
            myOriginalHandler.execute(editor, caret, dataContext);
        }
        return;
    }
    final EditorNavigationDelegate[] extensions = EditorNavigationDelegate.EP_NAME.getExtensions();
    for (EditorNavigationDelegate delegate : extensions) {
        if (delegate.navigateToLineEnd(editor, dataContext) == EditorNavigationDelegate.Result.STOP) {
            return;
        }
    }
    final CaretModel caretModel = editor.getCaretModel();
    final int caretOffset = caretModel.getOffset();
    CharSequence chars = editor.getDocument().getCharsSequence();
    int length = editor.getDocument().getTextLength();
    if (caretOffset < length) {
        final int offset1 = CharArrayUtil.shiftBackward(chars, caretOffset - 1, " \t");
        if (offset1 < 0 || chars.charAt(offset1) == '\n' || chars.charAt(offset1) == '\r') {
            final int offset2 = CharArrayUtil.shiftForward(chars, offset1 + 1, " \t");
            boolean isEmptyLine = offset2 >= length || chars.charAt(offset2) == '\n' || chars.charAt(offset2) == '\r';
            if (isEmptyLine) {
                // There is a possible case that indent string is not calculated for particular document (that is true at least for plain text
                // documents). Hence, we check that and don't finish processing in case we have such a situation.
                boolean stopProcessing = true;
                PsiDocumentManager.getInstance(project).commitAllDocuments();
                CodeStyleManager styleManager = CodeStyleManager.getInstance(project);
                final String lineIndent = styleManager.getLineIndent(file, caretOffset);
                if (lineIndent != null) {
                    int col = calcColumnNumber(lineIndent, editor.getSettings().getTabSize(project));
                    int line = caretModel.getVisualPosition().line;
                    caretModel.moveToVisualPosition(new VisualPosition(line, col));
                    if (caretModel.getLogicalPosition().column != col) {
                        if (!ApplicationManager.getApplication().isWriteAccessAllowed() && !FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) {
                            return;
                        }
                        editor.getSelectionModel().removeSelection();
                        WriteAction.run(() -> document.replaceString(offset1 + 1, offset2, lineIndent));
                    }
                } else {
                    stopProcessing = false;
                }
                editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
                editor.getSelectionModel().removeSelection();
                if (stopProcessing) {
                    return;
                }
            }
        }
    }
    if (myOriginalHandler != null) {
        myOriginalHandler.execute(editor, caret, dataContext);
    }
}
Also used : CodeInsightSettings(com.intellij.codeInsight.CodeInsightSettings) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) Project(com.intellij.openapi.project.Project) PsiFile(com.intellij.psi.PsiFile)

Example 70 with CodeStyleManager

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

the class FieldReturnValue method createReplacement.

public PsiStatement createReplacement(final PsiMethod extractedMethod, final PsiMethodCallExpression methodCallExpression) throws IncorrectOperationException {
    final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(methodCallExpression.getProject()).getElementFactory();
    final CodeStyleManager styleManager = CodeStyleManager.getInstance(methodCallExpression.getProject());
    PsiExpressionStatement expressionStatement;
    expressionStatement = (PsiExpressionStatement) elementFactory.createStatementFromText("x = y();", null);
    expressionStatement = (PsiExpressionStatement) styleManager.reformat(expressionStatement);
    final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression) expressionStatement.getExpression();
    assignmentExpression.getLExpression().replace(elementFactory.createExpressionFromText(myField.getName(), myField));
    assignmentExpression.getRExpression().replace(methodCallExpression);
    return expressionStatement;
}
Also used : 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