Search in sources :

Example 91 with LocalSearchScope

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

the class XsltExtractTemplateAction method extractFrom.

private boolean extractFrom(@NotNull final PsiElement start, final PsiElement end, String newName) {
    final XmlTag outerTemplate = XsltCodeInsightUtil.getTemplateTag(start, false);
    if (outerTemplate == null) {
        return false;
    }
    final XmlTag parentScope = PsiTreeUtil.getParentOfType(start, XmlTag.class, true);
    if (parentScope == null) {
        return false;
    }
    final StringBuilder sb = new StringBuilder("\n");
    final Set<String> vars = new LinkedHashSet<>();
    final int startOffset = start.getTextRange().getStartOffset();
    final int endOffset = end.getTextRange().getEndOffset();
    PsiElement e = start;
    while (e != null) {
        if (e instanceof XmlTag) {
            final XmlTag tag = (XmlTag) e;
            if (XsltSupport.isVariable(tag)) {
                final XsltVariable variable = XsltElementFactory.getInstance().wrapElement(tag, XsltVariable.class);
                final LocalSearchScope searchScope = new LocalSearchScope(parentScope);
                final Query<PsiReference> query = ReferencesSearch.search(variable, searchScope);
                for (PsiReference reference : query) {
                    final XmlElement context = PsiTreeUtil.getContextOfType(reference.getElement(), XmlElement.class, true);
                    if (context == null || context.getTextRange().getStartOffset() > endOffset) {
                        return false;
                    }
                }
            }
        }
        sb.append(e.getText());
        final List<XPathVariableReference> references = RefactoringUtil.collectVariableReferences(e);
        for (XPathVariableReference reference : references) {
            final XPathVariable variable = reference.resolve();
            if (variable instanceof XsltVariable) {
                final XmlTag var = ((XsltVariable) variable).getTag();
                if (var.getTextRange().getStartOffset() < startOffset) {
                    // don't pass through global parameters and variables
                    if (XsltCodeInsightUtil.getTemplateTag(variable, false) != null) {
                        vars.add(variable.getName());
                    }
                }
            } else if (variable == null) {
                // TODO just copy unresolved refs or fail?
                vars.add(reference.getReferencedName());
            }
        }
        if (e == end) {
            break;
        }
        e = e.getNextSibling();
    }
    sb.append("\n");
    final String s = newName == null ? Messages.showInputDialog(start.getProject(), "Template Name: ", getRefactoringName(), Messages.getQuestionIcon()) : newName;
    if (s != null) {
        new WriteCommandAction(start.getProject()) {

            protected void run(@NotNull Result result) throws Throwable {
                final PsiFile containingFile = start.getContainingFile();
                XmlTag templateTag = parentScope.createChildTag("template", XsltSupport.XSLT_NS, sb.toString(), false);
                templateTag.setAttribute("name", s);
                final PsiElement dummy = XmlElementFactory.getInstance(start.getProject()).createDisplayText(" ");
                final PsiElement outerParent = outerTemplate.getParent();
                final PsiElement element = outerParent.addAfter(dummy, outerTemplate);
                templateTag = (XmlTag) outerParent.addAfter(templateTag, element);
                final TextRange adjust = templateTag.getTextRange();
                final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(start.getProject());
                final Document doc = psiDocumentManager.getDocument(containingFile);
                assert doc != null;
                psiDocumentManager.doPostponedOperationsAndUnblockDocument(doc);
                CodeStyleManager.getInstance(start.getManager().getProject()).adjustLineIndent(containingFile, adjust);
                final PsiElement parent = start.getParent();
                XmlTag callTag = parentScope.createChildTag("call-template", XsltSupport.XSLT_NS, null, false);
                callTag.setAttribute("name", s);
                if (start instanceof XmlToken && ((XmlToken) start).getTokenType() == XmlTokenType.XML_DATA_CHARACTERS) {
                    assert start == end;
                    callTag = (XmlTag) start.replace(callTag);
                } else {
                    callTag = (XmlTag) parent.addBefore(callTag, start);
                    parent.deleteChildRange(start, end);
                }
                for (String var : vars) {
                    final XmlTag param = templateTag.createChildTag("param", XsltSupport.XSLT_NS, null, false);
                    param.setAttribute("name", var);
                    RefactoringUtil.addParameter(templateTag, param);
                    final XmlTag arg = RefactoringUtil.addWithParam(callTag);
                    arg.setAttribute("name", var);
                    arg.setAttribute("select", "$" + var);
                }
            }
        }.execute().logException(Logger.getInstance(getClass().getName()));
    }
    return true;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) XPathVariableReference(org.intellij.lang.xpath.psi.XPathVariableReference) TextRange(com.intellij.openapi.util.TextRange) Document(com.intellij.openapi.editor.Document) NotNull(org.jetbrains.annotations.NotNull) Result(com.intellij.openapi.application.Result) XPathVariable(org.intellij.lang.xpath.psi.XPathVariable) XsltVariable(org.intellij.lang.xpath.xslt.psi.XsltVariable)

