Java Code Examples for com.intellij.psi.PsiElement#getTextOffset()

The following examples show how to use com.intellij.psi.PsiElement#getTextOffset() . 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: ANTLRv4FoldingBuilder.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static void addRuleRefFoldingDescriptors(List<FoldingDescriptor> descriptors, PsiElement root) {
    for (RuleSpecNode specNode : PsiTreeUtil.findChildrenOfType(root, RuleSpecNode.class)) {
        GrammarElementRefNode refNode = PsiTreeUtil.findChildOfAnyType(specNode, GrammarElementRefNode.class);
        if (refNode == null) continue;
        PsiElement nextSibling = refNode.getNextSibling();
        if (nextSibling == null) continue;
        int startOffset = nextSibling.getTextOffset();

        ASTNode backward = TreeUtil.findChildBackward(specNode.getNode(), SEMICOLON);
        if (backward == null) continue;
        int endOffset = backward.getTextRange().getEndOffset();
        if (startOffset >= endOffset) continue;

        descriptors.add(new FoldingDescriptor(specNode, new TextRange(startOffset, endOffset)));

    }
}
 
Example 2
Source File: HaxeCompilerServices.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
private int recalculateFileOffset(@NotNull PsiFile file, @NotNull PsiElement position, Editor editor) {
    int offset = position.getTextOffset();;

    VirtualFile virtualFile = file.getVirtualFile();
    if (null == virtualFile) {  // In memory file, the position doesn't change.
        return offset;
    }

    // Get the separator, checking the file if we don't know yet.  May still return null.
    String separator = LoadTextUtil.detectLineSeparator(virtualFile, true);

    // IntelliJ IDEA normalizes file line endings, so if file line endings is
    // CRLF - then we have to shift an offset so Haxe compiler could get proper offset
    if (LineSeparator.CRLF.getSeparatorString().equals(separator)) {
        int lineNumber =
            com.intellij.openapi.util.text.StringUtil.offsetToLineNumber(editor.getDocument().getText(), offset);
        offset += lineNumber;
    }
    return offset;
}
 
Example 3
Source File: IdeHelper.java    From yiistorm with MIT License 6 votes vote down vote up
public static void navigateToPsiElement(PsiElement psiElement) {
    Project project = psiElement.getProject();
    PsiElement navElement = psiElement.getNavigationElement();
    navElement = TargetElementUtilBase.getInstance().getGotoDeclarationTarget(psiElement, navElement);
    if (navElement instanceof Navigatable) {
        if (((Navigatable) navElement).canNavigate()) {
            ((Navigatable) navElement).navigate(true);
        }
    } else if (navElement != null) {
        int navOffset = navElement.getTextOffset();
        VirtualFile virtualFile = PsiUtilCore.getVirtualFile(navElement);
        if (virtualFile != null) {
            new OpenFileDescriptor(project, virtualFile, navOffset).navigate(true);
        }
    }
}
 
Example 4
Source File: FluidUtil.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
public static PsiElement retrieveFluidElementAtPosition(PsiElement psiElement) {
    FileViewProvider viewProvider = psiElement.getContainingFile().getViewProvider();
    if (!viewProvider.getLanguages().contains(FluidLanguage.INSTANCE)) {
        return null;
    }

    int textOffset = psiElement.getTextOffset();
    FluidFile psi = (FluidFile) viewProvider.getPsi(FluidLanguage.INSTANCE);

    if (psiElement instanceof XmlAttributeValue) {
        textOffset += 2;
    }

    PsiElement elementAt = psi.findElementAt(textOffset);
    if (elementAt == null) {
        return null;
    }

    if (elementAt.getNode().getElementType().equals(FluidTypes.IDENTIFIER)) {
        return elementAt.getParent();
    }

    return null;
}
 
Example 5
Source File: HaxeColorAnnotator.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
private static void annotateCompilationExpression(PsiElement node, AnnotationHolder holder) {
  final Set<String> definitions = HaxeProjectSettings.getInstance(node.getProject()).getUserCompilerDefinitionsAsSet();
  final String nodeText = node.getText();
  for (Pair<String, Integer> pair : HaxeStringUtil.getWordsWithOffset(nodeText)) {
    final String word = pair.getFirst();
    final int offset = pair.getSecond();
    final int absoluteOffset = node.getTextOffset() + offset;
    final TextRange range = new TextRange(absoluteOffset, absoluteOffset + word.length());
    final Annotation annotation = holder.createInfoAnnotation(range, null);
    final String attributeName = definitions.contains(word) ? HaxeSyntaxHighlighterColors.HAXE_DEFINED_VAR
                                                            : HaxeSyntaxHighlighterColors.HAXE_UNDEFINED_VAR;
    annotation.setTextAttributes(TextAttributesKey.find(attributeName));
    annotation.registerFix(new HaxeDefineIntention(word, definitions.contains(word)), range);
  }
}
 
