com.intellij.lang.injection.InjectedLanguageManager Java Examples

The following examples show how to use com.intellij.lang.injection.InjectedLanguageManager. 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: CompletionInitializationUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
static OffsetsInFile toInjectedIfAny(PsiFile originalFile, OffsetsInFile hostCopyOffsets) {
  CompletionAssertions.assertHostInfo(hostCopyOffsets.getFile(), hostCopyOffsets.getOffsets());

  int hostStartOffset = hostCopyOffsets.getOffsets().getOffset(CompletionInitializationContext.START_OFFSET);
  OffsetsInFile translatedOffsets = hostCopyOffsets.toInjectedIfAny(hostStartOffset);
  if (translatedOffsets != hostCopyOffsets) {
    PsiFile injected = translatedOffsets.getFile();
    if (originalFile != injected && injected instanceof PsiFileImpl && InjectedLanguageManager.getInstance(originalFile.getProject()).isInjectedFragment(originalFile)) {
      ((PsiFileImpl)injected).setOriginalFile(originalFile);
    }
    DocumentWindow documentWindow = InjectedLanguageUtil.getDocumentWindow(injected);
    CompletionAssertions.assertInjectedOffsets(hostStartOffset, injected, documentWindow);

    if (injected.getTextRange().contains(translatedOffsets.getOffsets().getOffset(CompletionInitializationContext.START_OFFSET))) {
      return translatedOffsets;
    }
  }

  return hostCopyOffsets;
}
 
Example #2
Source File: LookupImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static int insertLookupInDocumentWindowIfNeeded(Project project, Editor editor, int caretOffset, int prefix, String lookupString) {
  DocumentWindow document = getInjectedDocument(project, editor, caretOffset);
  if (document == null) return insertLookupInDocument(caretOffset, editor.getDocument(), prefix, lookupString);
  PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
  int offset = document.hostToInjected(caretOffset);
  int lookupStart = Math.min(offset, Math.max(offset - prefix, 0));
  int diff = -1;
  if (file != null) {
    List<TextRange> ranges = InjectedLanguageManager.getInstance(project).intersectWithAllEditableFragments(file, TextRange.create(lookupStart, offset));
    if (!ranges.isEmpty()) {
      diff = ranges.get(0).getStartOffset() - lookupStart;
      if (ranges.size() == 1 && diff == 0) diff = -1;
    }
  }
  if (diff == -1) return insertLookupInDocument(caretOffset, editor.getDocument(), prefix, lookupString);
  return document.injectedToHost(insertLookupInDocument(offset, document, prefix - diff, diff == 0 ? lookupString : lookupString.substring(diff)));
}
 
Example #3
Source File: InjectionReferenceTest.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
@NotNull
private PsiElement findInjectedBashReference(String fileName, String lookupText) {
    PsiElement javaLiteral = configurePsiAtCaret(fileName);
    Assert.assertTrue(javaLiteral instanceof PsiLanguageInjectionHost);

    //inject bash into the literal
    InjectLanguageAction.invokeImpl(getProject(), myFixture.getEditor(), javaLiteral.getContainingFile(), Injectable.fromLanguage(BashFileType.BASH_LANGUAGE));

    String fileContent = javaLiteral.getContainingFile().getText();
    PsiElement bashPsiLeaf = InjectedLanguageManager.getInstance(getProject()).findInjectedElementAt(myFixture.getFile(), fileContent.indexOf(lookupText) + 1);
    Assert.assertNotNull(bashPsiLeaf);

    PsiElement reference = PsiTreeUtil.findFirstParent(bashPsiLeaf, psiElement -> psiElement.getReference() != null);
    Assert.assertNotNull(reference);

    return reference;
}
 
Example #4
Source File: BladeInjectTypeProvider.java    From idea-php-laravel-plugin with MIT License 6 votes vote down vote up
/**
 *  Resolve PHP language injection in Blade
 *
 *  @see BladeVariableTypeProvider#getHostPhpFileForInjectedIfExists
 */
@Nullable
private static BladeFileImpl getHostBladeFileForInjectionIfExists(PsiElement element) {
    PsiFile file = element.getContainingFile();
    InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(element.getProject());
    if (injectedLanguageManager.isInjectedFragment(file)) {
        PsiLanguageInjectionHost host = injectedLanguageManager.getInjectionHost(element);
        if (host instanceof BladePsiLanguageInjectionHost && host.isValidHost()) {
            PsiFile bladeFile = host.getContainingFile();
            if (bladeFile instanceof BladeFileImpl) {
                return (BladeFileImpl) bladeFile;
            }
        }
    }

    return null;
}
 
