Search in sources :

Example 51 with CodeStyleManager

use of com.intellij.psi.codeStyle.CodeStyleManager in project idea-handlebars by dmarcotte.

the class HbTypedHandler method adjustMustacheFormatting.

/**
   * When appropriate, adjusts the formatting for some 'staches, particularily close 'staches
   * and simple inverses ("{{^}}" and "{{else}}")
   */
private static void adjustMustacheFormatting(Project project, int offset, Editor editor, PsiFile file, FileViewProvider provider) {
    if (!HbConfig.isFormattingEnabled()) {
        // formatting disabled; nothing to do
        return;
    }
    PsiElement elementAtCaret = provider.findElementAt(offset - 1, HbLanguage.class);
    PsiElement closeOrSimpleInverseParent = PsiTreeUtil.findFirstParent(elementAtCaret, true, new Condition<PsiElement>() {

        @Override
        public boolean value(PsiElement element) {
            return element != null && (element instanceof HbSimpleInverse || element instanceof HbCloseBlockMustache);
        }
    });
    // run the formatter if the user just completed typing a SIMPLE_INVERSE or a CLOSE_BLOCK_STACHE
    if (closeOrSimpleInverseParent != null) {
        // grab the current caret position (AutoIndentLinesHandler is about to mess with it)
        PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
        CaretModel caretModel = editor.getCaretModel();
        CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
        codeStyleManager.adjustLineIndent(file, editor.getDocument().getLineStartOffset(caretModel.getLogicalPosition().line));
    }
}
Also used : CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) CaretModel(com.intellij.openapi.editor.CaretModel) PsiElement(com.intellij.psi.PsiElement)

Example 52 with CodeStyleManager

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

the class AndroidExtractAsIncludeAction method doRefactor.

private static void doRefactor(AndroidFacet facet, PsiFile file, XmlFile newFile, PsiElement from, PsiElement to, XmlTag parentTag, boolean wrapWithMerge) {
    final Project project = facet.getModule().getProject();
    final String textToExtract = file.getText().substring(from.getTextRange().getStartOffset(), to.getTextRange().getEndOffset());
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    final Document document = documentManager.getDocument(newFile);
    assert document != null;
    document.setText("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + (wrapWithMerge ? "<merge>\n" + textToExtract + "\n</merge>" : textToExtract));
    documentManager.commitDocument(document);
    final Set<String> unknownPrefixes = new HashSet<String>();
    newFile.accept(new XmlRecursiveElementVisitor() {

        @Override
        public void visitXmlTag(XmlTag tag) {
            super.visitXmlTag(tag);
            final String prefix = tag.getNamespacePrefix();
            if (!unknownPrefixes.contains(prefix) && tag.getNamespace().length() == 0) {
                unknownPrefixes.add(prefix);
            }
        }

        @Override
        public void visitXmlAttribute(XmlAttribute attribute) {
            final String prefix = attribute.getNamespacePrefix();
            if (!unknownPrefixes.contains(prefix) && attribute.getNamespace().length() == 0) {
                unknownPrefixes.add(prefix);
            }
        }
    });
    final XmlTag rootTag = newFile.getRootTag();
    assert rootTag != null;
    final XmlElementFactory elementFactory = XmlElementFactory.getInstance(project);
    final XmlAttribute[] attributes = rootTag.getAttributes();
    final XmlAttribute firstAttribute = attributes.length > 0 ? attributes[0] : null;
    for (String prefix : unknownPrefixes) {
        final String namespace = parentTag.getNamespaceByPrefix(prefix);
        final String xmlNsAttrName = "xmlns:" + prefix;
        if (namespace.length() > 0 && rootTag.getAttribute(xmlNsAttrName) == null) {
            final XmlAttribute xmlnsAttr = elementFactory.createXmlAttribute(xmlNsAttrName, namespace);
            if (firstAttribute != null) {
                rootTag.addBefore(xmlnsAttr, firstAttribute);
            } else {
                rootTag.add(xmlnsAttr);
            }
        }
    }
    String includingLayout = SdkConstants.LAYOUT_RESOURCE_PREFIX + ResourceHelper.getResourceName(file);
    IncludeReference.setIncludingLayout(project, newFile, includingLayout);
    final String resourceName = AndroidCommonUtils.getResourceName(ResourceType.LAYOUT.getName(), newFile.getName());
    final XmlTag includeTag = elementFactory.createTagFromText("<include layout=\"@layout/" + resourceName + "\"/>");
    parentTag.addAfter(includeTag, to);
    parentTag.deleteChildRange(from, to);
    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
    codeStyleManager.reformat(newFile);
}
Also used : CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) XmlAttribute(com.intellij.psi.xml.XmlAttribute) Document(com.intellij.openapi.editor.Document) Project(com.intellij.openapi.project.Project) HashSet(com.intellij.util.containers.HashSet) XmlTag(com.intellij.psi.xml.XmlTag)