Example 92 with LocalSearchScope

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

the class JavaFxMethodSearcher method searchMethod.

private static void searchMethod(@NotNull PsiMethod psiMethod, @NotNull ReferencesSearch.SearchParameters queryParameters, @NotNull Processor<PsiReference> consumer) {
    final Project project = PsiUtilCore.getProjectInReadAction(psiMethod);
    final SearchScope scope = ReadAction.compute(queryParameters::getEffectiveSearchScope);
    if (scope instanceof LocalSearchScope) {
        final VirtualFile[] vFiles = ((LocalSearchScope) scope).getVirtualFiles();
        for (VirtualFile vFile : vFiles) {
            if (JavaFxFileTypeFactory.isFxml(vFile)) {
                final PsiFile psiFile = PsiManager.getInstance(project).findFile(vFile);
                if (psiFile != null) {
                    final Boolean goOn = ReadAction.compute(() -> searchMethodInFile(psiMethod, psiFile, consumer));
                    if (!goOn)
                        break;
                }
            }
        }
    } else if (scope instanceof GlobalSearchScope) {
        final String propertyName = ReadAction.compute(() -> PropertyUtil.getPropertyName(psiMethod.getName()));
        if (propertyName == null)
            return;
        final String className = ReadAction.compute(() -> {
            final PsiClass psiClass = psiMethod.getContainingClass();
            return psiClass != null ? psiClass.getName() : null;
        });
        if (className == null)
            return;
        final GlobalSearchScope fxmlScope = new JavaFxScopeEnlarger.GlobalFxmlSearchScope((GlobalSearchScope) scope);
        final VirtualFile[] filteredFiles = ReadAction.compute(() -> CacheManager.SERVICE.getInstance(project).getVirtualFilesWithWord(className, UsageSearchContext.IN_PLAIN_TEXT, fxmlScope, true));
        if (ArrayUtil.isEmpty(filteredFiles))
            return;
        final GlobalSearchScope filteredScope = GlobalSearchScope.filesScope(project, ContainerUtil.newHashSet(filteredFiles));
        ApplicationManager.getApplication().runReadAction((Runnable) () -> CacheManager.SERVICE.getInstance(project).processFilesWithWord(file -> searchMethodInFile(psiMethod, file, consumer), propertyName, UsageSearchContext.IN_PLAIN_TEXT, filteredScope, true));
    }
}
Also used : LocalSearchScope(com.intellij.psi.search.LocalSearchScope) VirtualFile(com.intellij.openapi.vfs.VirtualFile) ReferencesSearch(com.intellij.psi.search.searches.ReferencesSearch) JavaFxFileTypeFactory(org.jetbrains.plugins.javaFX.fxml.JavaFxFileTypeFactory) ArrayUtil(com.intellij.util.ArrayUtil) JavaFxPropertyElement(org.jetbrains.plugins.javaFX.refactoring.JavaFxPropertyElement) XmlAttribute(com.intellij.psi.xml.XmlAttribute) VirtualFile(com.intellij.openapi.vfs.VirtualFile) QueryExecutor(com.intellij.util.QueryExecutor) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) SearchScope(com.intellij.psi.search.SearchScope) ContainerUtil(com.intellij.util.containers.ContainerUtil) ReadAction(com.intellij.openapi.application.ReadAction) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) UsageSearchContext(com.intellij.psi.search.UsageSearchContext) PropertyUtil(com.intellij.psi.util.PropertyUtil) PsiUtilCore(com.intellij.psi.util.PsiUtilCore) CacheManager(com.intellij.psi.impl.cache.CacheManager) Processor(com.intellij.util.Processor) ApplicationManager(com.intellij.openapi.application.ApplicationManager) Project(com.intellij.openapi.project.Project) XmlElement(com.intellij.psi.xml.XmlElement) com.intellij.psi(com.intellij.psi) NotNull(org.jetbrains.annotations.NotNull) Ref(com.intellij.openapi.util.Ref) Project(com.intellij.openapi.project.Project) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) SearchScope(com.intellij.psi.search.SearchScope) LocalSearchScope(com.intellij.psi.search.LocalSearchScope)

