Java Code Examples for com.intellij.psi.PsiReference#getElement()

The following examples show how to use com.intellij.psi.PsiReference#getElement() . 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: GenericInlineHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void collectConflicts(final PsiReference reference,
                                    final PsiElement element,
                                    final Map<Language, InlineHandler.Inliner> inliners,
                                    final MultiMap<PsiElement, String> conflicts) {
  final PsiElement referenceElement = reference.getElement();
  if (referenceElement == null) return;
  final Language language = referenceElement.getLanguage();
  final InlineHandler.Inliner inliner = inliners.get(language);
  if (inliner != null) {
    final MultiMap<PsiElement, String> refConflicts = inliner.getConflicts(reference, element);
    if (refConflicts != null) {
      for (PsiElement psiElement : refConflicts.keySet()) {
        conflicts.putValues(psiElement, refConflicts.get(psiElement));
      }
    }
  }
  else {
    conflicts.putValue(referenceElement, "Cannot inline reference from " + language.getID());
  }
}
 
Example 2
Source File: GenericInlineHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static Map<Language, InlineHandler.Inliner> initializeInliners(PsiElement element,
                                                                      InlineHandler.Settings settings,
                                                                      Collection<? extends PsiReference> allReferences) {
  final Map<Language, InlineHandler.Inliner> inliners = new HashMap<Language, InlineHandler.Inliner>();
  for (PsiReference ref : allReferences) {
    if (ref == null) {
      LOG.error("element: " + element.getClass()+ ", allReferences contains null!");
      continue;
    }
    PsiElement refElement = ref.getElement();
    LOG.assertTrue(refElement != null, ref.getClass().getName());

    final Language language = refElement.getLanguage();
    if (inliners.containsKey(language)) continue;

    final List<InlineHandler> handlers = InlineHandlers.getInlineHandlers(language);
    for (InlineHandler handler : handlers) {
      InlineHandler.Inliner inliner = handler.createInliner(element, settings);
      if (inliner != null) {
        inliners.put(language, inliner);
        break;
      }
    }
  }
  return inliners;
}
 
Example 3
Source File: FunctionResolveTestCase.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
@NotNull
private PsiElement doCheckFunctionReference(boolean dumbMode) throws Exception {
    boolean oldDumb = DumbService.isDumb(myProject);

    DumbServiceImpl.getInstance(myProject).setDumb(dumbMode);
    try {
        PsiReference psiReference = configure();
        Assert.assertTrue(psiReference.getElement() instanceof BashCommand);
        BashCommand commandElement = (BashCommand) psiReference.getElement();

        Assert.assertTrue(psiReference.resolve() instanceof BashFunctionDef);
        Assert.assertTrue(commandElement.isFunctionCall());
        Assert.assertFalse(commandElement.isVarDefCommand());
        Assert.assertFalse(commandElement.isExternalCommand());
        Assert.assertTrue(commandElement.getReference().isReferenceTo(psiReference.resolve()));

        return psiReference.resolve();
    } finally {
        DumbServiceImpl.getInstance(myProject).setDumb(oldDumb);
    }
}
 
Example 4
Source File: LegacyCompletionContributor.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void processReference(final CompletionResultSet result,
                                     final int startOffset,
                                     final PairConsumer<PsiReference, CompletionResultSet> consumer,
                                     final PsiReference reference) {
  PsiElement element = reference.getElement();
  final int offsetInElement = startOffset - element.getTextRange().getStartOffset();
  if (!ReferenceRange.containsOffsetInElement(reference, offsetInElement)) {
    return;
  }

  TextRange range = reference.getRangeInElement();
  try {
    final String prefix = element.getText().substring(range.getStartOffset(), offsetInElement);
    consumer.consume(reference, result.withPrefixMatcher(prefix));
  }
  catch (StringIndexOutOfBoundsException e) {
    LOG.error("Reference=" + reference +
              "; element=" + element + " of " + element.getClass() +
              "; range=" + range +
              "; offset=" + offsetInElement,
              e);
  }
}
 