Example 53 with CodeStyleManager

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

the class ExtractParameterAsLocalVariableFix method doFix.

@Override
public void doFix(Project project, ProblemDescriptor descriptor) {
    final PsiElement element = descriptor.getPsiElement();
    if (!(element instanceof PsiExpression)) {
        return;
    }
    final PsiExpression expression = ParenthesesUtils.stripParentheses((PsiExpression) element);
    if (!(expression instanceof PsiReferenceExpression)) {
        return;
    }
    final PsiReferenceExpression parameterReference = (PsiReferenceExpression) expression;
    final PsiElement target = parameterReference.resolve();
    if (!(target instanceof PsiParameter)) {
        return;
    }
    final PsiParameter parameter = (PsiParameter) target;
    final PsiElement declarationScope = parameter.getDeclarationScope();
    final PsiElement body;
    if (declarationScope instanceof PsiMethod) {
        final PsiMethod method = (PsiMethod) declarationScope;
        body = method.getBody();
    } else if (declarationScope instanceof PsiCatchSection) {
        final PsiCatchSection catchSection = (PsiCatchSection) declarationScope;
        body = catchSection.getCatchBlock();
    } else if (declarationScope instanceof PsiLoopStatement) {
        final PsiLoopStatement forStatement = (PsiLoopStatement) declarationScope;
        final PsiStatement forBody = forStatement.getBody();
        if (forBody instanceof PsiBlockStatement) {
            final PsiBlockStatement blockStatement = (PsiBlockStatement) forBody;
            body = blockStatement.getCodeBlock();
        } else {
            body = forBody;
        }
    } else if (declarationScope instanceof PsiLambdaExpression) {
        final PsiLambdaExpression lambdaExpression = (PsiLambdaExpression) declarationScope;
        body = lambdaExpression.getBody();
    } else {
        return;
    }
    if (body == null) {
        return;
    }
    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
    final String parameterName = parameterReference.getText();
    final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
    final String variableName = javaCodeStyleManager.suggestUniqueVariableName(parameterName, parameterReference, true);
    final SearchScope scope = parameter.getUseScope();
    final Query<PsiReference> search = ReferencesSearch.search(parameter, scope);
    final PsiReference reference = search.findFirst();
    if (reference == null) {
        return;
    }
    final PsiElement referenceElement = reference.getElement();
    if (!(referenceElement instanceof PsiReferenceExpression)) {
        return;
    }
    final PsiReferenceExpression firstReference = (PsiReferenceExpression) referenceElement;
    final PsiElement[] children = body.getChildren();
    final int startIndex;
    final int endIndex;
    if (body instanceof PsiCodeBlock) {
        startIndex = 1;
        endIndex = children.length - 1;
    } else {
        startIndex = 0;
        endIndex = children.length;
    }
    boolean newDeclarationCreated = false;
    final StringBuilder buffer = new StringBuilder();
    for (int i = startIndex; i < endIndex; i++) {
        final PsiElement child = children[i];
        newDeclarationCreated |= replaceVariableName(child, firstReference, variableName, parameterName, buffer);
    }
    if (body instanceof PsiExpression) {
        // expression lambda
        buffer.insert(0, "return ");
        buffer.append(';');
    }
    final String replacementText;
    if (newDeclarationCreated) {
        replacementText = "{" + buffer + '}';
    } else {
        final PsiType type = parameter.getType();
        final String className = type.getCanonicalText();
        replacementText = '{' + className + ' ' + variableName + " = " + parameterName + ';' + buffer + '}';
    }
    final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();
    final PsiCodeBlock block = elementFactory.createCodeBlockFromText(replacementText, declarationScope);
    body.replace(block);
    codeStyleManager.reformat(declarationScope);
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) SearchScope(com.intellij.psi.search.SearchScope)

