Search in sources :

Example 1 with LocalSearchScope

use of com.intellij.psi.search.LocalSearchScope in project intellij-community by JetBrains.

the class GroovyRefactoringSupportProvider method isInplaceRenameAvailable.

@Override
public boolean isInplaceRenameAvailable(@NotNull PsiElement elementToRename, PsiElement nameSuggestionContext) {
    if (nameSuggestionContext != null && nameSuggestionContext.getContainingFile() != elementToRename.getContainingFile())
        return false;
    if (!(elementToRename instanceof GrLabeledStatement)) {
        return false;
    }
    SearchScope useScope = PsiSearchHelper.SERVICE.getInstance(elementToRename.getProject()).getUseScope(elementToRename);
    if (!(useScope instanceof LocalSearchScope))
        return false;
    PsiElement[] scopeElements = ((LocalSearchScope) useScope).getScope();
    if (scopeElements.length > 1) {
        return false;
    }
    PsiFile containingFile = elementToRename.getContainingFile();
    return PsiTreeUtil.isAncestor(containingFile, scopeElements[0], false);
}
Also used : LocalSearchScope(com.intellij.psi.search.LocalSearchScope) SearchScope(com.intellij.psi.search.SearchScope) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) PsiFile(com.intellij.psi.PsiFile) GrLabeledStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrLabeledStatement) PsiElement(com.intellij.psi.PsiElement)

Example 2 with LocalSearchScope

use of com.intellij.psi.search.LocalSearchScope in project intellij-community by JetBrains.

the class PropertiesReferenceContributor method registerReferenceProviders.

@Override
public void registerReferenceProviders(@NotNull final PsiReferenceRegistrar registrar) {
    registrar.registerReferenceProvider(literalExpression(), new PropertiesReferenceProvider(true));
    registrar.registerReferenceProvider(literalExpression().withParent(psiNameValuePair().withName(AnnotationUtil.PROPERTY_KEY_RESOURCE_BUNDLE_PARAMETER)), new ResourceBundleReferenceProvider());
    registrar.registerReferenceProvider(literalExpression(), new PsiReferenceProvider() {

        private final PsiReferenceProvider myUnderlying = new ResourceBundleReferenceProvider();

        @NotNull
        @Override
        public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
            final PsiElement parent = element.getParent();
            if (!(parent instanceof PsiField)) {
                return PsiReference.EMPTY_ARRAY;
            }
            final PsiField field = (PsiField) parent;
            if (field.getInitializer() != element || !field.hasModifierProperty(PsiModifier.FINAL) || !field.getType().equalsToText(CommonClassNames.JAVA_LANG_STRING)) {
                return PsiReference.EMPTY_ARRAY;
            }
            List<PsiReference> references = new ArrayList<>();
            final PsiClass propertyKeyAnnotation = JavaPsiFacade.getInstance(element.getProject()).findClass(AnnotationUtil.PROPERTY_KEY, element.getResolveScope());
            if (propertyKeyAnnotation != null) {
                AnnotatedElementsSearch.searchPsiParameters(propertyKeyAnnotation, new LocalSearchScope(element.getContainingFile())).forEach(parameter -> {
                    final PsiModifierList list = parameter.getModifierList();
                    LOG.assertTrue(list != null);
                    final PsiAnnotation annotation = list.findAnnotation(AnnotationUtil.PROPERTY_KEY);
                    LOG.assertTrue(annotation != null);
                    for (PsiNameValuePair pair : annotation.getParameterList().getAttributes()) {
                        if (AnnotationUtil.PROPERTY_KEY_RESOURCE_BUNDLE_PARAMETER.equals(pair.getName())) {
                            final PsiAnnotationMemberValue value = pair.getValue();
                            if (value instanceof PsiReferenceExpression && ((PsiReferenceExpression) value).resolve() == field) {
                                Collections.addAll(references, myUnderlying.getReferencesByElement(element, context));
                                return false;
                            }
                        }
                    }
                    return true;
                });
            }
            return references.toArray(new PsiReference[references.size()]);
        }
    });
    registrar.registerReferenceProvider(PsiJavaPatterns.psiElement(PropertyValueImpl.class), new PsiReferenceProvider() {

        @NotNull
        @Override
        public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
            String text = element.getText();
            String[] words = text.split("\\s");
            if (words.length != 1)
                return PsiReference.EMPTY_ARRAY;
            return CLASS_REFERENCE_PROVIDER.getReferencesByString(words[0], element, 0);
        }
    });
}
Also used : LocalSearchScope(com.intellij.psi.search.LocalSearchScope) ProcessingContext(com.intellij.util.ProcessingContext) PsiJavaPatterns.psiNameValuePair(com.intellij.patterns.PsiJavaPatterns.psiNameValuePair) PsiJavaPatterns.literalExpression(com.intellij.patterns.PsiJavaPatterns.literalExpression) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) ArrayList(java.util.ArrayList) PropertyValueImpl(com.intellij.lang.properties.psi.impl.PropertyValueImpl) List(java.util.List) AnnotatedElementsSearch(com.intellij.psi.search.searches.AnnotatedElementsSearch) AnnotationUtil(com.intellij.codeInsight.AnnotationUtil) com.intellij.psi(com.intellij.psi) JavaClassReferenceProvider(com.intellij.psi.impl.source.resolve.reference.impl.providers.JavaClassReferenceProvider) Logger(com.intellij.openapi.diagnostic.Logger) PsiJavaPatterns(com.intellij.patterns.PsiJavaPatterns) NotNull(org.jetbrains.annotations.NotNull) Collections(java.util.Collections) ProcessingContext(com.intellij.util.ProcessingContext) NotNull(org.jetbrains.annotations.NotNull) ArrayList(java.util.ArrayList) List(java.util.List) PropertyValueImpl(com.intellij.lang.properties.psi.impl.PropertyValueImpl)