Example 5
Source File: StepCompletionContributor.java    From Intellij-Plugin with Apache License 2.0 6 votes vote down vote up
public static String getPrefix(CompletionParameters parameters) {
    PsiElement insertedElement = parameters.getPosition();
    int offsetInFile = parameters.getOffset();

    PsiReference ref = insertedElement.getContainingFile().findReferenceAt(offsetInFile);
    if (isStep(insertedElement) && ref != null) {
        List<TextRange> ranges = ReferenceRange.getRanges(ref);
        PsiElement element = ref.getElement();
        int startOffset = element.getTextRange().getStartOffset();
        for (TextRange range : ranges) {
            if (range.contains(offsetInFile - startOffset)) {
                int endIndex = offsetInFile - startOffset;
                int startIndex = range.getStartOffset();
                return StringUtil.trimStart(element.getText().substring(startIndex + 1, endIndex), " ");
            }
        }

    }
    return parameters.getPosition().getText().replace("IntellijIdeaRulezzz ", "").trim();
}
 
Example 6
Source File: CSharpMemberInplaceRenamer.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean acceptReference(PsiReference reference)
{
	final PsiElement element = reference.getElement();
	final TextRange textRange = reference.getRangeInElement();
	final String referenceText = element.getText().substring(textRange.getStartOffset(), textRange.getEndOffset());
	return Comparing.strEqual(CSharpPsiUtilImpl.getNameWithoutAt(referenceText), myElementToRename.getName());
}
 
Example 7
Source File: ExternalJavaDocAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static PsiElement getElement(DataContext dataContext, Editor editor) {
  PsiElement element = dataContext.getData(CommonDataKeys.PSI_ELEMENT);
  if (element == null && editor != null) {
    PsiReference reference = TargetElementUtil.findReference(editor, editor.getCaretModel().getOffset());
    if (reference != null) {
      element = reference.getElement();
    }
  }
  return element;
}
 
Example 8
Source File: HighlightManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void addOccurrenceHighlights(@Nonnull Editor editor,
                                    @Nonnull PsiReference[] occurrences,
                                    @Nonnull TextAttributes attributes,
                                    boolean hideByTextChange,
                                    Collection<RangeHighlighter> outHighlighters) {
  if (occurrences.length == 0) return;
  int flags = HIDE_BY_ESCAPE;
  if (hideByTextChange) {
    flags |= HIDE_BY_TEXT_CHANGE;
  }
  Color scrollmarkColor = getScrollMarkColor(attributes);

  int oldOffset = editor.getCaretModel().getOffset();
  int horizontalScrollOffset = editor.getScrollingModel().getHorizontalScrollOffset();
  int verticalScrollOffset = editor.getScrollingModel().getVerticalScrollOffset();
  for (PsiReference occurrence : occurrences) {
    PsiElement element = occurrence.getElement();
    int startOffset = element.getTextRange().getStartOffset();
    int start = startOffset + occurrence.getRangeInElement().getStartOffset();
    int end = startOffset + occurrence.getRangeInElement().getEndOffset();
    PsiFile containingFile = element.getContainingFile();
    Project project = element.getProject();
    // each reference can reside in its own injected editor
    Editor textEditor = InjectedLanguageUtil.openEditorFor(containingFile, project);
    if (textEditor != null) {
      addOccurrenceHighlight(textEditor, start, end, attributes, flags, outHighlighters, scrollmarkColor);
    }
  }
  editor.getCaretModel().moveToOffset(oldOffset);
  editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
  editor.getScrollingModel().scrollHorizontally(horizontalScrollOffset);
  editor.getScrollingModel().scrollVertically(verticalScrollOffset);
}
 