Example #5
Source File: CodeStyleManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static Pair<PsiElement, CharTable> doFindWhiteSpaceNode(@Nonnull PsiFile file, int offset) {
  ASTNode astNode = SourceTreeToPsiMap.psiElementToTree(file);
  if (!(astNode instanceof FileElement)) {
    return new Pair<>(null, null);
  }
  PsiElement elementAt = InjectedLanguageManager.getInstance(file.getProject()).findInjectedElementAt(file, offset);
  final CharTable charTable = ((FileElement)astNode).getCharTable();
  if (elementAt == null) {
    elementAt = findElementInTreeWithFormatterEnabled(file, offset);
  }

  if (elementAt == null) {
    return new Pair<>(null, charTable);
  }
  ASTNode node = elementAt.getNode();
  if (node == null || node.getElementType() != TokenType.WHITE_SPACE) {
    return new Pair<>(null, charTable);
  }
  return Pair.create(elementAt, charTable);
}
 
Example #6
Source File: BladePsiUtil.java    From idea-php-laravel-plugin with MIT License 6 votes vote down vote up
/**
 * Crazy shit to find component directive for a given slot
 * Blade Plugin do not provide a nested tree!
 *
 * "@component('layouts.app')"
 *  "@slot('title')"
 *      Home Page
 *  "@endslot"
 * "@endcomponent"
 */
@Nullable
public static String findComponentForSlotScope(@NotNull PsiElement psiDirectiveParameter) {
    PsiElement bladeHost;
    if(psiDirectiveParameter.getNode().getElementType() == BladeTokenTypes.DIRECTIVE_PARAMETER_CONTENT) {
        bladeHost = psiDirectiveParameter.getParent();
    } else {
        bladeHost = InjectedLanguageManager
            .getInstance(psiDirectiveParameter.getProject())
            .getInjectionHost(psiDirectiveParameter);
    }

    if(!(bladeHost instanceof BladePsiDirectiveParameter)) {
        return null;
    }

    return findComponentForSlotScope((BladePsiDirectiveParameter) bladeHost);
}
 
Example #7
Source File: TypedHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static Editor injectedEditorIfCharTypedIsSignificant(final int charTyped, @Nonnull Editor editor, @Nonnull PsiFile oldFile) {
  int offset = editor.getCaretModel().getOffset();
  // even for uncommitted document try to retrieve injected fragment that has been there recently
  // we are assuming here that when user is (even furiously) typing, injected language would not change
  // and thus we can use its lexer to insert closing braces etc
  List<DocumentWindow> injected = InjectedLanguageManager.getInstance(oldFile.getProject()).getCachedInjectedDocumentsInRange(oldFile, ProperTextRange.create(offset, offset));
  for (DocumentWindow documentWindow : injected) {
    if (documentWindow.isValid() && documentWindow.containsRange(offset, offset)) {
      PsiFile injectedFile = PsiDocumentManager.getInstance(oldFile.getProject()).getPsiFile(documentWindow);
      if (injectedFile != null) {
        Editor injectedEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(editor, injectedFile);
        // IDEA-52375/WEB-9105 fix: last quote in editable fragment should be handled by outer language quote handler
        TextRange hostRange = documentWindow.getHostRange(offset);
        CharSequence sequence = editor.getDocument().getCharsSequence();
        if (sequence.length() > offset && charTyped != Character.codePointAt(sequence, offset) || hostRange != null && hostRange.contains(offset)) {
          return injectedEditor;
        }
      }
    }
  }

  return editor;
}
 
Example #8
Source File: TrafficLightRenderer.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public boolean canClosePopup() {
  if (myAdditionalPanels.isEmpty()) {
    return true;
  }
  if (myAdditionalPanels.stream().allMatch(p -> p.canClose())) {
    PsiFile psiFile = getPsiFile();
    if (myAdditionalPanels.stream().filter(p -> p.isModified()).peek(TrafficLightRenderer::applyPanel).count() > 0) {
      if (psiFile != null) {
        InjectedLanguageManager.getInstance(getProject()).dropFileCaches(psiFile);
      }
      myDaemonCodeAnalyzer.restart();
    }
    return true;
  }
  return false;
}
 