Example 54 with CodeStyleManager

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

the class GenerateComponentExternalizationAction method actionPerformed.

public void actionPerformed(AnActionEvent e) {
    final PsiClass target = getComponentInContext(e.getDataContext());
    assert target != null;
    final PsiElementFactory factory = JavaPsiFacade.getInstance(target.getProject()).getElementFactory();
    final CodeStyleManager formatter = CodeStyleManager.getInstance(target.getManager().getProject());
    final JavaCodeStyleManager styler = JavaCodeStyleManager.getInstance(target.getProject());
    final String qualifiedName = target.getQualifiedName();
    Runnable runnable = () -> ApplicationManager.getApplication().runWriteAction(() -> {
        try {
            final PsiReferenceList implList = target.getImplementsList();
            assert implList != null;
            final PsiJavaCodeReferenceElement referenceElement = factory.createReferenceFromText(PERSISTENCE_STATE_COMPONENT + "<" + qualifiedName + ">", target);
            implList.add(styler.shortenClassReferences(referenceElement.copy()));
            PsiMethod read = factory.createMethodFromText("public void loadState(" + qualifiedName + " state) {\n" + "    com.intellij.util.xmlb.XmlSerializerUtil.copyBean(state, this);\n" + "}", target);
            read = (PsiMethod) formatter.reformat(target.add(read));
            styler.shortenClassReferences(read);
            PsiMethod write = factory.createMethodFromText("public " + qualifiedName + " getState() {\n" + "    return this;\n" + "}\n", target);
            write = (PsiMethod) formatter.reformat(target.add(write));
            styler.shortenClassReferences(write);
            PsiAnnotation annotation = target.getModifierList().addAnnotation(STATE);
            annotation = (PsiAnnotation) formatter.reformat(annotation.replace(factory.createAnnotationFromText("@" + STATE + "(name = \"" + qualifiedName + "\", " + "storages = {@" + STORAGE + "(file = \"" + StoragePathMacros.WORKSPACE_FILE + "\"\n )})", target)));
            styler.shortenClassReferences(annotation);
        } catch (IncorrectOperationException e1) {
            LOG.error(e1);
        }
    });
    CommandProcessor.getInstance().executeCommand(target.getProject(), runnable, DevKitBundle.message("command.implement.externalizable"), null);
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 55 with CodeStyleManager

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

the class InlineIncrementIntention method processIntention.

@Override
protected void processIntention(@NotNull PsiElement element) {
    final PsiReferenceExpression operandExpression = IncrementUtil.getIncrementOrDecrementOperand(element);
    final PsiExpressionStatement expressionStatement = ObjectUtils.tryCast(element.getParent(), PsiExpressionStatement.class);
    final String operatorText = IncrementUtil.getOperatorText(element);
    if (operandExpression != null && expressionStatement != null && operatorText != null) {
        final PsiVariable variable = resolveSimpleVariableReference(operandExpression);
        if (variable != null) {
            final Occurrence occurrence = findSingleReadOccurrence(expressionStatement, variable);
            if (occurrence != null) {
                final Project project = expressionStatement.getProject();
                final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
                final String text = occurrence.isPrevious ? occurrence.referenceExpression.getText() + operatorText : operatorText + occurrence.referenceExpression.getText();
                PsiExpression incrementOrDecrement = factory.createExpressionFromText(text, expressionStatement);
                incrementOrDecrement = (PsiExpression) occurrence.referenceExpression.replace(incrementOrDecrement);
                final CodeStyleManager codeStyle = CodeStyleManager.getInstance(project);
                codeStyle.reformat(incrementOrDecrement, true);
                final CommentTracker ct = new CommentTracker();
                ct.deleteAndRestoreComments(expressionStatement);
            }
        }
    }
}
Also used : Project(com.intellij.openapi.project.Project) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) CommentTracker(com.siyeh.ig.psiutils.CommentTracker)

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