Example 9
Source File: FindUsagesHelper.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean processUsagesInText(@Nonnull final PsiElement element,
                                             @Nonnull Collection<String> stringToSearch,
                                             @Nonnull GlobalSearchScope searchScope,
                                             @Nonnull Processor<UsageInfo> processor) {
  final TextRange elementTextRange = ApplicationManager.getApplication().runReadAction(new NullableComputable<TextRange>() {
    @Override
    public TextRange compute() {
      if (!element.isValid() || element instanceof PsiCompiledElement) return null;
      return element.getTextRange();
    }
  });
  UsageInfoFactory factory = new UsageInfoFactory() {
    @Override
    public UsageInfo createUsageInfo(@Nonnull PsiElement usage, int startOffset, int endOffset) {
      if (elementTextRange != null
          && usage.getContainingFile() == element.getContainingFile()
          && elementTextRange.contains(startOffset)
          && elementTextRange.contains(endOffset)) {
        return null;
      }

      PsiReference someReference = usage.findReferenceAt(startOffset);
      if (someReference != null) {
        PsiElement refElement = someReference.getElement();
        for (PsiReference ref : PsiReferenceService.getService().getReferences(refElement, new PsiReferenceService.Hints(element, null))) {
          if (element.getManager().areElementsEquivalent(ref.resolve(), element)) {
            TextRange range = ref.getRangeInElement().shiftRight(refElement.getTextRange().getStartOffset() - usage.getTextRange().getStartOffset());
            return new UsageInfo(usage, range.getStartOffset(), range.getEndOffset(), true);
          }
        }
      }

      return new UsageInfo(usage, startOffset, endOffset, true);
    }
  };
  for (String s : stringToSearch) {
    if (!PsiSearchHelperImpl.processTextOccurrences(element, s, searchScope, processor, factory)) return false;
  }
  return true;
}
 
Example 10
Source File: HaxeFindUsagesHandler.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@NotNull
private static ReadActionProcessor<PsiReference> getConstructorSearchProcessor(@NotNull Processor<UsageInfo> processor) {
  return new ReadActionProcessor<PsiReference>() {
    @Override
    public boolean processInReadAction(PsiReference reference) {
      PsiElement refElement = reference.getElement();
      final PsiElement parent = refElement.getParent();
      if (parent instanceof HaxeType && parent.getParent() instanceof HaxeNewExpression) {
        TextRange rangeInElement = reference.getRangeInElement();
        processor.process(new UsageInfo(refElement, rangeInElement.getStartOffset(), rangeInElement.getEndOffset(), false));
      }
      return true;
    }
  };
}
 
Example 11
Source File: RouteFoldingBuilder.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
@Nullable
private FoldingDescriptor foldRouteReferenceString(PsiReference reference, String value, FoldingGroup group) {
    PsiElement element = reference.getElement();
    TextRange foldingRange = new TextRange(element.getTextRange().getStartOffset() + 1, element.getTextRange().getEndOffset() - 1);

    if (!RouteIndex.hasRoute(element.getProject(), value)) {
        return null;
    }

    Collection<RouteStub> route = RouteIndex.getRoute(element.getProject(), value);
    if (route.size() == 0) {
        return null;
    }

    RouteStub routeDef = route.iterator().next();

    return new FoldingDescriptor(element.getNode(), foldingRange, group) {
        @Nullable
        @Override
        public String getPlaceholderText() {
            if (routeDef.getPath() == null) {
                return routeDef.getController() + "::" + routeDef.getMethod();
            }

            return routeDef.getPath();
        }
    };
}
 
Example 12
Source File: HaskellResolveTestCase.java    From intellij-haskforce with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();
    for (File file : getTestDataFiles()) {
        if (file.isDirectory()) continue;
        String text = FileUtil.loadFile(file, CharsetToolkit.UTF8);
        text = StringUtil.convertLineSeparators(text);
        int referencedOffset = text.indexOf("<ref>");
        text = text.replace("<ref>", "");
        int resolvedOffset = text.indexOf("<resolved>");
        text = text.replace("<resolved>", "");
        String relativePath = file.getCanonicalPath().substring(
          file.getCanonicalPath().indexOf(getTestDataPath()) + getTestDataPath().length() + 1
        );
        VirtualFile vFile = myFixture.getTempDirFixture().createFile(relativePath, text);
        PsiFile psiFile = myFixture.configureFromTempProjectFile(relativePath);
        if (referencedOffset != -1) {
            referencedElement = psiFile.findReferenceAt(referencedOffset);
            if (referencedElement == null) fail("Reference was null in " + file.getName());
        }
        if (resolvedOffset != -1) {
            final PsiReference ref = psiFile.findReferenceAt(resolvedOffset);
            if (ref == null) { fail("Reference was null in " + file.getName()); }
            resolvedElement = ref.getElement();
            if (resolvedElement == null) { fail("Reference returned null element in " + file.getName()); }
        }
    }
}
 