Example 93 with LocalSearchScope

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

the class Replacer method testReplace.

public String testReplace(String in, String what, String by, ReplaceOptions options, boolean filePattern, boolean createPhysicalFile, FileType sourceFileType, Language sourceDialect) {
    this.options = options;
    final MatchOptions matchOptions = this.options.getMatchOptions();
    matchOptions.setSearchPattern(what);
    this.options.setReplacement(by);
    replacementBuilder = null;
    context = null;
    replaceHandler = null;
    matchOptions.clearVariableConstraints();
    MatcherImplUtil.transform(matchOptions);
    final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(matchOptions.getFileType());
    assert profile != null;
    profile.checkSearchPattern(project, matchOptions);
    checkSupportedReplacementPattern(project, options);
    Matcher matcher = new Matcher(project);
    try {
        PsiElement firstElement, lastElement, parent;
        if (options.getMatchOptions().getScope() == null) {
            PsiElement[] elements = MatcherImplUtil.createTreeFromText(in, filePattern ? PatternTreeContext.File : PatternTreeContext.Block, sourceFileType, sourceDialect, null, project, createPhysicalFile);
            firstElement = elements[0];
            lastElement = elements[elements.length - 1];
            parent = firstElement.getParent();
            matchOptions.setScope(new LocalSearchScope(parent));
        } else {
            parent = ((LocalSearchScope) options.getMatchOptions().getScope()).getScope()[0];
            firstElement = parent.getFirstChild();
            lastElement = parent.getLastChild();
        }
        matchOptions.setResultIsContextMatch(true);
        CollectingMatchResultSink sink = new CollectingMatchResultSink();
        matcher.testFindMatches(sink, matchOptions);
        final List<ReplacementInfo> resultPtrList = new ArrayList<>();
        for (final MatchResult result : sink.getMatches()) {
            resultPtrList.add(buildReplacement(result));
        }
        sink.getMatches().clear();
        int startOffset = firstElement.getTextRange().getStartOffset();
        int endOffset = filePattern ? 0 : parent.getTextLength() - (lastElement.getTextRange().getEndOffset());
        // get nodes from text may contain
        PsiElement prevSibling = firstElement.getPrevSibling();
        if (prevSibling instanceof PsiWhiteSpace) {
            startOffset -= prevSibling.getTextLength() - 1;
        }
        PsiElement nextSibling = lastElement.getNextSibling();
        if (nextSibling instanceof PsiWhiteSpace) {
            endOffset -= nextSibling.getTextLength() - 1;
        }
        replaceAll(resultPtrList);
        String result = parent.getText();
        result = result.substring(startOffset);
        result = result.substring(0, result.length() - endOffset);
        return result;
    } catch (Exception e) {
        throw new IncorrectOperationException(e);
    } finally {
        options.getMatchOptions().setScope(null);
    }
}
Also used : LocalSearchScope(com.intellij.psi.search.LocalSearchScope) ReplacementInfo(com.intellij.structuralsearch.plugin.replace.ReplacementInfo) IncorrectOperationException(com.intellij.util.IncorrectOperationException) CollectingMatchResultSink(com.intellij.structuralsearch.plugin.util.CollectingMatchResultSink) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 94 with LocalSearchScope

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

the class PatternCompiler method compilePattern.

