Search in sources :

Example 11 with GrString

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString in project intellij-community by JetBrains.

the class GroovyBlockGenerator method generateSubBlocks.

public List<Block> generateSubBlocks() {
    //For binary expressions
    PsiElement blockPsi = myNode.getPsi();
    IElementType elementType = myNode.getElementType();
    if (blockPsi instanceof GrBinaryExpression && !(blockPsi.getParent() instanceof GrBinaryExpression)) {
        return generateForBinaryExpr();
    }
    //For multiline strings
    if ((elementType == GroovyTokenTypes.mSTRING_LITERAL || elementType == GroovyTokenTypes.mGSTRING_LITERAL) && myBlock.getTextRange().equals(myNode.getTextRange())) {
        String text = myNode.getText();
        if (text.length() > 6) {
            if (text.substring(0, 3).equals("'''") && text.substring(text.length() - 3).equals("'''") || text.substring(0, 3).equals("\"\"\"") & text.substring(text.length() - 3).equals("\"\"\"")) {
                return generateForMultiLineString();
            }
        }
    }
    //for gstrings
    if (elementType == GroovyElementTypes.GSTRING || elementType == GroovyElementTypes.REGEX || elementType == GroovyTokenTypes.mREGEX_LITERAL || elementType == GroovyTokenTypes.mDOLLAR_SLASH_REGEX_LITERAL) {
        final FormattingContext context = myNode.getPsi() instanceof GrString && ((GrString) myNode.getPsi()).isPlainString() ? myContext.createContext(true) : myContext;
        final ArrayList<Block> subBlocks = new ArrayList<>();
        ASTNode[] children = getGroovyChildren(myNode);
        for (ASTNode childNode : children) {
            if (childNode.getTextRange().getLength() > 0) {
                subBlocks.add(new GroovyBlock(childNode, getIndent(childNode), Wrap.createWrap(WrapType.NONE, false), context));
            }
        }
        return subBlocks;
    }
    // chained properties, calls, indexing, etc
    if (NESTED.contains(elementType) && blockPsi.getParent() != null && !NESTED.contains(blockPsi.getParent().getNode().getElementType())) {
        final List<Block> subBlocks = new ArrayList<>();
        AlignmentProvider.Aligner dotsAligner = myContext.getSettings().ALIGN_MULTILINE_CHAINED_METHODS ? myAlignmentProvider.createAligner(false) : null;
        final Wrap wrap = myWrappingProcessor.getChainedMethodCallWrap();
        addNestedChildren(myNode.getPsi(), subBlocks, dotsAligner, true, wrap);
        return subBlocks;
    }
    if (blockPsi instanceof GrListOrMap && ((GrListOrMap) blockPsi).isMap() && myContext.getGroovySettings().ALIGN_NAMED_ARGS_IN_MAP) {
        AlignmentProvider.Aligner labels = myAlignmentProvider.createAligner(false);
        AlignmentProvider.Aligner exprs = myAlignmentProvider.createAligner(true);
        GrNamedArgument[] namedArgs = ((GrListOrMap) blockPsi).getNamedArguments();
        for (GrNamedArgument arg : namedArgs) {
            GrArgumentLabel label = arg.getLabel();
            if (label != null)
                labels.append(label);
            PsiElement colon = arg.getColon();
            if (colon == null)
                colon = arg.getExpression();
            if (colon != null)
                exprs.append(colon);
        }
    }
    // For Parameter lists
    if (isListLikeClause(blockPsi)) {
        final ArrayList<Block> subBlocks = new ArrayList<>();
        List<ASTNode> astNodes = visibleChildren(myNode);
        if (mustAlign(blockPsi, astNodes)) {
            final AlignmentProvider.Aligner aligner = myAlignmentProvider.createAligner(false);
            for (ASTNode node : astNodes) {
                if (!isKeyword(node))
                    aligner.append(node.getPsi());
            }
        }
        for (ASTNode childNode : astNodes) {
            subBlocks.add(new GroovyBlock(childNode, getIndent(childNode), getChildWrap(childNode), myContext));
        }
        return subBlocks;
    }
    boolean classLevel = blockPsi instanceof GrTypeDefinitionBody;
    if (blockPsi instanceof GrClosableBlock && ((GrClosableBlock) blockPsi).getArrow() != null && ((GrClosableBlock) blockPsi).getParameters().length > 0 && !getClosureBodyVisibleChildren(myNode).isEmpty()) {
        GrClosableBlock closableBlock = (GrClosableBlock) blockPsi;
        ArrayList<Block> blocks = new ArrayList<>();
        PsiElement lbrace = closableBlock.getLBrace();
        if (lbrace != null) {
            ASTNode node = lbrace.getNode();
            blocks.add(new GroovyBlock(node, getIndent(node), Wrap.createWrap(WrapType.NONE, false), myContext));
        }
        /* {
        Indent indent = GroovyIndentProcessor.getChildIndent(myBlock, parameterListNode);
        GroovyBlock block = new GroovyBlock(parameterListNode, indent, myWrap, mySettings, myGroovySettings, myAlignmentProvider);
        blocks.add(block);
      }

      {
        PsiElement arrow = closableBlock.getArrow();
        ASTNode node = arrow.getNode();
        Indent indent = GroovyIndentProcessor.getChildIndent(myBlock, node);
        GroovyBlock block = new GroovyBlock(node, indent, myWrap, mySettings, myGroovySettings, myAlignmentProvider);
        blocks.add(block);
      }*/
        {
            Indent indent = Indent.getNormalIndent();
            ASTNode parameterListNode = closableBlock.getParameterList().getNode();
            ClosureBodyBlock bodyBlock = new ClosureBodyBlock(parameterListNode, indent, Wrap.createWrap(WrapType.NONE, false), myContext);
            blocks.add(bodyBlock);
        }
        PsiElement rbrace = closableBlock.getRBrace();
        if (rbrace != null) {
            ASTNode node = rbrace.getNode();
            blocks.add(new GroovyBlock(node, getIndent(node), Wrap.createWrap(WrapType.NONE, false), myContext));
        }
        return blocks;
    }
    if (blockPsi instanceof GrCodeBlock || blockPsi instanceof GroovyFile || classLevel) {
        return generateSubBlockForCodeBlocks(classLevel, visibleChildren(myNode), myContext.getGroovySettings().INDENT_LABEL_BLOCKS);
    }
    if (blockPsi instanceof GrMethod) {
        final ArrayList<Block> subBlocks = new ArrayList<>();
        for (ASTNode childNode : getGroovyChildren(myNode)) {
            if (childNode.getElementType() == GroovyTokenTypes.mLPAREN)
                continue;
            if (childNode.getElementType() == GroovyTokenTypes.mRPAREN)
                continue;
            if (childNode.getElementType() == GroovyElementTypes.PARAMETERS_LIST) {
                subBlocks.add(new ParameterListBlock(((GrMethod) blockPsi), Indent.getNoneIndent(), Wrap.createWrap(WrapType.NONE, false), myContext));
            } else if (canBeCorrectBlock(childNode)) {
                subBlocks.add(new GroovyBlock(childNode, getIndent(childNode), getChildWrap(childNode), myContext));
            }
        }
        return subBlocks;
    } else if (blockPsi instanceof GrTraditionalForClause) {
        if (myContext.getSettings().ALIGN_MULTILINE_FOR) {
            final GrTraditionalForClause clause = (GrTraditionalForClause) blockPsi;
            final AlignmentProvider.Aligner parenthesesAligner = myAlignmentProvider.createAligner(false);
            parenthesesAligner.append(clause.getInitialization());
            parenthesesAligner.append(clause.getCondition());
            parenthesesAligner.append(clause.getUpdate());
        }
    } else if (blockPsi instanceof GrBinaryExpression) {
        if (myContext.getSettings().ALIGN_MULTILINE_BINARY_OPERATION) {
            final GrBinaryExpression binary = (GrBinaryExpression) blockPsi;
            final GrExpression left = binary.getLeftOperand();
            final GrExpression right = binary.getRightOperand();
            if (left != null && right != null) {
                myAlignmentProvider.addPair(left, right, false);
            }
        }
    } else if (blockPsi instanceof GrAssignmentExpression) {
        if (myContext.getSettings().ALIGN_MULTILINE_ASSIGNMENT) {
            final GrAssignmentExpression assignment = (GrAssignmentExpression) blockPsi;
            final GrExpression lValue = assignment.getLValue();
            final GrExpression rValue = assignment.getRValue();
            if (lValue != null && rValue != null) {
                myAlignmentProvider.addPair(lValue, rValue, false);
            }
        }
    } else if (blockPsi instanceof GrConditionalExpression) {
        if (myContext.getSettings().ALIGN_MULTILINE_TERNARY_OPERATION) {
            final GrConditionalExpression conditional = (GrConditionalExpression) blockPsi;
            final AlignmentProvider.Aligner exprAligner = myAlignmentProvider.createAligner(false);
            exprAligner.append(conditional.getCondition());
            if (!(conditional instanceof GrElvisExpression)) {
                exprAligner.append(conditional.getThenBranch());
            }
            exprAligner.append(conditional.getElseBranch());
            ASTNode question = conditional.getNode().findChildByType(GroovyTokenTypes.mQUESTION);
            ASTNode colon = conditional.getNode().findChildByType(GroovyTokenTypes.mCOLON);
            if (question != null && colon != null) {
                AlignmentProvider.Aligner questionColonAligner = myAlignmentProvider.createAligner(false);
                questionColonAligner.append(question.getPsi());
                questionColonAligner.append(colon.getPsi());
            }
        }
    }
    // For other cases
    final ArrayList<Block> subBlocks = new ArrayList<>();
    for (ASTNode childNode : visibleChildren(myNode)) {
        subBlocks.add(new GroovyBlock(childNode, getIndent(childNode), getChildWrap(childNode), myContext));
    }
    return subBlocks;
}
Also used : FormattingContext(org.jetbrains.plugins.groovy.formatter.FormattingContext) GrNamedArgument(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument) GrString(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString) ArrayList(java.util.ArrayList) GrString(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString) AlignmentProvider(org.jetbrains.plugins.groovy.formatter.AlignmentProvider) GrListOrMap(org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap) ASTNode(com.intellij.lang.ASTNode) PsiElement(com.intellij.psi.PsiElement) LeafPsiElement(com.intellij.psi.impl.source.tree.LeafPsiElement) GrCodeBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock) GrArgumentLabel(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) IElementType(com.intellij.psi.tree.IElementType) GrTypeDefinitionBody(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinitionBody) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GrCodeBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile) GrTraditionalForClause(org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrTraditionalForClause)

