Java Code Examples for com.intellij.lang.ASTNode#getTextRange()

The following examples show how to use com.intellij.lang.ASTNode#getTextRange() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DuneFoldingBuilder.java    From reasonml-idea-plugin with MIT License 6 votes vote down vote up
@Nullable
private FoldingDescriptor fold(@Nullable PsiElement root) {
    if (root == null) {
        return null;
    }

    // find next element
    ASTNode element = root.getFirstChild().getNode();
    ASTNode nextElement = element == null ? null : ORUtil.nextSiblingNode(element);
    ASTNode nextNextElement = nextElement == null ? null : ORUtil.nextSiblingNode(nextElement);

    if (nextNextElement != null) {
        TextRange rootRange = root.getTextRange();
        TextRange nextRange = nextElement.getTextRange();
        return new FoldingDescriptor(root, TextRange.create(nextRange.getEndOffset(), rootRange.getEndOffset() - 1));
    }

    return null;
}
 
Example 2
Source File: BashPsiUtils.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
@Nullable
public static ASTNode findEquivalentParent(@NotNull ASTNode node, @Nullable IElementType stopAt) {
    TextRange sourceRange = node.getTextRange();

    ASTNode current = node;
    while (true) {
        ASTNode parent = current.getTreeParent();
        if (parent == null || !parent.getTextRange().equals(sourceRange)) {
            return stopAt != null && current.getElementType() != stopAt ? null : current;
        }

        current = parent;
        if (stopAt == null || stopAt.equals(current.getElementType())) {
            return current;
        }
    }
}
 
Example 3
Source File: GLSLFoldingBuilder.java    From glsl4idea with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void appendDescriptors(final ASTNode node, final List<FoldingDescriptor> descriptors) {
    IElementType type = node.getElementType();

    final TextRange textRange = node.getTextRange();
    //Don't add folding to 0-length nodes, crashes in new FoldingDescriptor
    if(textRange.getLength() <= 0)return;

    if (type == GLSLTokenTypes.COMMENT_BLOCK || type == GLSLElementTypes.COMPOUND_STATEMENT) {
        descriptors.add(new FoldingDescriptor(node, textRange));
    }

    ASTNode child = node.getFirstChildNode();
    while (child != null) {
        appendDescriptors(child, descriptors);
        child = child.getTreeNext();
    }
}
 
Example 4
Source File: FormatterUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static StringBuilder createNewLeafChars(final ASTNode leafElement, final TextRange textRange, final String whiteSpace) {
  final TextRange elementRange = leafElement.getTextRange();
  final String elementText = leafElement.getText();

  final StringBuilder result = new StringBuilder();

  if (elementRange.getStartOffset() < textRange.getStartOffset()) {
    result.append(elementText.substring(0, textRange.getStartOffset() - elementRange.getStartOffset()));
  }

  result.append(whiteSpace);

  if (elementRange.getEndOffset() > textRange.getEndOffset()) {
    result.append(elementText.substring(textRange.getEndOffset() - elementRange.getStartOffset()));
  }

  return result;
}
 
Example 5
Source File: CodeStyleManagerRunnable.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static TextRange getSignificantRange(final PsiFile file, final int offset) {
  final ASTNode elementAtOffset = SourceTreeToPsiMap.psiElementToTree(CodeStyleManagerImpl.findElementInTreeWithFormatterEnabled(file, offset));
  if (elementAtOffset == null) {
    int significantRangeStart = CharArrayUtil.shiftBackward(file.getText(), offset - 1, "\n\r\t ");
    return new TextRange(Math.max(significantRangeStart, 0), offset);
  }

  final FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(file);
  if (builder != null) {
    final TextRange textRange = builder.getRangeAffectingIndent(file, offset, elementAtOffset);
    if (textRange != null) {
      return textRange;
    }
  }

  final TextRange elementRange = elementAtOffset.getTextRange();
  if (isWhiteSpace(elementAtOffset)) {
    return extendRangeAtStartOffset(file, elementRange);
  }

  return elementRange;
}
 
Example 6
Source File: FusionFoldingBuilder.java    From intellij-neos with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This function appends new FoldingDescriptors to the given one.
 *
 * @param node        Block node
 * @param document    Current document
 * @param descriptors List<FoldingDescriptor>
 * @return The given node
 */