Example 6
Source File: CsvIntentionHelper.java    From intellij-csv-validator with Apache License 2.0 5 votes vote down vote up
public static int getOpeningQuotePosition(PsiElement firstFieldElement, PsiElement lastFieldElement) {
    if (CsvHelper.getElementType(firstFieldElement) != CsvTypes.QUOTE) {
        return firstFieldElement.getTextOffset();
    }
    if (CsvHelper.getElementType(lastFieldElement) == CsvTypes.QUOTE) {
        return lastFieldElement.getTextOffset();
    }
    return -1;
}
 
Example 7
Source File: JumpToAttachPointAction.java    From needsmoredojo with Apache License 2.0 5 votes vote down vote up
private void jumpToElementInTemplate(PsiFile templateFile, PsiElement sourceElement)
{
    if(!AMDValidator.elementIsAttachPoint(sourceElement))
    {
        Notifications.Bus.notify(new Notification("needsmoredojo", "Jump To Attach Point", "Element is not an attach point or is in an invalid statement with an attach point: '" + sourceElement.getText() + "'", NotificationType.INFORMATION));
        return;
    }

    FileEditorManager.getInstance(templateFile.getProject()).openFile(templateFile.getVirtualFile(), true, true);
    Editor editor = EditorFactory.getInstance().getEditors(PsiDocumentManager.getInstance(templateFile.getProject()).getDocument(templateFile))[0];

    PsiElement templateElement = TemplatedWidgetUtil.getAttachPointElementInHtmlFile(sourceElement, templateFile);

    if(templateElement == null)
    {
        Notifications.Bus.notify(new Notification("needsmoredojo", "Jump To Attach Point", "Attach point not found in " + templateFile.getVirtualFile().getName() + ": '" + sourceElement.getText() + "'", NotificationType.INFORMATION));
    }

    int index = templateElement.getTextOffset();
    editor.getCaretModel().moveToOffset(index);
    editor.getScrollingModel().scrollToCaret(ScrollType.CENTER);

    List<PsiElement> elementsToHighlight = new ArrayList<PsiElement>();
    elementsToHighlight.add(templateElement);
    if(templateElement.getNextSibling() != null)
    {
        elementsToHighlight.add(templateElement.getNextSibling());
        if(templateElement.getNextSibling().getNextSibling() != null)
        {
            elementsToHighlight.add(templateElement.getNextSibling().getNextSibling());
        }
    }

    HighlightingUtil.highlightElement(editor, templateFile.getProject(), elementsToHighlight.toArray(new PsiElement[0]));
}
 
Example 8
Source File: CsvHelper.java    From intellij-csv-validator with Apache License 2.0 5 votes vote down vote up
public static int getFieldEndOffset(PsiElement field) {
    PsiElement separator = CsvHelper.getNextSeparator(field);
    if (separator == null) {
        separator = getNextCRLF(field.getParent());
    }
    return separator == null ? field.getContainingFile().getTextLength() : separator.getTextOffset();
}
 
Example 9
Source File: CSharpStubParameterImpl.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Override
public int getTextOffset()
{
	PsiElement nameIdentifier = getNameIdentifier();
	return nameIdentifier == null ? super.getTextOffset() : nameIdentifier.getTextOffset();
}
 
Example 10
Source File: HaxeSurroundDescriptor.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@NotNull
@Override
public PsiElement[] getElementsToSurround(PsiFile file, int startOffset, int endOffset) {
  final List<PsiElement> path = UsefulPsiTreeUtil.getPathToParentOfType(file.findElementAt(startOffset), HaxeBlockStatement.class);
  if (path == null || path.size() < 2) {
    return PsiElement.EMPTY_ARRAY;
  }
  final List<PsiElement> result = new ArrayList<PsiElement>();
  PsiElement child = path.get(path.size() - 2);
  while (child != null && child.getTextOffset() < endOffset) {
    result.add(child);
    child = child.getNextSibling();
  }
  return result.toArray(new PsiElement[result.size()]);
}
 
Example 11
Source File: CSharpTupleElementImpl.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Override
public int getTextOffset()
{
	PsiElement nameIdentifier = getNameIdentifier();
	return nameIdentifier == null ? super.getTextOffset() : nameIdentifier.getTextOffset();
}
 
Example 12
Source File: MemberChooser.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public int compare(ElementNode n1, ElementNode n2) {
  if (n1.getDelegate() instanceof ClassMemberWithElement && n2.getDelegate() instanceof ClassMemberWithElement) {
    PsiElement element1 = ((ClassMemberWithElement)n1.getDelegate()).getElement();
    PsiElement element2 = ((ClassMemberWithElement)n2.getDelegate()).getElement();
    if (!(element1 instanceof PsiCompiledElement) && !(element2 instanceof PsiCompiledElement)) {
      return element1.getTextOffset() - element2.getTextOffset();
    }
  }
  return n1.getOrder() - n2.getOrder();
}
 
