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;
}
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));
}
}
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);
}
}
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;
}
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();
}
Aggregations