Example #9
Source File: InjectedLanguageUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * @deprecated use {@link InjectedLanguageManager#enumerateEx(PsiElement, PsiFile, boolean, PsiLanguageInjectionHost.InjectedPsiVisitor)} instead
 */
@Deprecated
public static boolean enumerate(@Nonnull PsiElement host, @Nonnull PsiFile containingFile, boolean probeUp, @Nonnull PsiLanguageInjectionHost.InjectedPsiVisitor visitor) {
  //do not inject into nonphysical files except during completion
  if (!containingFile.isPhysical() && containingFile.getOriginalFile() == containingFile) {
    final PsiElement context = InjectedLanguageManager.getInstance(containingFile.getProject()).getInjectionHost(containingFile);
    if (context == null) return false;

    final PsiFile file = context.getContainingFile();
    if (file == null || !file.isPhysical() && file.getOriginalFile() == file) return false;
  }

  if (containingFile.getViewProvider() instanceof InjectedFileViewProvider) return false; // no injection inside injection

  PsiElement inTree = loadTree(host, containingFile);
  if (inTree != host) {
    host = inTree;
    containingFile = host.getContainingFile();
  }
  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(containingFile.getProject());
  Document document = documentManager.getDocument(containingFile);
  if (document == null || documentManager.isCommitted(document)) {
    probeElementsUp(host, containingFile, probeUp, visitor);
  }
  return true;
}
 
Example #10
Source File: HighlightManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void addOccurrenceHighlights(@Nonnull Editor editor,
                                    @Nonnull PsiElement[] elements,
                                    @Nonnull TextAttributes attributes,
                                    boolean hideByTextChange,
                                    Collection<RangeHighlighter> outHighlighters) {
  if (elements.length == 0) return;
  int flags = HIDE_BY_ESCAPE;
  if (hideByTextChange) {
    flags |= HIDE_BY_TEXT_CHANGE;
  }

  Color scrollmarkColor = getScrollMarkColor(attributes);
  if (editor instanceof EditorWindow) {
    editor = ((EditorWindow)editor).getDelegate();
  }

  for (PsiElement element : elements) {
    TextRange range = element.getTextRange();
    range = InjectedLanguageManager.getInstance(myProject).injectedToHost(element, range);
    addOccurrenceHighlight(editor, range.getStartOffset(), range.getEndOffset(), attributes, flags, outHighlighters, scrollmarkColor);
  }
}
 
Example #11
Source File: InjectedLanguageUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static String getUnescapedText(@Nonnull PsiFile file, @Nullable final PsiElement startElement, @Nullable final PsiElement endElement) {
  final InjectedLanguageManager manager = InjectedLanguageManager.getInstance(file.getProject());
  if (manager.getInjectionHost(file) == null) {
    return file.getText().substring(startElement == null ? 0 : startElement.getTextRange().getStartOffset(), endElement == null ? file.getTextLength() : endElement.getTextRange().getStartOffset());
  }
  final StringBuilder sb = new StringBuilder();
  file.accept(new PsiRecursiveElementWalkingVisitor() {

    Boolean myState = startElement == null ? Boolean.TRUE : null;

    @Override
    public void visitElement(PsiElement element) {
      if (element == startElement) myState = Boolean.TRUE;
      if (element == endElement) myState = Boolean.FALSE;
      if (Boolean.FALSE == myState) return;
      if (Boolean.TRUE == myState && element.getFirstChild() == null) {
        sb.append(getUnescapedLeafText(element, false));
      }
      else {
        super.visitElement(element);
      }
    }
  });
  return sb.toString();
}
 
Example #12
Source File: InjectedLanguageUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Finds injected language in expression
 *
 * @param expression  where to find
 * @param classToFind class that represents language we look for
 * @param <T>         class that represents language we look for
 * @return instance of class that represents language we look for or null of not found
 */
@Nullable
@SuppressWarnings("unchecked") // We check types dynamically (using isAssignableFrom)
public static <T extends PsiFileBase> T findInjectedFile(@Nonnull final PsiElement expression, @Nonnull final Class<T> classToFind) {
  final List<Pair<PsiElement, TextRange>> files = InjectedLanguageManager.getInstance(expression.getProject()).getInjectedPsiFiles(expression);
  if (files == null) {
    return null;
  }
  for (final Pair<PsiElement, TextRange> fileInfo : files) {
    final PsiElement injectedFile = fileInfo.first;
    if (classToFind.isAssignableFrom(injectedFile.getClass())) {
      return (T)injectedFile;
    }
  }
  return null;
}
 
Example #13
Source File: BraceHighlightingHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static PsiFile getInjectedFileIfAny(@Nonnull final Editor editor,
                                            @Nonnull final Project project,
                                            int offset,
                                            @Nonnull PsiFile psiFile,
                                            @Nonnull final Alarm alarm) {
  Document document = editor.getDocument();
  // when document is committed, try to highlight braces in injected lang - it's fast
  if (PsiDocumentManager.getInstance(project).isCommitted(document)) {
    final PsiElement injectedElement = InjectedLanguageManager.getInstance(psiFile.getProject()).findInjectedElementAt(psiFile, offset);
    if (injectedElement != null /*&& !(injectedElement instanceof PsiWhiteSpace)*/) {
      final PsiFile injected = injectedElement.getContainingFile();
      if (injected != null) {
        return injected;
      }
    }
  }
  else {
    PsiDocumentManager.getInstance(project).performForCommittedDocument(document, () -> {
      if (!project.isDisposed() && !editor.isDisposed()) {
        BraceHighlighter.updateBraces(editor, alarm);
      }
    });
  }
  return psiFile;
}
 
Example #14
Source File: ProblemDescriptorBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public int getLineNumber() {
  if (myLineNumber == -1) {
    PsiElement psiElement = getPsiElement();
    if (psiElement == null) return -1;
    if (!psiElement.isValid()) return -1;
    LOG.assertTrue(psiElement.isPhysical());
    InjectedLanguageManager manager = InjectedLanguageManager.getInstance(psiElement.getProject());
    PsiFile containingFile = manager.getTopLevelFile(psiElement);
    Document document = PsiDocumentManager.getInstance(psiElement.getProject()).getDocument(containingFile);
    if (document == null) return -1;
    TextRange textRange = getTextRange();
    if (textRange == null) return -1;
    textRange = manager.injectedToHost(psiElement, textRange);
    final int startOffset = textRange.getStartOffset();
    final int textLength = document.getTextLength();
    LOG.assertTrue(startOffset <= textLength, getDescriptionTemplate() + " at " + startOffset + ", " + textLength);
    myLineNumber =  document.getLineNumber(startOffset) + 1;
  }
  return myLineNumber;
}
 
Example #15
Source File: LossyEncodingInspection.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public ProblemDescriptor[] checkFile(@Nonnull PsiFile file, @Nonnull InspectionManager manager, boolean isOnTheFly) {
  if (InjectedLanguageManager.getInstance(file.getProject()).isInjectedFragment(file)) return null;
  if (!file.isPhysical()) return null;
  FileViewProvider viewProvider = file.getViewProvider();
  if (viewProvider.getBaseLanguage() != file.getLanguage()) return null;
  VirtualFile virtualFile = file.getVirtualFile();
  if (virtualFile == null) return null;
  if (!virtualFile.isInLocalFileSystem()) return null;
  CharSequence text = viewProvider.getContents();
  Charset charset = LoadTextUtil.extractCharsetFromFileContent(file.getProject(), virtualFile, text);

  // no sense in checking transparently decoded file: all characters there are already safely encoded
  if (charset instanceof Native2AsciiCharset) return null;

  List<ProblemDescriptor> descriptors = new SmartList<ProblemDescriptor>();
  boolean ok = checkFileLoadedInWrongEncoding(file, manager, isOnTheFly, virtualFile, charset, descriptors);
  if (ok) {
    checkIfCharactersWillBeLostAfterSave(file, manager, isOnTheFly, text, charset, descriptors);
  }

  return descriptors.toArray(new ProblemDescriptor[descriptors.size()]);
}
 
Example #16
Source File: PsiViewerDialog.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void caretPositionChanged(CaretEvent e) {
  if (!available() || myEditor.getSelectionModel().hasSelection()) return;
  final ViewerTreeStructure treeStructure = (ViewerTreeStructure)myPsiTreeBuilder.getTreeStructure();
  final PsiElement rootPsiElement = treeStructure.getRootPsiElement();
  if (rootPsiElement == null) return;
  final PsiElement rootElement = ((ViewerTreeStructure)myPsiTreeBuilder.getTreeStructure()).getRootPsiElement();
  int baseOffset = rootPsiElement.getTextRange().getStartOffset();
  final int offset = myEditor.getCaretModel().getOffset() + baseOffset;
  final PsiElement element = InjectedLanguageUtil.findElementAtNoCommit(rootElement.getContainingFile(), offset);
  if (element != null && myBlockTreeBuilder != null) {
    TextRange rangeInHostFile = InjectedLanguageManager.getInstance(myProject).injectedToHost(element, element.getTextRange());
    selectBlockNode(findBlockNode(rangeInHostFile, true));
  }
  myPsiTreeBuilder.select(element);
}
 
Example #17
Source File: InjectedLanguageUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean isInInjectedLanguagePrefixSuffix(@Nonnull final PsiElement element) {
  PsiFile injectedFile = element.getContainingFile();
  if (injectedFile == null) return false;
  Project project = injectedFile.getProject();
  InjectedLanguageManager languageManager = InjectedLanguageManager.getInstance(project);
  if (!languageManager.isInjectedFragment(injectedFile)) return false;
  TextRange elementRange = element.getTextRange();
  List<TextRange> edibles = languageManager.intersectWithAllEditableFragments(injectedFile, elementRange);
  int combinedEdiblesLength = edibles.stream().mapToInt(TextRange::getLength).sum();

  return combinedEdiblesLength != elementRange.getLength();
}
 
Example #18
Source File: FoldingUpdate.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static String createSignature(@Nonnull PsiElement element) {
  String signature = FoldingPolicy.getSignature(element);
  if (signature != null && Registry.is("folding.signature.validation")) {
    PsiFile containingFile = element.getContainingFile();
    PsiElement restoredElement = FoldingPolicy.restoreBySignature(containingFile, signature);
    if (!element.equals(restoredElement)) {
      StringBuilder trace = new StringBuilder();
      PsiElement restoredAgain = FoldingPolicy.restoreBySignature(containingFile, signature, trace);
      LOG.error("element: " +
                element +
                "(" +
                element.getText() +
                "); restoredElement: " +
                restoredElement +
                "; signature: '" +
                signature +
                "'; file: " +
                containingFile +
                "; injected: " +
                InjectedLanguageManager.getInstance(element.getProject()).isInjectedFragment(containingFile) +
                "; languages: " +
                containingFile.getViewProvider().getLanguages() +
                "; restored again: " +
                restoredAgain +
                "; restore produces same results: " +
                (restoredAgain == restoredElement) +
                "; trace:\n" +
                trace);
    }
  }
  return signature;
}
 
Example #19
Source File: LookupImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static DocumentWindow getInjectedDocument(Project project, Editor editor, int offset) {
  PsiFile hostFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
  if (hostFile != null) {
    // inspired by com.intellij.codeInsight.editorActions.TypedHandler.injectedEditorIfCharTypedIsSignificant()
    List<DocumentWindow> injected = InjectedLanguageManager.getInstance(project).getCachedInjectedDocumentsInRange(hostFile, TextRange.create(offset, offset));
    for (DocumentWindow documentWindow : injected) {
      if (documentWindow.isValid() && documentWindow.containsRange(offset, offset)) {
        return documentWindow;
      }
    }
  }
  return null;
}
 
Example #20
Source File: CommentByLineCommentAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean isValidFor(@Nonnull Project project, @Nonnull Editor editor, @Nonnull Caret caret, @Nonnull final PsiFile file) {
  final FileType fileType = file.getFileType();
  if (fileType instanceof AbstractFileType) {
    return ((AbstractFileType)fileType).getCommenter() != null;
  }

  if (LanguageCommenters.INSTANCE.forLanguage(file.getLanguage()) != null || LanguageCommenters.INSTANCE.forLanguage(file.getViewProvider().getBaseLanguage()) != null) return true;
  PsiElement host = InjectedLanguageManager.getInstance(project).getInjectionHost(file);
  return host != null && LanguageCommenters.INSTANCE.forLanguage(host.getLanguage()) != null;
}
 
Example #21
Source File: ShowIntentionActionsHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void invoke(@Nonnull final Project project, @Nonnull Editor editor, @Nonnull PsiFile file, boolean showFeedbackOnEmptyMenu) {
  PsiDocumentManager.getInstance(project).commitAllDocuments();
  if (editor instanceof EditorWindow) {
    editor = ((EditorWindow)editor).getDelegate();
    file = InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file);
  }

  final LookupEx lookup = LookupManager.getActiveLookup(editor);
  if (lookup != null) {
    lookup.showElementActions(null);
    return;
  }

  final DaemonCodeAnalyzerImpl codeAnalyzer = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(project);
  letAutoImportComplete(editor, file, codeAnalyzer);

  ShowIntentionsPass.IntentionsInfo intentions = ShowIntentionsPass.getActionsToShow(editor, file, true);
  IntentionsUI.getInstance(project).hide();

  if (HintManagerImpl.getInstanceImpl().performCurrentQuestionAction()) return;

  //intentions check isWritable before modification: if (!file.isWritable()) return;

  TemplateState state = TemplateManagerImpl.getTemplateState(editor);
  if (state != null && !state.isFinished()) {
    return;
  }

  editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
  Editor finalEditor = editor;
  PsiFile finalFile = file;
  showIntentionHint(project, finalEditor, finalFile, intentions, showFeedbackOnEmptyMenu);
}
 