Example 3 with LocalSearchScope

use of com.intellij.psi.search.LocalSearchScope in project intellij-community by JetBrains.

the class ImportOnDemandIntention method processIntention.

@Override
protected void processIntention(@NotNull PsiElement element, @NotNull Project project, Editor editor) throws IncorrectOperationException {
    if (!(element instanceof GrReferenceElement))
        return;
    final GrReferenceElement ref = (GrReferenceElement) element;
    final PsiElement resolved = ref.resolve();
    if (!(resolved instanceof PsiClass))
        return;
    final String qname = ((PsiClass) resolved).getQualifiedName();
    final GrImportStatement importStatement = GroovyPsiElementFactory.getInstance(project).createImportStatementFromText(qname, true, true, null);
    final PsiFile containingFile = element.getContainingFile();
    if (!(containingFile instanceof GroovyFile))
        return;
    ((GroovyFile) containingFile).addImport(importStatement);
    for (PsiReference reference : ReferencesSearch.search(resolved, new LocalSearchScope(containingFile))) {
        final PsiElement refElement = reference.getElement();
        if (refElement == null)
            continue;
        final PsiElement parent = refElement.getParent();
        if (parent instanceof GrQualifiedReference<?>) {
            org.jetbrains.plugins.groovy.codeStyle.GrReferenceAdjuster.shortenReference((GrQualifiedReference<?>) parent);
        }
    }
}
Also used : LocalSearchScope(com.intellij.psi.search.LocalSearchScope) PsiClass(com.intellij.psi.PsiClass) PsiReference(com.intellij.psi.PsiReference) PsiFile(com.intellij.psi.PsiFile) GrImportStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement) GrReferenceElement(org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement) PsiElement(com.intellij.psi.PsiElement) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile) GrQualifiedReference(org.jetbrains.plugins.groovy.lang.psi.GrQualifiedReference)

Example 4 with LocalSearchScope