Example 13
Source File: AbstractNamedNode.java    From protobuf-jetbrains-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public int getTextOffset() {
    PsiElement id = getNameIdentifier();
    return id != null ? id.getTextOffset() : super.getTextOffset();
}
 
Example 14
Source File: MoveElementLeftRightActionHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public int compare(PsiElement o1, PsiElement o2) {
  return o1.getTextOffset() - o2.getTextOffset();
}
 
Example 15
Source File: CSharpLightPropertyDeclarationBuilder.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
@Override
public int getTextOffset()
{
	PsiElement nameIdentifier = getNameIdentifier();
	return nameIdentifier == null ? super.getTextOffset() : nameIdentifier.getTextOffset();
}
 
Example 16
Source File: XQueryPsiImplUtil.java    From intellij-xquery with Apache License 2.0 4 votes vote down vote up
public static int getTextOffset(XQueryVarName element) {
    if (element == null) return 0;
    PsiElement nameIdentifier = getNameIdentifier(element);
    if (nameIdentifier == null) return endOfColon(element);
    return nameIdentifier.getTextOffset();
}
 
Example 17
Source File: XQueryPsiImplUtil.java    From intellij-xquery with Apache License 2.0 4 votes vote down vote up
public static int getTextOffset(XQueryFunctionName element) {
    if (element == null) return 0;
    PsiElement nameIdentifier = getNameIdentifier(element);
    if (nameIdentifier == null) return endOfColon(element);
    return nameIdentifier.getTextOffset();
}
 
Example 18
Source File: XQueryPsiImplUtil.java    From intellij-xquery with Apache License 2.0 4 votes vote down vote up
public static int getTextOffset(XQueryXmlTagName element) {
    if (element == null) return 0;
    PsiElement nameIdentifier = getNameIdentifier(element);
    if (nameIdentifier == null) return endOfColon(element);
    return nameIdentifier.getTextOffset();
}
 
Example 19
Source File: TestLineMarkerContributor.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@NotNull
private static Icon getTestStateIcon(@NotNull PsiElement element, @NotNull Icon defaultIcon) {
  // SMTTestProxy maps test run data to a URI derived from a location hint produced by `package:test`.
  // If we can find corresponding data, we can provide state-aware icons. If not, we default to
  // a standard Run state.

  PsiFile containingFile;
  try {
    containingFile = element.getContainingFile();
  }
  catch (PsiInvalidElementAccessException e) {
    containingFile = null;
  }

  final Project project = element.getProject();
  final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);

  final Document document = containingFile == null ? null : psiDocumentManager.getDocument(containingFile);
  if (document != null) {
    final int textOffset = element.getTextOffset();
    final int lineNumber = document.getLineNumber(textOffset);

    // e.g., dart_location:///Users/pq/IdeaProjects/untitled1298891289891/test/unit_test.dart,3,2,["my first unit test"]
    final String path = FileUtil.toSystemIndependentName(containingFile.getVirtualFile().getPath());
    final String testLocationPrefix = "dart_location://" + path + "," + lineNumber;

    final TestStateStorage storage = TestStateStorage.getInstance(project);
    if (storage != null) {
      final Map<String, TestStateStorage.Record> tests = storage.getRecentTests(SCANNED_TEST_RESULT_LIMIT, getSinceDate());
      if (tests != null) {
        // TODO(pq): investigate performance implications.
        for (Map.Entry<String, TestStateStorage.Record> entry : tests.entrySet()) {
          if (entry.getKey().startsWith(testLocationPrefix)) {
            final TestStateStorage.Record state = entry.getValue();
            final TestStateInfo.Magnitude magnitude = TestIconMapper.getMagnitude(state.magnitude);
            if (magnitude != null) {
              switch (magnitude) {
                case IGNORED_INDEX:
                  return AllIcons.RunConfigurations.TestState.Yellow2;
                case ERROR_INDEX:
                case FAILED_INDEX:
                  return AllIcons.RunConfigurations.TestState.Red2;
                case PASSED_INDEX:
                case COMPLETE_INDEX:
                  return AllIcons.RunConfigurations.TestState.Green2;
                default:
              }
            }
          }
        }
      }
    }
  }

  return defaultIcon;
}
 
Example 20
Source File: XQueryXmlSlashTypedHandler.java    From intellij-xquery with Apache License 2.0 4 votes vote down vote up
private boolean isAtTheSlashOfClosingOfEmptyTag(int offset, PsiElement element) {
    return element != null && element.getNode() != null
            && element.getNode().getElementType() == XQueryTypes.XMLEMPTYELEMENTEND
            && offset == element.getTextOffset();
}