Example 12 with GrString

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString in project intellij-community by JetBrains.

the class GroovyGStringSelectioner method getLineTextRange.

@NotNull
private static TextRange getLineTextRange(PsiElement e, int cursorOffset) {
    assert e.getParent() instanceof GrString;
    PsiElement next = e;
    int startOffset = cursorOffset;
    int endOffset = cursorOffset;
    if (e.getNode().getElementType() == GroovyTokenTypes.mGSTRING_CONTENT) {
        final String text = e.getText();
        int cur;
        int index = -1;
        while (true) {
            cur = text.indexOf('\n', index + 1);
            if (cur < 0 || cur + e.getTextOffset() > cursorOffset)
                break;
            index = cur;
        }
        if (index >= 0) {
            startOffset = e.getTextOffset() + index + 1;
        }
        index = text.indexOf('\n', cursorOffset - e.getTextOffset());
        if (index >= 0) {
            endOffset = e.getTextOffset() + index + 1;
        }
    }
    if (startOffset == cursorOffset) {
        do {
            if (next == null)
                break;
            final ASTNode node = next.getNode();
            if (node == null)
                break;
            final IElementType type = node.getElementType();
            if (type == GroovyTokenTypes.mGSTRING_BEGIN) {
                startOffset = next.getTextRange().getEndOffset();
                break;
            }
            if (type == GroovyElementTypes.GSTRING_CONTENT) {
                final String text;
                if (startOffset == cursorOffset && next.getTextRange().contains(cursorOffset)) {
                    text = next.getText().substring(0, startOffset - next.getTextOffset());
                } else {
                    text = next.getText();
                }
                final int i = text.lastIndexOf('\n');
                if (i >= 0) {
                    startOffset = next.getTextOffset() + i + 1;
                    break;
                }
            }
            startOffset = next.getTextOffset();
            next = next.getPrevSibling();
        } while (true);
    }
    if (endOffset == cursorOffset) {
        next = e;
        do {
            if (next == null)
                break;
            final ASTNode node = next.getNode();
            if (node == null)
                break;
            final IElementType type = node.getElementType();
            if (type == GroovyTokenTypes.mGSTRING_END) {
                endOffset = next.getTextOffset();
                break;
            }
            if (type == GroovyElementTypes.GSTRING_CONTENT) {
                final String text;
                final int offset;
                if (endOffset == cursorOffset && next.getTextRange().contains(cursorOffset)) {
                    offset = endOffset - next.getTextOffset();
                    text = next.getText().substring(offset);
                } else {
                    offset = 0;
                    text = next.getText();
                }
                final int i = text.indexOf('\n');
                if (i >= 0) {
                    endOffset = next.getTextOffset() + offset + i;
                    break;
                }
            }
            endOffset = next.getTextOffset() + next.getTextLength();
            next = next.getNextSibling();
        } while (true);
    }
    return new TextRange(startOffset, endOffset);
}
Also used : IElementType(com.intellij.psi.tree.IElementType) GrString(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString) ASTNode(com.intellij.lang.ASTNode) TextRange(com.intellij.openapi.util.TextRange) GrString(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString) PsiElement(com.intellij.psi.PsiElement) NotNull(org.jetbrains.annotations.NotNull)