use of com.intellij.psi.search.LocalSearchScope in project intellij-community by JetBrains.

the class ImportStaticIntention method shortenUsages.

private static boolean shortenUsages(PsiElement resolved, PsiFile containingFile) {
    boolean isAnythingShortened = false;
    for (PsiReference reference : ReferencesSearch.search(resolved, new LocalSearchScope(containingFile))) {
        final PsiElement refElement = reference.getElement();
        if (refElement instanceof GrQualifiedReference<?>) {
            boolean shortened = GrReferenceAdjuster.shortenReference((GrQualifiedReference<?>) refElement);
            isAnythingShortened |= shortened;
        }
    }
    return isAnythingShortened;
}
Also used : LocalSearchScope(com.intellij.psi.search.LocalSearchScope) GrQualifiedReference(org.jetbrains.plugins.groovy.lang.psi.GrQualifiedReference)

Example 5 with LocalSearchScope

use of com.intellij.psi.search.LocalSearchScope in project intellij-community by JetBrains.

the class VariableInlineHandler method invoke.

public static void invoke(@NotNull final XPathVariable variable, Editor editor) {
    final String type = LanguageFindUsages.INSTANCE.forLanguage(variable.getLanguage()).getType(variable);
    final Project project = variable.getProject();
    final XmlTag tag = ((XsltElement) variable).getTag();
    final String expression = tag.getAttributeValue("select");
    if (expression == null) {
        CommonRefactoringUtil.showErrorHint(project, editor, MessageFormat.format("{0} ''{1}'' has no value.", StringUtil.capitalize(type), variable.getName()), TITLE, null);
        return;
    }
    final Collection<PsiReference> references = ReferencesSearch.search(variable, new LocalSearchScope(tag.getParentTag()), false).findAll();
    if (references.size() == 0) {
        CommonRefactoringUtil.showErrorHint(project, editor, MessageFormat.format("{0} ''{1}'' is never used.", variable.getName()), TITLE, null);
        return;
    }
    boolean hasExternalRefs = false;
    if (XsltSupport.isTopLevelElement(tag)) {
        final Query<PsiReference> query = ReferencesSearch.search(variable, GlobalSearchScope.allScope(project), false);
        hasExternalRefs = !query.forEach(new Processor<PsiReference>() {

            int allRefs = 0;

            public boolean process(PsiReference psiReference) {
                if (++allRefs > references.size()) {
                    return false;
                } else if (!references.contains(psiReference)) {
                    return false;
                }
                return true;
            }
        });
    }
    final HighlightManager highlighter = HighlightManager.getInstance(project);
    final ArrayList<RangeHighlighter> highlighters = new ArrayList<>();
    final PsiReference[] psiReferences = references.toArray(new PsiReference[references.size()]);
    TextRange[] ranges = ContainerUtil.map2Array(psiReferences, TextRange.class, s -> {
        final PsiElement psiElement = s.getElement();
        final XmlAttributeValue context = PsiTreeUtil.getContextOfType(psiElement, XmlAttributeValue.class, true);
        if (psiElement instanceof XPathElement && context != null) {
            return XsltCodeInsightUtil.getRangeInsideHostingFile((XPathElement) psiElement).cutOut(s.getRangeInElement());
        }
        return psiElement.getTextRange().cutOut(s.getRangeInElement());
    });
    final Editor e = editor instanceof EditorWindow ? ((EditorWindow) editor).getDelegate() : editor;
    for (TextRange range : ranges) {
        final TextAttributes textAttributes = EditorColors.SEARCH_RESULT_ATTRIBUTES.getDefaultAttributes();
        final Color color = getScrollmarkColor(textAttributes);
        highlighter.addOccurrenceHighlight(e, range.getStartOffset(), range.getEndOffset(), textAttributes, HighlightManagerImpl.HIDE_BY_ESCAPE, highlighters, color);
    }
    highlighter.addOccurrenceHighlights(e, new PsiElement[] { ((XsltVariable) variable).getNameIdentifier() }, EditorColors.WRITE_SEARCH_RESULT_ATTRIBUTES.getDefaultAttributes(), false, highlighters);
    if (!hasExternalRefs) {
        if (!ApplicationManager.getApplication().isUnitTestMode() && Messages.showYesNoDialog(MessageFormat.format("Inline {0} ''{1}''? ({2} occurrence{3})", type, variable.getName(), String.valueOf(references.size()), references.size() > 1 ? "s" : ""), TITLE, Messages.getQuestionIcon()) != Messages.YES) {
            return;
        }
    } else {
        if (!ApplicationManager.getApplication().isUnitTestMode() && Messages.showYesNoDialog(MessageFormat.format("Inline {0} ''{1}''? ({2} local occurrence{3})\n" + "\nWarning: It is being used in external files. Its declaration will not be removed.", type, variable.getName(), String.valueOf(references.size()), references.size() > 1 ? "s" : ""), TITLE, Messages.getWarningIcon()) != Messages.YES) {
            return;
        }
    }
    final boolean hasRefs = hasExternalRefs;
    new WriteCommandAction.Simple(project, "XSLT.Inline", tag.getContainingFile()) {

        @Override
        protected void run() throws Throwable {
            try {
                for (PsiReference psiReference : references) {
                    final PsiElement element = psiReference.getElement();
                    if (element instanceof XPathElement) {
                        final XPathElement newExpr = XPathChangeUtil.createExpression(element, expression);
                        element.replace(newExpr);
                    } else {
                        assert false;
                    }
                }
                if (!hasRefs) {
                    tag.delete();
                }
            } catch (IncorrectOperationException e) {
                Logger.getInstance(VariableInlineHandler.class.getName()).error(e);
            }
        }
    }.execute();
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) XsltElement(org.intellij.lang.xpath.xslt.psi.XsltElement) ArrayList(java.util.ArrayList) RangeHighlighter(com.intellij.openapi.editor.markup.RangeHighlighter) TextAttributes(com.intellij.openapi.editor.markup.TextAttributes) PsiElement(com.intellij.psi.PsiElement) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) HighlightManager(com.intellij.codeInsight.highlighting.HighlightManager) PsiReference(com.intellij.psi.PsiReference) TextRange(com.intellij.openapi.util.TextRange) XmlAttributeValue(com.intellij.psi.xml.XmlAttributeValue) XPathElement(org.intellij.lang.xpath.psi.XPathElement) EditorWindow(com.intellij.injected.editor.EditorWindow) Project(com.intellij.openapi.project.Project) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Editor(com.intellij.openapi.editor.Editor) XmlTag(com.intellij.psi.xml.XmlTag)

Aggregations

LocalSearchScope (com.intellij.psi.search.LocalSearchScope)113 SearchScope (com.intellij.psi.search.SearchScope)31 NotNull (org.jetbrains.annotations.NotNull)22 PsiElement (com.intellij.psi.PsiElement)19 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)19 Project (com.intellij.openapi.project.Project)18 Nullable (org.jetbrains.annotations.Nullable)13 ArrayList (java.util.ArrayList)12 VirtualFile (com.intellij.openapi.vfs.VirtualFile)11 UsageInfo (com.intellij.usageView.UsageInfo)11 TextRange (com.intellij.openapi.util.TextRange)9 IncorrectOperationException (com.intellij.util.IncorrectOperationException)9 com.intellij.psi (com.intellij.psi)8 PsiReference (com.intellij.psi.PsiReference)8 PsiFile (com.intellij.psi.PsiFile)7 ReferencesSearch (com.intellij.psi.search.searches.ReferencesSearch)7 AnalysisScope (com.intellij.analysis.AnalysisScope)6 Processor (com.intellij.util.Processor)6 PsiTreeUtil (com.intellij.psi.util.PsiTreeUtil)5 Ref (com.intellij.openapi.util.Ref)4