private static ASTNode appendDescriptors(final ASTNode node, final Document document, final List<FoldingDescriptor> descriptors) {
    IElementType elementType = node.getElementType();
    if (isFoldable(elementType)) {
        TextRange nodeTextRange = node.getTextRange();
        int newEndLine = document.getLineNumber(nodeTextRange.getEndOffset());
        int endLineOffset = document.getLineEndOffset(newEndLine);
        descriptors.add(new FoldingDescriptor(node, new TextRange(nodeTextRange.getStartOffset(), endLineOffset)));
    }
    ASTNode child = node.getFirstChildNode();
    while (child != null) {
        child = appendDescriptors(child, document, descriptors).getTreeNext();
    }
    return node;
}
 
Example 7
Source File: GraphQLFoldingBuilder.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
private static void buildFolding(ASTNode node, List<FoldingDescriptor> list) {
    boolean isBlock = GraphQLBlock.INDENT_PARENTS.contains(node.getElementType());
    if(!isBlock && GraphQLElementTypes.QUOTED_STRING.equals(node.getElementType())) {
        // triple quoted multi-line strings should support folding
        ASTNode quote = node.findChildByType(GraphQLElementTypes.OPEN_QUOTE);
        isBlock = quote != null && quote.getTextLength() == 3;
    }
    if (isBlock && !node.getTextRange().isEmpty()) {
        final TextRange range = node.getTextRange();
        list.add(new FoldingDescriptor(node, range));
    }
    for (ASTNode child : node.getChildren(null)) {
        buildFolding(child, list);
    }
}
 
Example 8
Source File: CppFoldingBuilder.java    From CppTools with Apache License 2.0 5 votes vote down vote up
private void addFolding(ASTNode node, Document doc, List<FoldingDescriptor> result) {
  final TextRange textRange = node.getTextRange();
  final int startLine = doc.getLineNumber(textRange.getStartOffset());
  final int endLine = doc.getLineNumber(textRange.getEndOffset());

  if (startLine != endLine && (endLine - startLine) < MAX_FOLDING_LINES) {
    result.add(new FoldingDescriptor(
      node,
      textRange
    ));
  }
}
 
Example 9
Source File: WeaveFolding.java    From mule-intellij-plugins with Apache License 2.0 4 votes vote down vote up
private static boolean spanMultipleLines(@NotNull ASTNode node, @NotNull Document document) {
    final TextRange range = node.getTextRange();
    return document.getLineNumber(range.getStartOffset()) < document.getLineNumber(range.getEndOffset());
}
 
Example 10
Source File: ProtoFoldingBuilder.java    From protobuf-jetbrains-plugin with Apache License 2.0 4 votes vote down vote up
private static boolean spanMultipleLines(@NotNull ASTNode node, @NotNull Document document) {
    final TextRange range = node.getTextRange();
    return document.getLineNumber(range.getStartOffset()) < document.getLineNumber(range.getEndOffset());
}
 
Example 11
Source File: GLSLFormattingModelBuilder.java    From glsl4idea with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Nullable
@Override
public TextRange getRangeAffectingIndent(PsiFile psiFile, int i, ASTNode astNode) {
    return astNode.getTextRange();
}
 
Example 12
Source File: SyntaxTraverser.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public TextRange rangeOf(@Nonnull ASTNode node) {
  return node.getTextRange();
}
 
Example 13
Source File: BlockSupportImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * Find ast node that could be reparsed incrementally
 *
 * @return Pair (target reparseable node, new replacement node)
 * or {@code null} if can't parse incrementally.
 */
@Nullable
public static Couple<ASTNode> findReparseableRoots(@Nonnull PsiFileImpl file, @Nonnull FileASTNode oldFileNode, @Nonnull TextRange changedPsiRange, @Nonnull CharSequence newFileText) {
  final FileElement fileElement = (FileElement)oldFileNode;
  final CharTable charTable = fileElement.getCharTable();
  int lengthShift = newFileText.length() - fileElement.getTextLength();

  if (fileElement.getElementType() instanceof ITemplateDataElementType || isTooDeep(file)) {
    // unable to perform incremental reparse for template data in JSP, or in exceptionally deep trees
    return null;
  }

  final ASTNode leafAtStart = fileElement.findLeafElementAt(Math.max(0, changedPsiRange.getStartOffset() - 1));
  final ASTNode leafAtEnd = fileElement.findLeafElementAt(Math.min(changedPsiRange.getEndOffset(), fileElement.getTextLength() - 1));
  ASTNode node = leafAtStart != null && leafAtEnd != null ? TreeUtil.findCommonParent(leafAtStart, leafAtEnd) : fileElement;
  Language baseLanguage = file.getViewProvider().getBaseLanguage();

  while (node != null && !(node instanceof FileElement)) {
    IElementType elementType = node.getElementType();
    if (elementType instanceof IReparseableElementTypeBase || elementType instanceof IReparseableLeafElementType) {
      final TextRange textRange = node.getTextRange();

      if (textRange.getLength() + lengthShift > 0 && (baseLanguage.isKindOf(elementType.getLanguage()) || !TreeUtil.containsOuterLanguageElements(node))) {
        final int start = textRange.getStartOffset();
        final int end = start + textRange.getLength() + lengthShift;
        if (end > newFileText.length()) {
          reportInconsistentLength(file, newFileText, node, start, end);
          break;
        }

        CharSequence newTextStr = newFileText.subSequence(start, end);

        ASTNode newNode;
        if (elementType instanceof IReparseableElementTypeBase) {
          newNode = tryReparseNode((IReparseableElementTypeBase)elementType, node, newTextStr, file.getManager(), baseLanguage, charTable);
        }
        else {
          newNode = tryReparseLeaf((IReparseableLeafElementType)elementType, node, newTextStr);
        }

        if (newNode != null) {
          if (newNode.getTextLength() != newTextStr.length()) {
            String details = ApplicationManager.getApplication().isInternal() ? "text=" + newTextStr + "; treeText=" + newNode.getText() + ";" : "";
            LOG.error("Inconsistent reparse: " + details + " type=" + elementType);
          }

          return Couple.of(node, newNode);
        }
      }
    }
    node = node.getTreeParent();
  }
  return null;
}
 