Example #22
Source File: InjectedLanguageUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Invocation of this method on uncommitted {@code hostFile} can lead to unexpected results, including throwing an exception!
 */
static PsiElement findInjectedElementNoCommit(@Nonnull PsiFile hostFile, final int offset) {
  if (hostFile instanceof PsiCompiledElement) return null;
  Project project = hostFile.getProject();
  if (InjectedLanguageManager.getInstance(project).isInjectedFragment(hostFile)) return null;
  final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  Trinity<PsiElement, PsiElement, Language> result = tryOffset(hostFile, offset, documentManager);
  return result.first;
}
 
Example #23
Source File: HighlightUsagesHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static List<TextRange> collectRangesToHighlight(@Nonnull PsiReference ref, @Nonnull List<TextRange> result) {
  for (TextRange relativeRange : ReferenceRange.getRanges(ref)) {
    PsiElement element = ref.getElement();
    TextRange range = safeCut(element.getTextRange(), relativeRange);
    // injection occurs
    result.add(InjectedLanguageManager.getInstance(element.getProject()).injectedToHost(element, range));
  }
  return result;
}
 
Example #24
Source File: ViewerTreeStructure.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public Object getParentElement(Object element) {
  if (element == myRootElement) {
    return null;
  }
  if (element == myRootPsiElement) {
    return myRootElement;
  }
  if (element instanceof PsiFile &&
      InjectedLanguageManager.getInstance(((PsiFile)element).getProject()).getInjectionHost(((PsiFile)element)) != null) {
    return new Inject(InjectedLanguageManager.getInstance(((PsiFile)element).getProject()).getInjectionHost(((PsiFile)element)),
                      (PsiElement)element);
  }
  return element instanceof Inject ? ((Inject)element).getParent() : ((PsiElement)element).getContext();
}
 