public static CompiledPattern compilePattern(final Project project, final MatchOptions options) throws MalformedPatternException, UnsupportedOperationException {
    FileType fileType = options.getFileType();
    assert fileType instanceof LanguageFileType;
    Language language = ((LanguageFileType) fileType).getLanguage();
    StructuralSearchProfile profile = StructuralSearchUtil.getProfileByLanguage(language);
    assert profile != null;
    CompiledPattern result = profile.createCompiledPattern();
    final String[] prefixes = result.getTypedVarPrefixes();
    assert prefixes.length > 0;
    final CompileContext context = new CompileContext();
    if (ApplicationManager.getApplication().isUnitTestMode())
        lastTestingContext = context;
    try {
        context.init(result, options, project, options.getScope() instanceof GlobalSearchScope);
        List<PsiElement> elements = compileByAllPrefixes(project, options, result, context, prefixes);
        final CompiledPattern pattern = context.getPattern();
        checkForUnknownVariables(pattern, elements);
        pattern.setNodes(elements);
        if (context.getSearchHelper().doOptimizing() && context.getSearchHelper().isScannedSomething()) {
            final Set<PsiFile> set = context.getSearchHelper().getFilesSetToScan();
            final List<PsiFile> filesToScan = new ArrayList<>(set.size());
            final GlobalSearchScope scope = (GlobalSearchScope) options.getScope();
            for (final PsiFile file : set) {
                if (!scope.contains(file.getVirtualFile())) {
                    continue;
                }
                if (file instanceof PsiFileImpl) {
                    ((PsiFileImpl) file).clearCaches();
                }
                filesToScan.add(file);
            }
            if (filesToScan.size() == 0) {
                throw new MalformedPatternException(SSRBundle.message("ssr.will.not.find.anything"));
            }
            result.setScope(new LocalSearchScope(PsiUtilCore.toPsiElementArray(filesToScan)));
        }
    } finally {
        context.clear();
    }
    return result;
}
Also used : LocalSearchScope(com.intellij.psi.search.LocalSearchScope) PsiFileImpl(com.intellij.psi.impl.source.PsiFileImpl) TIntArrayList(gnu.trove.TIntArrayList) LanguageFileType(com.intellij.openapi.fileTypes.LanguageFileType) Language(com.intellij.lang.Language) FileType(com.intellij.openapi.fileTypes.FileType) LanguageFileType(com.intellij.openapi.fileTypes.LanguageFileType) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) CompiledPattern(com.intellij.structuralsearch.impl.matcher.CompiledPattern)

Example 95 with LocalSearchScope

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

the class MatcherImpl method findMatches.

/**
   * Finds the matches of given pattern starting from given tree element.
   * @throws MalformedPatternException
   * @throws UnsupportedPatternException
   */
protected void findMatches(MatchResultSink sink, final MatchOptions options) throws MalformedPatternException, UnsupportedPatternException {
    CompiledPattern compiledPattern = prepareMatching(sink, options);
    if (compiledPattern == null) {
        return;
    }
    matchContext.getSink().setMatchingProcess(scheduler);
    scheduler.init();
    progress = matchContext.getSink().getProgressIndicator();
    if (isTesting) {
        // testing mode;
        final PsiElement[] elements = ((LocalSearchScope) options.getScope()).getScope();
        PsiElement parent = elements[0].getParent();
        if (elements.length > 0 && matchContext.getPattern().getStrategy().continueMatching(parent != null ? parent : elements[0])) {
            visitor.matchContext(new SsrFilteringNodeIterator(new ArrayBackedNodeIterator(elements)));
        } else {
            final LanguageFileType fileType = (LanguageFileType) matchContext.getOptions().getFileType();
            final Language language = fileType.getLanguage();
            for (PsiElement element : elements) {
                match(element, language);
            }
        }
        matchContext.getSink().matchingFinished();
        return;
    }
    if (!findMatches(options, compiledPattern)) {
        return;
    }
    if (scheduler.getTaskQueueEndAction() == null) {
        scheduler.setTaskQueueEndAction(() -> matchContext.getSink().matchingFinished());
    }
    scheduler.executeNext();
}
Also used : LocalSearchScope(com.intellij.psi.search.LocalSearchScope) LanguageFileType(com.intellij.openapi.fileTypes.LanguageFileType) Language(com.intellij.lang.Language) SsrFilteringNodeIterator(com.intellij.structuralsearch.impl.matcher.iterators.SsrFilteringNodeIterator) ArrayBackedNodeIterator(com.intellij.dupLocator.iterators.ArrayBackedNodeIterator)

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