Example 13
Source File: PantsUnresolvedReferenceFixFinder.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
@NotNull
public static List<PantsQuickFix> findMissingDependencies(@NotNull PsiReference reference) {
  final PsiElement unresolvedPsiElement = reference.getElement();
  @NonNls final String referenceName = reference.getRangeInElement().substring(unresolvedPsiElement.getText());

  final PsiFile containingFile = unresolvedPsiElement.getContainingFile();
  return containingFile != null ? findMissingDependencies(referenceName, containingFile) : Collections.<PantsQuickFix>emptyList();
}
 
Example 14
Source File: DeletionMarkingVisitor.java    From JHelper with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void removeIfNoReference(OCElement element) {
	for (PsiReference reference : ReferencesSearch.search(element, searchScope)) {
		PsiElement referenceElement = reference.getElement();
		if (!isParentFor(element, referenceElement)) {
			return;
		}
	}
	toDelete.add(element);
}
 
Example 15
Source File: BlazeGoAnnotatorTest.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static void assertNoAnnotations(@Nullable PsiReference reference) {
  assertThat(reference).isNotNull();
  PsiElement element = reference.getElement();
  AnnotationHolderImpl holder =
      new AnnotationHolderImpl(new AnnotationSession(element.getContainingFile()));
  new GoAnnotator().annotate(element, holder);
  assertThat(holder).isEmpty();
}
 
Example 16
Source File: BuildTargetElementEvaluator.java    From intellij with Apache License 2.0 5 votes vote down vote up
/** Returns null in the cases where we're happy with the default behavior. */
@Nullable
@Override
public PsiElement getElementByReference(PsiReference ref, int flags) {
  if (!(ref instanceof PsiMultiReference) || !(ref.getElement() instanceof StringLiteral)) {
    return null;
  }
  // choose the outer-most reference
  PsiReference[] refs = ((PsiMultiReference) ref).getReferences().clone();
  Arrays.sort(refs, COMPARATOR);
  return refs[0].resolve();
}
 
Example 17
Source File: SoyIdentifierManipulator.java    From bamboo-soy with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public PsiElement handleContentChange(
    @NotNull PsiElement element, @NotNull TextRange range, String newContent)
    throws IncorrectOperationException {
  if (element instanceof IdentifierMixin) {
    IdentifierMixin identifierMixin = (IdentifierMixin) element;
    PsiReference reference = identifierMixin.getReference();
    if (reference != null && reference.getElement() instanceof PsiNamedElement) {
      ((PsiNamedElement) reference.getElement()).setName(newContent);
    }
  }
  return ((PsiNamedElement) element).setName(newContent);
}
 
Example 18
Source File: ReferenceDescriptor.java    From consulo with Apache License 2.0 4 votes vote down vote up
public ReferenceDescriptor fun(PsiReference psiReference) {
  final PsiElement element = psiReference.getElement();
  final PsiFile file = element.getContainingFile();
  return new ReferenceDescriptor(file, element.getTextRange().getStartOffset() + psiReference.getRangeInElement().getStartOffset());
}
 
Example 19
Source File: TemplateBuilderImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
private RangeMarker wrapReference(final PsiReference ref) {
  PsiElement element = ref.getElement();
  return myDocument.createRangeMarker(ref.getRangeInElement().shiftRight(
    InjectedLanguageManager.getInstance(myFile.getProject()).injectedToHost(element, element.getTextRange().getStartOffset())
  ));
}