Example #25
Source File: HighlightUsagesHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public static TextRange getNameIdentifierRange(PsiFile file, PsiElement element) {
  final InjectedLanguageManager injectedManager = InjectedLanguageManager.getInstance(element.getProject());
  if (element instanceof PomTargetPsiElement) {
    final PomTarget target = ((PomTargetPsiElement)element).getTarget();
    if (target instanceof PsiDeclaredTarget) {
      final PsiDeclaredTarget declaredTarget = (PsiDeclaredTarget)target;
      final TextRange range = declaredTarget.getNameIdentifierRange();
      if (range != null) {
        if (range.getStartOffset() < 0 || range.getLength() <= 0) {
          return null;
        }
        final PsiElement navElement = declaredTarget.getNavigationElement();
        if (PsiUtilBase.isUnderPsiRoot(file, navElement)) {
          return injectedManager.injectedToHost(navElement, range.shiftRight(navElement.getTextRange().getStartOffset()));
        }
      }
    }
  }

  if (!PsiUtilBase.isUnderPsiRoot(file, element)) {
    return null;
  }

  PsiElement identifier = IdentifierUtil.getNameIdentifier(element);
  if (identifier != null && PsiUtilBase.isUnderPsiRoot(file, identifier)) {
    return injectedManager.injectedToHost(identifier, identifier.getTextRange());
  }
  return null;
}
 