Example 14
Source File: EnterInStringLiteralHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public Result preprocessEnter(@Nonnull final PsiFile file, @Nonnull final Editor editor, @Nonnull Ref<Integer> caretOffsetRef,
                              @Nonnull final Ref<Integer> caretAdvanceRef, @Nonnull final DataContext dataContext,
                              final EditorActionHandler originalHandler) {
  int caretOffset = caretOffsetRef.get().intValue();
  int caretAdvance = caretAdvanceRef.get().intValue();
  if (!isInStringLiteral(editor, dataContext, caretOffset)) return Result.Continue;
  PsiDocumentManager.getInstance(file.getProject()).commitDocument(editor.getDocument());
  PsiElement psiAtOffset = file.findElementAt(caretOffset);
  if (psiAtOffset != null && psiAtOffset.getTextOffset() < caretOffset) {
    Document document = editor.getDocument();
    CharSequence text = document.getText();
    ASTNode token = psiAtOffset.getNode();
    JavaLikeQuoteHandler quoteHandler = getJavaLikeQuoteHandler(editor, psiAtOffset);

    if (quoteHandler != null &&
        quoteHandler.getConcatenatableStringTokenTypes() != null &&
        quoteHandler.getConcatenatableStringTokenTypes().contains(token.getElementType())) {
      TextRange range = token.getTextRange();
      final char literalStart = token.getText().charAt(0);
      final StringLiteralLexer lexer = new StringLiteralLexer(literalStart, token.getElementType());
      lexer.start(text, range.getStartOffset(), range.getEndOffset());

      while (lexer.getTokenType() != null) {
        if (lexer.getTokenStart() < caretOffset && caretOffset < lexer.getTokenEnd()) {
          if (StringEscapesTokenTypes.STRING_LITERAL_ESCAPES.contains(lexer.getTokenType())) {
            caretOffset = lexer.getTokenEnd();
          }
          break;
        }
        lexer.advance();
      }

      if (quoteHandler.needParenthesesAroundConcatenation(psiAtOffset)) {
        document.insertString(psiAtOffset.getTextRange().getEndOffset(), ")");
        document.insertString(psiAtOffset.getTextRange().getStartOffset(), "(");
        caretOffset++;
        caretAdvance++;
      }

      final String insertedFragment = literalStart + " " + quoteHandler.getStringConcatenationOperatorRepresentation();
      document.insertString(caretOffset, insertedFragment + " " + literalStart);
      caretOffset += insertedFragment.length();
      caretAdvance = 1;
      CommonCodeStyleSettings langSettings =
              CodeStyleSettingsManager.getSettings(file.getProject()).getCommonSettings(file.getLanguage());
      if (langSettings.BINARY_OPERATION_SIGN_ON_NEXT_LINE) {
        caretOffset -= 1;
        caretAdvance = 3;
      }
      caretOffsetRef.set(caretOffset);
      caretAdvanceRef.set(caretAdvance);
      return Result.DefaultForceIndent;
    }
  }
  return Result.Continue;
}
 
Example 15
Source File: CodeFormatterFacade.java    From consulo with Apache License 2.0 4 votes vote down vote up
public ASTNode processElement(ASTNode element) {
  TextRange range = element.getTextRange();
  return processRange(element, range.getStartOffset(), range.getEndOffset());
}