Example 13 with GrString

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString in project intellij-community by JetBrains.

the class GroovyGStringSelectioner method select.

@Override
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
    final List<TextRange> ranges = ContainerUtil.newArrayList();
    final PsiElement parent = e.getParent();
    if (parent instanceof GrStringContent && parent.getParent() instanceof GrString) {
        TextRange range = getLineTextRange(parent, cursorOffset);
        ranges.add(range);
    } else if (parent instanceof GrString) {
        PsiElement firstChild = parent.getFirstChild();
        PsiElement lastChild = parent.getLastChild();
        if (firstChild.getNode().getElementType() == GroovyTokenTypes.mGSTRING_BEGIN) {
            firstChild = firstChild.getNextSibling();
        }
        if (lastChild.getNode().getElementType() == GroovyTokenTypes.mGSTRING_END) {
            lastChild = lastChild.getPrevSibling();
        }
        if (firstChild != null && lastChild != null) {
            TextRange range = new TextRange(firstChild.getTextOffset(), lastChild.getTextOffset() + lastChild.getTextLength());
            ranges.add(range);
        }
        ranges.add(parent.getTextRange());
    } else if (parent instanceof GrStringInjection) {
        if (e instanceof GrReferenceExpression) {
            List<TextRange> r = new ArrayList<>(2);
            SelectWordUtil.addWordSelection(editor.getSettings().isCamelWords(), editorText, cursorOffset, r);
            for (TextRange textRange : r) {
                if (editorText.charAt(textRange.getStartOffset()) == '$') {
                    textRange = new TextRange(textRange.getStartOffset() + 1, textRange.getEndOffset());
                }
                ranges.add(textRange);
            }
        }
        ranges.add(parent.getTextRange());
        ranges.add(e.getTextRange());
    }
    return ranges;
}
Also used : GrStringContent(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrStringContent) GrString(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString) ArrayList(java.util.ArrayList) TextRange(com.intellij.openapi.util.TextRange) GrStringInjection(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrStringInjection) PsiElement(com.intellij.psi.PsiElement) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)