Example #26
Source File: InjectedLanguageUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * @deprecated use {@link InjectedLanguageManager#getTopLevelFile(PsiElement)} instead
 */
@Deprecated
public static PsiFile getTopLevelFile(@Nonnull PsiElement element) {
  PsiFile containingFile = element.getContainingFile();
  if (containingFile == null) return null;
  if (containingFile.getViewProvider() instanceof InjectedFileViewProvider) {
    PsiElement host = InjectedLanguageManager.getInstance(containingFile.getProject()).getInjectionHost(containingFile);
    if (host != null) containingFile = host.getContainingFile();
  }
  return containingFile;
}
 
Example #27
Source File: PsiViewerDialog.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void valueChanged(ListSelectionEvent e) {
  clearSelection();
  updateVersionsCombo(null);
  updateExtensionsCombo();
  final int ind = myRefs.getSelectedIndex();
  final PsiElement element = getPsiElement();
  if (ind > -1 && element != null) {
    final PsiReference[] references = element.getReferences();
    if (ind < references.length) {
      final TextRange textRange = references[ind].getRangeInElement();
      TextRange range = InjectedLanguageManager.getInstance(myProject).injectedToHost(element, element.getTextRange());
      int start = range.getStartOffset();
      int end = range.getEndOffset();
      final ViewerTreeStructure treeStructure = (ViewerTreeStructure)myPsiTreeBuilder.getTreeStructure();
      PsiElement rootPsiElement = treeStructure.getRootPsiElement();
      if (rootPsiElement != null) {
        int baseOffset = rootPsiElement.getTextRange().getStartOffset();
        start -= baseOffset;
        end -= baseOffset;
      }

      start += textRange.getStartOffset();
      end = start + textRange.getLength();
      myListenerHighlighter = myEditor.getMarkupModel()
        .addRangeHighlighter(start, end, HighlighterLayer.FIRST + 1, myAttributes, HighlighterTargetArea.EXACT_RANGE);
    }
  }
}
 
Example #28
Source File: TemplateLanguageErrorFilter.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean shouldHighlightErrorElement(@Nonnull PsiErrorElement element) {
  if (isKnownSubLanguage(element.getParent().getLanguage())) {
    //
    // Immediately discard filters with non-matching template class if already known
    //
    Class templateClass = element.getUserData(TEMPLATE_VIEW_PROVIDER_CLASS_KEY);
    if (templateClass != null && (templateClass != myTemplateFileViewProviderClass)) return true;
    
    PsiFile psiFile = element.getContainingFile();
    int offset = element.getTextOffset();
    InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(element.getProject());
    if (injectedLanguageManager.isInjectedFragment(psiFile)) {
      PsiElement host = injectedLanguageManager.getInjectionHost(element);
      if (host != null) {
        psiFile = host.getContainingFile();
        offset = injectedLanguageManager.injectedToHost(element, offset);
      }
    }
    final FileViewProvider viewProvider = psiFile.getViewProvider();
    element.putUserData(TEMPLATE_VIEW_PROVIDER_CLASS_KEY, viewProvider.getClass());
    if (!(viewProvider.getClass() == myTemplateFileViewProviderClass)) {
      return true;
    }
    //
    // An error can occur at template element or before it. Check both.
    //
    if (shouldIgnoreErrorAt(viewProvider, offset) || shouldIgnoreErrorAt(viewProvider, offset + 1)) return false;
  }
  return true;
}
 
Example #29
Source File: SelectWordHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean isInsideEditableInjection(EditorWindow editor, TextRange range, Project project) {
  PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
  if (file == null) return true;
  List<TextRange> editables = InjectedLanguageManager.getInstance(project).intersectWithAllEditableFragments(file, range);

  return editables.size() == 1 && range.equals(editables.get(0));
}
 
Example #30
Source File: HighlightUsagesHandlerBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
public void addOccurrence(@Nonnull PsiElement element) {
  TextRange range = element.getTextRange();
  if (range != null) {
    range = InjectedLanguageManager.getInstance(element.getProject()).injectedToHost(element, range);
    myReadUsages.add(range);
  }
}