@NotNull protected List<HighlightInfo> doHighlighting() { PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); TIntArrayList toIgnoreList = new TIntArrayList(); if (!doFolding()) { toIgnoreList.add(Pass.UPDATE_FOLDING); } if (!doInspections()) { toIgnoreList.add(Pass.LOCAL_INSPECTIONS); toIgnoreList.add(Pass.WHOLE_FILE_LOCAL_INSPECTIONS); } int[] toIgnore = toIgnoreList.isEmpty() ? ArrayUtil.EMPTY_INT_ARRAY : toIgnoreList.toNativeArray(); Editor editor = getEditor(); PsiFile file = getFile(); if (editor instanceof EditorWindow) { editor = ((EditorWindow)editor).getDelegate(); file = InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file); } return CodeInsightTestFixtureImpl.instantiateAndRun(file, editor, toIgnore, false); }
@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; }
private void findAllStyleApplications(final VirtualFile layoutVFile, final List<UsageInfo> usages) { ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { final PsiFile layoutFile = PsiManager.getInstance(myProject).findFile(layoutVFile); if (!(layoutFile instanceof XmlFile)) { return; } if (!(DomManager.getDomManager(myProject).getDomFileDescription( (XmlFile)layoutFile) instanceof LayoutDomFileDescription)) { return; } collectPossibleStyleApplications(layoutFile, usages); PsiManager.getInstance(myProject).dropResolveCaches(); InjectedLanguageManager.getInstance(myProject).dropFileCaches(layoutFile); } }); }
@Override @Nullable public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull 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()]); }
private static CompletionContext createCompletionContext(PsiFile hostCopy, int hostStartOffset, OffsetMap hostMap, PsiFile originalFile) { CompletionAssertions.assertHostInfo(hostCopy, hostMap); InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(hostCopy.getProject()); CompletionContext context; PsiFile injected = InjectedLanguageUtil.findInjectedPsiNoCommit(hostCopy, hostStartOffset); if (injected != null) { if (injected instanceof PsiFileImpl) { ((PsiFileImpl)injected).setOriginalFile(originalFile); } DocumentWindow documentWindow = InjectedLanguageUtil.getDocumentWindow(injected); CompletionAssertions.assertInjectedOffsets(hostStartOffset, injectedLanguageManager, injected, documentWindow); context = new CompletionContext(injected, translateOffsetMapToInjected(hostMap, documentWindow)); } else { context = new CompletionContext(hostCopy, hostMap); } CompletionAssertions.assertFinalOffsets(originalFile, context, injected); return context; }
@Override public void addOccurrenceHighlights(@NotNull Editor editor, @NotNull PsiElement[] elements, @NotNull 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, trimOffsetToDocumentSize(editor, range.getStartOffset()), trimOffsetToDocumentSize(editor, range.getEndOffset()), attributes, flags, outHighlighters, scrollmarkColor); } }
@Nullable private PsiElement getNamedElement(@Nullable final PsiElement element) { if (element == null) return null; TargetElementEvaluatorEx2 evaluator = getElementEvaluatorsEx2(element.getLanguage()); if (evaluator != null) { PsiElement result = evaluator.getNamedElement(element); if (result != null) return result; } PsiElement parent; if ((parent = PsiTreeUtil.getParentOfType(element, PsiNamedElement.class, false)) != null) { boolean isInjected = parent instanceof PsiFile && InjectedLanguageManager.getInstance(parent.getProject()).isInjectedFragment((PsiFile)parent); // A bit hacky depends on navigation offset correctly overridden if (!isInjected && parent.getTextOffset() == element.getTextRange().getStartOffset()) { if (evaluator == null || evaluator.isAcceptableNamedParent(parent)) { return parent; } } } return null; }
@NotNull public static List<PropertiesFile> propertiesFilesByBundleName(final String resourceBundleName, final PsiElement context) { PsiFile containingFile = context.getContainingFile(); PsiElement containingFileContext = InjectedLanguageManager.getInstance(containingFile.getProject()).getInjectionHost(containingFile); if (containingFileContext != null) containingFile = containingFileContext.getContainingFile(); VirtualFile virtualFile = containingFile.getVirtualFile(); if (virtualFile == null) { virtualFile = containingFile.getOriginalFile().getVirtualFile(); } if (virtualFile != null) { Project project = containingFile.getProject(); final Module module = ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(virtualFile); if (module != null) { PropertiesReferenceManager refManager = PropertiesReferenceManager.getInstance(project); return refManager.findPropertiesFiles(module, resourceBundleName); } } return Collections.emptyList(); }
private boolean addInjectedPsiHighlights(@NotNull final Set<PsiFile> injectedFiles, @NotNull final ProgressIndicator progress, @NotNull final Collection<HighlightInfo> outInfos) { if (injectedFiles.isEmpty()) return true; final InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(myProject); final TextAttributes injectedAttributes = myGlobalScheme.getAttributes(EditorColors.INJECTED_LANGUAGE_FRAGMENT); return JobLauncher.getInstance() .invokeConcurrentlyUnderProgress(new ArrayList<PsiFile>(injectedFiles), progress, isFailFastOnAcquireReadAction(), new Processor<PsiFile>() { @Override public boolean process(final PsiFile injectedPsi) { return addInjectedPsiHighlights(injectedPsi, injectedAttributes, outInfos, progress, injectedLanguageManager); } }); }
@NotNull public static PsiElement getContext(@NotNull PsiFile file, int offset, boolean searchInInjectedFragment) { PsiElement element = null; if (searchInInjectedFragment && !InjectedLanguageManager.getInstance(file.getProject()).isInjectedFragment(file)) { PsiDocumentManager documentManager = PsiDocumentManager.getInstance(file.getProject()); Document document = documentManager.getDocument(file); if (document != null && !documentManager.isCommitted(document)) { LOGGER.error("Trying to access to injected template context on uncommited document, offset = " + offset, AttachmentFactory.createAttachment(file.getVirtualFile())); } else { element = InjectedLanguageUtil.findInjectedElementNoCommit(file, offset); } } if (element == null) { element = PsiUtilCore.getElementAtOffset(file, offset); } return element; }
@Nullable protected Pair<PsiElement, TextRange> getRangePair(final PsiFile file, final Editor editor) { final int offset = editor.getCaretModel().getOffset(); final PsiLanguageInjectionHost host = PsiTreeUtil.getParentOfType(file.findElementAt(offset), PsiLanguageInjectionHost.class, false); if (host == null || ElementManipulators.getManipulator(host) == null) return null; final List<Pair<PsiElement, TextRange>> injections = InjectedLanguageManager.getInstance(host.getProject()).getInjectedPsiFiles(host); if (injections == null || injections.isEmpty()) return null; final int offsetInElement = offset - host.getTextRange().getStartOffset(); final Pair<PsiElement, TextRange> rangePair = ContainerUtil.find(injections, new Condition<Pair<PsiElement, TextRange>>() { @Override public boolean value(final Pair<PsiElement, TextRange> pair) { return pair.second.containsRange(offsetInElement, offsetInElement); } }); if (rangePair != null) { final Language language = rangePair.first.getContainingFile().getLanguage(); final Object action = language.getUserData(EDIT_ACTION_AVAILABLE); if (action != null && action.equals(false)) return null; myLastLanguageName = language.getDisplayName(); } return rangePair; }
@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); }
@Override public void selectionChanged(SelectionEvent e) { if (!available() || !myEditor.getSelectionModel().hasSelection()) return; ViewerTreeStructure treeStructure = (ViewerTreeStructure)myPsiTreeBuilder.getTreeStructure(); if (treeStructure == null) return; final PsiElement rootElement = treeStructure.getRootPsiElement(); if (rootElement == null) return; final SelectionModel selection = myEditor.getSelectionModel(); final TextRange textRange = rootElement.getTextRange(); int baseOffset = textRange != null ? textRange.getStartOffset() : 0; final int start = selection.getSelectionStart()+baseOffset; final int end = selection.getSelectionEnd()+baseOffset - 1; final PsiElement element = findCommonParent(InjectedLanguageUtil.findElementAtNoCommit(rootElement.getContainingFile(), start), InjectedLanguageUtil.findElementAtNoCommit(rootElement.getContainingFile(), end)); if (element != null && myBlockTreeBuilder != null) { if (myEditor.getContentComponent().hasFocus()) { TextRange rangeInHostFile = InjectedLanguageManager.getInstance(myProject).injectedToHost(element, element.getTextRange()); selectBlockNode(findBlockNode(rangeInHostFile, true)); } } myPsiTreeBuilder.select(element); }
/** * 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(@NotNull final PsiElement expression, @NotNull 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; }
public static String getUnescapedText(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(); }
@Override public void highlightUsages(@NotNull PsiFile file, @NotNull Editor editor, boolean clearHighlights) { PsiElement target = getElement(); if (file instanceof PsiCompiledFile) file = ((PsiCompiledFile)file).getDecompiledPsiFile(); Project project = target.getProject(); final FindUsagesManager findUsagesManager = ((FindManagerImpl)FindManager.getInstance(project)).getFindUsagesManager(); final FindUsagesHandler handler = findUsagesManager.getFindUsagesHandler(target, true); // in case of injected file, use host file to highlight all occurrences of the target in each injected file PsiFile context = InjectedLanguageManager.getInstance(project).getTopLevelFile(file); SearchScope searchScope = new LocalSearchScope(context); Collection<PsiReference> refs = handler == null ? ReferencesSearch.search(target, searchScope, false).findAll() : handler.findReferencesToHighlight(target, searchScope); new HighlightUsagesHandler.DoHighlightRunnable(new ArrayList<PsiReference>(refs), project, target, editor, context, clearHighlights).run(); }
@Nullable private static RegExpLanguageHost findRegExpHost(@Nullable final PsiElement element) { if (ApplicationManager.getApplication().isUnitTestMode() && myHost != null) { return myHost; } if (element == null) { return null; } PsiLanguageInjectionHost host = InjectedLanguageManager.getInstance(element.getProject()).getInjectionHost(element); if (host instanceof RegExpLanguageHost) { return (RegExpLanguageHost)host; } if (host != null) { return INSTANCE.forClass(host.getClass()); } return null; }
@NotNull public Object[] getVariants() { final ArrayList<Object> ret = Lists.newArrayList(super.getVariants()); PsiFile file = myElement.getContainingFile(); final InjectedLanguageManager languageManager = InjectedLanguageManager.getInstance(myElement.getProject()); final PsiLanguageInjectionHost host = languageManager.getInjectionHost(myElement); if (host != null) file = host.getContainingFile(); final PsiElement originalElement = CompletionUtil.getOriginalElement(myElement); final PyQualifiedExpression element = originalElement instanceof PyQualifiedExpression ? (PyQualifiedExpression)originalElement : myElement; // include our own names final CompletionVariantsProcessor processor = new CompletionVariantsProcessor(element); if (file instanceof ScopeOwner) PyResolveUtil.scopeCrawlUp(processor, (ScopeOwner)file, null, null); ret.addAll(processor.getResultList()); return ret.toArray(); }
@Override public boolean isSupported(@NotNull final Class visitorClass, @NotNull final PsiFile file) { //inspections if (visitorClass == PyArgumentListInspection.class) { return false; } if (visitorClass == PyIncorrectDocstringInspection.class || visitorClass == PyMissingOrEmptyDocstringInspection.class || visitorClass == PyUnboundLocalVariableInspection.class || visitorClass == PyUnnecessaryBackslashInspection.class || visitorClass == PyByteLiteralInspection.class || visitorClass == PyNonAsciiCharInspection.class || visitorClass == PyPackageRequirementsInspection.class || visitorClass == PyMandatoryEncodingInspection.class || visitorClass == PyInterpreterInspection.class || visitorClass == PyDocstringTypesInspection.class || visitorClass == PySingleQuotedDocstringInspection.class || visitorClass == PyClassHasNoInitInspection.class || visitorClass == PyStatementEffectInspection.class) { return false; } //annotators if (visitorClass == DocStringAnnotator.class || visitorClass == ParameterListAnnotator.class || visitorClass == ReturnAnnotator.class || visitorClass == HighlightingAnnotator.class) return false; // doctest in separate file final PsiFile topLevelFile = InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file); if (visitorClass == PyUnresolvedReferencesInspection.class && !(topLevelFile instanceof PyFile)) { return false; } return true; }
@Override public void visitPyElement(final PyElement node) { super.visitPyElement(node); final PsiFile file = node.getContainingFile(); final InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(node.getProject()); if (injectedLanguageManager.isInjectedFragment(file)) { final PsiLanguageInjectionHost host = injectedLanguageManager.getInjectionHost(node); processInjection(host); } if (node instanceof PyReferenceOwner) { final PyResolveContext resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(myTypeEvalContext); processReference(node, ((PyReferenceOwner)node).getReference(resolveContext)); } else { if (node instanceof PsiLanguageInjectionHost) { processInjection((PsiLanguageInjectionHost)node); } for (final PsiReference reference : node.getReferences()) { processReference(node, reference); } } }
private void processInjection(@Nullable PsiLanguageInjectionHost node) { if (node == null) return; final List<Pair<PsiElement, TextRange>> files = InjectedLanguageManager.getInstance(node.getProject()).getInjectedPsiFiles(node); if (files != null) { for (Pair<PsiElement, TextRange> pair : files) { new PyRecursiveElementVisitor() { @Override public void visitPyElement(PyElement element) { super.visitPyElement(element); if (element instanceof PyReferenceOwner) { final PyResolveContext resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(myTypeEvalContext); final PsiPolyVariantReference reference = ((PyReferenceOwner)element).getReference(resolveContext); final ResolveResult[] resolveResults = reference.multiResolve(false); for (ResolveResult resolveResult : resolveResults) { if (resolveResult instanceof ImportedResolveResult) { myUsedImports.addAll(((ImportedResolveResult)resolveResult).getNameDefiners()); } } } } }.visitElement(pair.getFirst()); } } }
@Override public Result preprocessEnter(@NotNull PsiFile file, @NotNull Editor editor, @NotNull Ref<Integer> caretOffset, @NotNull Ref<Integer> caretAdvance, @NotNull DataContext dataContext, EditorActionHandler originalHandler) { int offset = caretOffset.get(); if (editor instanceof EditorWindow) { file = InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file); editor = InjectedLanguageUtil.getTopLevelEditor(editor); offset = editor.getCaretModel().getOffset(); } if (!(file instanceof PyFile)) { return Result.Continue; } // honor dedent (PY-3009) if (BackspaceHandler.isWhitespaceBeforeCaret(editor)) { return Result.DefaultSkipIndent; } return Result.Continue; }
private static void invokeImpl(Project project, Editor editor, PsiFile file) { final PsiFile psiFile = InjectedLanguageUtil.findInjectedPsiNoCommit(file, editor.getCaretModel().getOffset()); if (psiFile == null) return; final PsiLanguageInjectionHost host = InjectedLanguageManager.getInstance(project).getInjectionHost(psiFile); if (host == null) return; final LanguageInjectionSupport support = psiFile.getUserData(LanguageInjectionSupport.SETTINGS_EDITOR); if (support == null) return; try { if (!support.editInjectionInPlace(host)) { ShowSettingsUtil.getInstance().editConfigurable(project, new InjectionsSettingsUI(project, Configuration.getProjectInstance(project))); } } finally { FileContentUtil.reparseFiles(project, Collections.<VirtualFile>emptyList(), true); } }
private static boolean hasInjectedEscapingQuotes(PsiElement element, String text) { if (text.startsWith("\\") && text.length() >= 4) { char escapedChar = text.charAt(1); PsiElement context = InjectedLanguageManager.getInstance(element.getContainingFile().getProject()).getInjectionHost(element.getContainingFile()); if (context != null && context.textContains(escapedChar) && context.getText().startsWith(String.valueOf(escapedChar)) && text.endsWith("\\"+escapedChar) ) { return true; } } return false; }
private void registerReferencesFromInjectedFragments(@NotNull PsiElement element) { InjectedLanguageManager.getInstance(myFile.getProject()).enumerateEx(element, myFile, false, new PsiLanguageInjectionHost.InjectedPsiVisitor() { @Override public void visit(@NotNull final PsiFile injectedPsi, @NotNull final List<PsiLanguageInjectionHost.Shred> places) { injectedPsi.accept(REGISTER_REFERENCES_VISITOR); } } ); }
@Override protected void setUp() throws Exception { super.setUp(); final LocalInspectionTool[] tools = configureLocalInspectionTools(); CodeInsightTestFixtureImpl.configureInspections(tools, getProject(), Collections.<String>emptyList(), getTestRootDisposable()); DaemonCodeAnalyzerImpl daemonCodeAnalyzer = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(getProject()); daemonCodeAnalyzer.prepareForTest(); final StartupManagerImpl startupManager = (StartupManagerImpl)StartupManagerEx.getInstanceEx(getProject()); startupManager.runStartupActivities(); startupManager.startCacheUpdate(); startupManager.runPostStartupActivities(); DaemonCodeAnalyzerSettings.getInstance().setImportHintEnabled(false); if (isPerformanceTest()) { IntentionManager.getInstance().getAvailableIntentionActions(); // hack to avoid slowdowns in PyExtensionFactory PathManagerEx.getTestDataPath(); // to cache stuff ReferenceProvidersRegistry.getInstance(); // pre-load tons of classes InjectedLanguageManager.getInstance(getProject()); // zillion of Dom Sem classes LanguageAnnotators.INSTANCE.allForLanguage(JavaLanguage.INSTANCE); // pile of annotator classes loads LanguageAnnotators.INSTANCE.allForLanguage(StdLanguages.XML); ProblemHighlightFilter.EP_NAME.getExtensions(); Extensions.getExtensions(ImplicitUsageProvider.EP_NAME); Extensions.getExtensions(XmlSchemaProvider.EP_NAME); Extensions.getExtensions(XmlFileNSInfoProvider.EP_NAME); Extensions.getExtensions(ExternalAnnotatorsFilter.EXTENSION_POINT_NAME); Extensions.getExtensions(IndexPatternBuilder.EP_NAME); } }
@Override public UsageGroup groupUsage(@NotNull Usage usage) { if (!(usage instanceof PsiElementUsage)) return null; PsiElement psiElement = ((PsiElementUsage)usage).getElement(); PsiFile containingFile = psiElement.getContainingFile(); if (containingFile == null) return null; InjectedLanguageManager manager = InjectedLanguageManager.getInstance(containingFile.getProject()); PsiFile topLevelFile = manager.getTopLevelFile(containingFile); if (topLevelFile instanceof PsiJavaFile) { PsiElement containingMethod = topLevelFile == containingFile ? psiElement : manager.getInjectionHost(containingFile); if (usage instanceof UsageInfo2UsageAdapter && topLevelFile == containingFile) { int offset = ((UsageInfo2UsageAdapter)usage).getUsageInfo().getNavigationOffset(); containingMethod = containingFile.findElementAt(offset); } do { containingMethod = PsiTreeUtil.getParentOfType(containingMethod, PsiMethod.class, true); if (containingMethod == null) break; final PsiClass containingClass = ((PsiMethod)containingMethod).getContainingClass(); if (containingClass == null || containingClass.getQualifiedName() != null) break; } while (true); if (containingMethod != null) { return new MethodUsageGroup((PsiMethod)containingMethod); } } return null; }
private static void doProcessFile(@NotNull PsiElementVisitor visitor, @NotNull PsiManager psiManager, @NotNull VirtualFile vFile, boolean clearResolveCache) { if (!vFile.isValid()) return; PsiFile psiFile = psiManager.findFile(vFile); if (psiFile == null || !shouldHighlightFile(psiFile)) return; psiFile.accept(visitor); if (clearResolveCache) { psiManager.dropResolveCaches(); InjectedLanguageManager.getInstance(psiManager.getProject()).dropFileCaches(psiFile); } }
private void resetEditor(@NotNull final List<UsageInfo> infos) { ApplicationManager.getApplication().assertIsDispatchThread(); PsiElement psiElement = infos.get(0).getElement(); if (psiElement == null) return; PsiFile psiFile = psiElement.getContainingFile(); if (psiFile == null) return; PsiLanguageInjectionHost host = InjectedLanguageManager.getInstance(myProject).getInjectionHost(psiFile); if (host != null) { psiFile = host.getContainingFile(); if (psiFile == null) return; } final Document document = PsiDocumentManager.getInstance(psiFile.getProject()).getDocument(psiFile); if (document == null) return; if (myEditor == null || document != myEditor.getDocument()) { releaseEditor(); removeAll(); myEditor = createEditor(psiFile, document); if (myEditor == null) return; myEditor.setBorder(null); add(myEditor.getComponent(), BorderLayout.CENTER); revalidate(); } final Editor editor = myEditor; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (myProject.isDisposed()) return; highlight(infos, editor); } }); }
public static RefElement retrieveRefElement(@NotNull PsiElement element, @NotNull GlobalInspectionContext globalContext) { PsiFile elementFile = element.getContainingFile(); RefElement refElement = globalContext.getRefManager().getReference(elementFile); if (refElement == null) { PsiElement context = InjectedLanguageManager.getInstance(elementFile.getProject()).getInjectionHost(elementFile); if (context != null) refElement = globalContext.getRefManager().getReference(context.getContainingFile()); } return refElement; }
@Override public void visitFile(PsiFile file) { final VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile != null) { String relative = ProjectUtilCore.displayUrlRelativeToProject(virtualFile, virtualFile.getPresentableUrl(), myProject, true, false); myContext.incrementJobDoneAmount(myContext.getStdJobDescriptors().BUILD_GRAPH, relative); } final FileViewProvider viewProvider = file.getViewProvider(); final Set<Language> relevantLanguages = viewProvider.getLanguages(); for (Language language : relevantLanguages) { visitElement(viewProvider.getPsi(language)); } myPsiManager.dropResolveCaches(); InjectedLanguageManager.getInstance(myProject).dropFileCaches(file); }
private static Boolean processInjectedFile(PsiElement element, final TextOccurenceProcessor processor, final StringSearcher searcher, ProgressIndicator progress, InjectedLanguageManager injectedLanguageManager) { if (!(element instanceof PsiLanguageInjectionHost)) return null; if (injectedLanguageManager == null) return null; List<Pair<PsiElement,TextRange>> list = injectedLanguageManager.getInjectedPsiFiles(element); if (list == null) return null; for (Pair<PsiElement, TextRange> pair : list) { final PsiElement injected = pair.getFirst(); if (!processElementsContainingWordInElement(processor, injected, searcher, false, progress)) return Boolean.FALSE; } return Boolean.TRUE; }
public static boolean isUnderPsiRoot(PsiFile root, PsiElement element) { PsiFile containingFile = element.getContainingFile(); if (containingFile == root) return true; for (PsiFile psiRoot : root.getPsiRoots()) { if (containingFile == psiRoot) return true; } PsiLanguageInjectionHost host = InjectedLanguageManager.getInstance(root.getProject()).getInjectionHost(element); return host != null && isUnderPsiRoot(root, host); }
@NotNull private static SmartPointerElementInfo createElementInfo(@NotNull PsiFile containingFile, @NotNull ProperTextRange range, boolean forInjected) { Project project = containingFile.getProject(); if (containingFile.getViewProvider() instanceof FreeThreadedFileViewProvider) { PsiLanguageInjectionHost host = InjectedLanguageManager.getInstance(project).getInjectionHost(containingFile); if (host != null) { SmartPsiElementPointer<PsiLanguageInjectionHost> hostPointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(host); return new InjectedSelfElementInfo(project, containingFile, range, containingFile, hostPointer); } } if (range.equals(containingFile.getTextRange())) return new FileElementInfo(containingFile); return new SelfElementInfo(project, range, PsiElement.class, containingFile, containingFile.getLanguage(), forInjected); }
static void assertInjectedOffsets(int hostStartOffset, InjectedLanguageManager injectedLanguageManager, PsiFile injected, DocumentWindow documentWindow) { assert documentWindow != null : "no DocumentWindow for an injected fragment"; TextRange host = injectedLanguageManager.injectedToHost(injected, injected.getTextRange()); assert hostStartOffset >= host.getStartOffset() : "startOffset before injected"; assert hostStartOffset <= host.getEndOffset() : "startOffset after injected"; }
private static OffsetMap translateOffsetMapToHost(PsiFile originalFile, PsiFile hostFile, Editor hostEditor, OffsetMap map) { final InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(hostFile.getProject()); final OffsetMap hostMap = new OffsetMap(hostEditor.getDocument()); for (final OffsetKey key : map.getAllOffsets()) { hostMap.addOffset(key, injectedLanguageManager.injectedToHost(originalFile, map.getOffset(key))); } return hostMap; }
protected void addOccurrence(@NotNull PsiElement element) { TextRange range = element.getTextRange(); if (range != null) { range = InjectedLanguageManager.getInstance(element.getProject()).injectedToHost(element, range); myReadUsages.add(range); } }
@Override public boolean shouldHighlightErrorElement(@NotNull 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; }
@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; }
public static void doHighlightElements(Editor editor, PsiElement[] elements, TextAttributes attributes, boolean clearHighlights) { HighlightManager highlightManager = HighlightManager.getInstance(editor.getProject()); List<TextRange> textRanges = new ArrayList<TextRange>(elements.length); for (PsiElement element : elements) { TextRange range = element.getTextRange(); // injection occurs range = InjectedLanguageManager.getInstance(element.getProject()).injectedToHost(element, range); textRanges.add(range); } highlightRanges(highlightManager, editor, attributes, clearHighlights, textRanges); }