Example 14 with GrString

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString in project intellij-community by JetBrains.

the class ExpressionGenerator method visitLiteralExpression.

@Override
public //doesn't visit GrString and regexps
void visitLiteralExpression(@NotNull GrLiteral literal) {
    final TypeConstraint[] constraints = GroovyExpectedTypesProvider.calculateTypeConstraints(literal);
    boolean isChar = false;
    for (TypeConstraint constraint : constraints) {
        if (constraint instanceof SubtypeConstraint && PsiType.CHAR.equals(TypesUtil.unboxPrimitiveTypeWrapper(constraint.getDefaultType()))) {
            isChar = true;
        }
    }
    final String text = literal.getText();
    if (text.startsWith("'''") || text.startsWith("\"\"\"")) {
        String string = GrStringUtil.removeQuotes(text).replace("\n", "\\n").replace("\r", "\\r");
        builder.append('"').append(string).append('"');
    } else if (text.startsWith("'")) {
        if (isChar) {
            builder.append(text);
        } else {
            builder.append('"').append(StringUtil.escapeQuotes(StringUtil.trimEnd(text.substring(1, text.length()), "'"))).append('"');
        }
    } else if (text.startsWith("\"")) {
        if (isChar) {
            builder.append('\'').append(StringUtil.escapeQuotes(StringUtil.trimEnd(text.substring(1, text.length()), "\""))).append('\'');
        } else {
            builder.append(text);
        }
    } else {
        builder.append(text);
    }
}
Also used : SubtypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.SubtypeConstraint) TypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint) GrString(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString)

Example 15 with GrString

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString in project android by JetBrains.

the class GradleDslLiteral method getValue.

@Override
@Nullable
public Object getValue() {
    if (myUnsavedValue != null) {
        return myUnsavedValue;
    }
    if (myExpression == null) {
        return null;
    }
    Object value = ((GrLiteral) myExpression).getValue();
    if (value != null) {
        return value;
    }
    if (myExpression instanceof GrString) {
        // String literal with variables. ex: compileSdkVersion = "$ANDROID-${VERSION}"
        String literalText = myExpression.getText();
        if (isQuotedString(literalText)) {
            literalText = unquoteString(literalText);
        }
        List<GradleResolvedVariable> resolvedVariables = Lists.newArrayList();
        GrStringInjection[] injections = ((GrString) myExpression).getInjections();
        for (GrStringInjection injection : injections) {
            String variableName = null;
            GrClosableBlock closableBlock = injection.getClosableBlock();
            if (closableBlock != null) {
                String blockText = closableBlock.getText();
                variableName = blockText.substring(1, blockText.length() - 1);
            } else {
                GrExpression expression = injection.getExpression();
                if (expression != null) {
                    variableName = expression.getText();
                }
            }
            if (!isEmpty(variableName)) {
                GradleDslExpression resolvedExpression = resolveReference(variableName, GradleDslExpression.class);
                if (resolvedExpression != null) {
                    Object resolvedValue = resolvedExpression.getValue();
                    if (resolvedValue != null) {
                        resolvedVariables.add(new GradleResolvedVariable(variableName, resolvedValue, resolvedExpression));
                        literalText = literalText.replace(injection.getText(), resolvedValue.toString());
                    }
                }
            }
        }
        setResolvedVariables(resolvedVariables);
        return literalText;
    }
    return null;
}
Also used : GrString(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GrString(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString) GradleResolvedVariable(com.android.tools.idea.gradle.dsl.parser.GradleResolvedVariable) GrStringInjection(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrStringInjection) GrLiteral(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

GrString (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString)15 PsiElement (com.intellij.psi.PsiElement)6 GrStringInjection (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrStringInjection)6 TextRange (com.intellij.openapi.util.TextRange)4 GrLiteral (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral)4 ASTNode (com.intellij.lang.ASTNode)3 IElementType (com.intellij.psi.tree.IElementType)3 Nullable (org.jetbrains.annotations.Nullable)3 GrClosableBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)3 GrExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression)3 GrStringContent (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrStringContent)3 ArrayList (java.util.ArrayList)2 NotNull (org.jetbrains.annotations.NotNull)2 GroovyPsiElement (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)2 GrListOrMap (org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap)2 GrArgumentLabel (org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel)2 GrCodeBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock)2 GradleResolvedVariable (com.android.tools.idea.gradle.dsl.parser.GradleResolvedVariable)1 FoldingDescriptor (com.intellij.lang.folding.FoldingDescriptor)1 NamedFoldingDescriptor (com.intellij.lang.folding.NamedFoldingDescriptor)1