com.intellij.psi.search.SearchScope Java Examples

The following examples show how to use com.intellij.psi.search.SearchScope. 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: CodeGenerationUtils.java    From JHelper with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static void removeUnusedCode(PsiFile file) {
	while (true) {
		Collection<PsiElement> toDelete = new ArrayList<>();
		Project project = file.getProject();
		SearchScope scope = GlobalSearchScope.fileScope(project, file.getVirtualFile());
		file.acceptChildren(new DeletionMarkingVisitor(toDelete, scope));
		if (toDelete.isEmpty()) {
			break;
		}
		WriteCommandAction.writeCommandAction(project).run(
				() -> {
					for (PsiElement element : toDelete) {
						element.delete();
					}
				}
		);

	}
}
 
Example #2
Source File: SearchForUsagesRunnable.java    From consulo with Apache License 2.0 6 votes vote down vote up
SearchForUsagesRunnable(@Nonnull UsageViewManagerImpl usageViewManager,
                        @Nonnull Project project,
                        @Nonnull AtomicReference<UsageViewImpl> usageViewRef,
                        @Nonnull UsageViewPresentation presentation,
                        @Nonnull UsageTarget[] searchFor,
                        @Nonnull Factory<UsageSearcher> searcherFactory,
                        @Nonnull FindUsagesProcessPresentation processPresentation,
                        @Nonnull SearchScope searchScopeToWarnOfFallingOutOf,
                        @javax.annotation.Nullable UsageViewManager.UsageViewStateListener listener) {
  myProject = project;
  myUsageViewRef = usageViewRef;
  myPresentation = presentation;
  mySearchFor = searchFor;
  mySearcherFactory = searcherFactory;
  myProcessPresentation = processPresentation;
  mySearchScopeToWarnOfFallingOutOf = searchScopeToWarnOfFallingOutOf;
  myListener = listener;
  myUsageViewManager = usageViewManager;
}
 
Example #3
Source File: PsiElement2UsageTargetAdapter.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void highlightUsages(@Nonnull PsiFile file, @Nonnull 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<>(refs), project, target, editor, context, clearHighlights).run();
}
 
Example #4
Source File: FindUsagesOptions.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static SearchScope calcScope(@Nonnull Project project, @Nullable DataContext dataContext) {
  String defaultScopeName = FindSettings.getInstance().getDefaultScopeName();
  List<SearchScope> predefined = PredefinedSearchScopeProvider.getInstance().getPredefinedScopes(project, dataContext, true, false, false,
                                                                                                 false);
  SearchScope resultScope = null;
  for (SearchScope scope : predefined) {
    if (scope.getDisplayName().equals(defaultScopeName)) {
      resultScope = scope;
      break;
    }
  }
  if (resultScope == null) {
    resultScope = ProjectScope.getProjectScope(project);
  }
  return resultScope;
}
 
Example #5
Source File: UseScopeTestCase.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
@Test
public void testUseScope() throws Exception {
    PsiReference variableReference = configure();
    PsiFile included = addFile("included.bash");
    PsiFile notIncluded = addFile("notIncluded.bash");

    PsiElement varDef = variableReference.resolve();
    Assert.assertNotNull("Var must resolve", varDef);
    Assert.assertTrue("var def must resolve to the definition in included.bash", included.equals(varDef.getContainingFile()));

    SearchScope varDefUseScope = varDef.getUseScope();
    Assert.assertTrue("Invalid type of scope: " + varDefUseScope, varDefUseScope instanceof GlobalSearchScope);

    GlobalSearchScope useScope = (GlobalSearchScope) varDefUseScope;
    Assert.assertTrue("The use scope must contain the original file itself.", useScope.contains(included.getVirtualFile()));

    //must contain the file which contains the include statement
    Assert.assertTrue("The use scope must contain the files which include the source file.", useScope.contains(myFile.getVirtualFile()));

    //must not contain the file which does not include the inspected file
    Assert.assertFalse("The use scope must not contain any other file.", useScope.contains(notIncluded.getVirtualFile()));
}
 
Example #6
Source File: ShowUsagesAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static MyModel setTableModel(@Nonnull JTable table,
                                     @Nonnull UsageViewImpl usageView,
                                     @Nonnull final List<UsageNode> data,
                                     @Nonnull AtomicInteger outOfScopeUsages,
                                     @Nonnull SearchScope searchScope) {
  ApplicationManager.getApplication().assertIsDispatchThread();
  final int columnCount = calcColumnCount(data);
  MyModel model = table.getModel() instanceof MyModel ? (MyModel)table.getModel() : null;
  if (model == null || model.getColumnCount() != columnCount) {
    model = new MyModel(data, columnCount);
    table.setModel(model);

    ShowUsagesTableCellRenderer renderer = new ShowUsagesTableCellRenderer(usageView, outOfScopeUsages, searchScope);
    for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
      TableColumn column = table.getColumnModel().getColumn(i);
      column.setPreferredWidth(0);
      column.setCellRenderer(renderer);
    }
  }
  return model;
}
 
Example #7
Source File: CSharpAllTypesSearchExecutor.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@Override
public boolean execute(@Nonnull final AllTypesSearch.SearchParameters queryParameters, @Nonnull final Processor<? super DotNetTypeDeclaration> consumer)
{
	SearchScope scope = queryParameters.getScope();

	if(scope instanceof GlobalSearchScope)
	{
		return processAllClassesInGlobalScope((GlobalSearchScope) scope, consumer, queryParameters);
	}

	PsiElement[] scopeRoots = ((LocalSearchScope) scope).getScope();
	for(final PsiElement scopeRoot : scopeRoots)
	{
		if(!processScopeRootForAllClasses(scopeRoot, consumer))
		{
			return false;
		}
	}
	return true;
}
 
Example #8
Source File: LSPRenameProcessor.java    From lsp4intellij with Apache License 2.0 6 votes vote down vote up
@NotNull
@SuppressWarnings("unused")
public Collection<PsiReference> findReferences(@NotNull PsiElement element, @NotNull SearchScope searchScope,
                                               boolean searchInCommentsAndStrings) {
    if (element instanceof LSPPsiElement) {
        if (elements.contains(element)) {
            return elements.stream().map(PsiElement::getReference).filter(Objects::nonNull).collect(Collectors.toList());
        }
        EditorEventManager manager = EditorEventManagerBase.forEditor(FileUtils.editorFromPsiFile(element.getContainingFile()));
        if (manager != null) {
            Pair<List<PsiElement>, List<VirtualFile>> refs = manager.references(element.getTextOffset(), true, false);
            if (refs.getFirst() != null && refs.getSecond() != null) {
                addEditors(refs.getSecond());
                return refs.getFirst().stream().map(PsiElement::getReference).filter(Objects::nonNull).collect(Collectors.toList());
            }
        }
    }
    return new ArrayList<>();
}
 
Example #9
Source File: PropertiesManager.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
public MicroProfileProjectInfo getMicroProfileProjectInfo(Module module,
                                                          List<MicroProfilePropertiesScope> scopes, ClasspathKind classpathKind, IPsiUtils utils,
                                                          DocumentFormat documentFormat) {
    MicroProfileProjectInfo info = createInfo(module, classpathKind);
    long startTime = System.currentTimeMillis();
    boolean excludeTestCode = classpathKind == ClasspathKind.SRC;
    PropertiesCollector collector = new PropertiesCollector(info, scopes);
    SearchScope scope = createSearchScope(module, scopes, classpathKind == ClasspathKind.TEST);
    SearchContext context = new SearchContext(module, scope, collector, utils, documentFormat);
    DumbService.getInstance(module.getProject()).runReadActionInSmartMode(() -> {
        Query<PsiModifierListOwner> query = createSearchQuery(context);
        beginSearch(context);
        query.forEach((Consumer<? super PsiModifierListOwner>) psiMember -> collectProperties(psiMember, context));
        endSearch(context);
    });
    LOGGER.info("End computing MicroProfile properties for '" + info.getProjectURI() + "' in "
            + (System.currentTimeMillis() - startTime) + "ms.");
    return info;
}
 
Example #10
Source File: FindPopupScopeUIImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void applyTo(@Nonnull FindModel findModel, @Nonnull FindPopupScopeUI.ScopeType selectedScope) {
  if (selectedScope == PROJECT) {
    findModel.setProjectScope(true);
  }
  else if (selectedScope == DIRECTORY) {
    String directory = myDirectoryChooser.getDirectory();
    findModel.setDirectoryName(directory);
  }
  else if (selectedScope == MODULE) {
    findModel.setModuleName((String)myModuleComboBox.getSelectedItem());
  }
  else if (selectedScope == SCOPE) {
    SearchScope selectedCustomScope = myScopeCombo.getSelectedScope();
    String customScopeName = selectedCustomScope == null ? null : selectedCustomScope.getDisplayName();
    findModel.setCustomScopeName(customScopeName);
    findModel.setCustomScope(selectedCustomScope);
    findModel.setCustomScope(true);
  }
}
 
Example #11
Source File: HaxeRenameProcessor.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@Override
public void prepareRenaming(@NotNull PsiElement element,
                            @NotNull String newName,
                            @NotNull Map<PsiElement, String> allRenames,
                            @NotNull SearchScope scope) {
  super.prepareRenaming(element, newName, allRenames, scope);
}
 
Example #12
Source File: BackwardDependenciesAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void analyze(@Nonnull final Project project, final AnalysisScope scope) {
  scope.setSearchInLibraries(true); //find library usages in project
  final SearchScope selectedScope = myPanel.myCombo.getSelectedScope();
  new BackwardDependenciesHandler(project, scope, selectedScope != null ? new AnalysisScope(selectedScope, project) : new AnalysisScope(project)).analyze();
  dispose();
}
 
Example #13
Source File: HaxeMethodsSearch.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
public static Query<PsiMethod> search(final PsiMethod method, SearchScope scope, final boolean checkDeep, HaxeHierarchyTimeoutHandler timeoutHandler) {
  if (ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
    @Override
    public Boolean compute() {
      return cannotBeOverriden(method);
    }
  })) return EmptyQuery.getEmptyQuery(); // Optimization
  return INSTANCE.createUniqueResultsQuery(new SearchParameters(method, scope, checkDeep));
}
 
Example #14
Source File: DaggerUseScopeEnlarger.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public SearchScope getAdditionalUseScope(PsiElement element) {
  if (isImplicitUsageMethod(element)) {
    return GlobalSearchScope.allScope(element.getProject());
  }
  return null;
}
 
Example #15
Source File: DefinitionsScopedSearch.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public SearchScope getScope() {
  return ApplicationManager.getApplication().runReadAction(new Computable<SearchScope>() {
    @Override
    public SearchScope compute() {
      return myScope.intersectWith(PsiSearchHelper.SERVICE.getInstance(myElement.getProject()).getUseScope(myElement));
    }
  });
}
 
Example #16
Source File: BaseRefactoringProcessor.java    From consulo with Apache License 2.0 5 votes vote down vote up
private Set<UnloadedModuleDescription> computeUnloadedModulesFromUseScope(UsageViewDescriptor descriptor) {
  if (ModuleManager.getInstance(myProject).getUnloadedModuleDescriptions().isEmpty()) {
    //optimization
    return Collections.emptySet();
  }

  Set<UnloadedModuleDescription> unloadedModulesInUseScope = new LinkedHashSet<>();
  for (PsiElement element : descriptor.getElements()) {
    SearchScope useScope = element.getUseScope();
    if (useScope instanceof GlobalSearchScope) {
      unloadedModulesInUseScope.addAll(((GlobalSearchScope)useScope).getUnloadedModulesBelongingToScope());
    }
  }
  return unloadedModulesInUseScope;
}
 
Example #17
Source File: ComponentResolveScopeEnlarger.java    From litho with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public SearchScope getAdditionalResolveScope(VirtualFile file, Project project) {
  if (ProjectRootManager.getInstance(project).getFileIndex().isInContent(file)) {
    return ComponentScope.getInstance();
  }
  return null;
}
 
Example #18
Source File: FindModel.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void setCustomScope(final SearchScope customScope) {
  boolean changed = this.customScope != null ? this.customScope.equals(customScope) : customScope != null;
  this.customScope = customScope;
  if (changed) {
    notifyObservers();
  }
}
 
Example #19
Source File: AutoFactoryUseScopeEnlarger.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public SearchScope getAdditionalUseScope(PsiElement element) {
  if (isAutoFactoryClass(element)) {
    return GlobalSearchScope.allScope(element.getProject());
  }
  return null;
}
 
Example #20
Source File: BlazePyUseScopeEnlarger.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public SearchScope getAdditionalUseScope(PsiElement element) {
  if (!Blaze.isBlazeProject(element.getProject())) {
    return null;
  }
  if (isPyPackageOutsideProject(element) || isPyFileOutsideProject(element)) {
    return GlobalSearchScope.projectScope(element.getProject());
  }
  return null;
}
 
Example #21
Source File: HaxeMethodPsiMixinImpl.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@NotNull
@Override
public SearchScope getUseScope() {
  if(this instanceof HaxeLocalFunctionDeclaration) {
    final PsiElement outerBlock = UsefulPsiTreeUtil.getParentOfType(this, HaxeBlockStatement.class);
    if(outerBlock != null) {
      return new LocalSearchScope(outerBlock);
    }
  }
  return super.getUseScope();
}
 
Example #22
Source File: ReformatCodeAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void registerScopeFilter(@Nonnull AbstractLayoutCodeProcessor processor, @Nullable final SearchScope scope) {
  if (scope == null) {
    return;
  }

  processor.addFileFilter(scope::contains);
}
 
Example #23
Source File: BashFileRenameProcessor.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
/**
 * Returns references to the given element. If it is a BashPsiElement a special search scope is used to locate the elements referencing the file.
 *
 * @param element References to the given element
 * @return
 */
@NotNull
@Override
public Collection<PsiReference> findReferences(PsiElement element) {
    //fixme fix the custom scope
    SearchScope scope = (element instanceof BashPsiElement)
            ? BashElementSharedImpl.getElementUseScope((BashPsiElement) element, element.getProject())
            : GlobalSearchScope.projectScope(element.getProject());

    Query<PsiReference> search = ReferencesSearch.search(element, scope);
    return search.findAll();
}
 
Example #24
Source File: FileFilterPanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
SearchScope getSearchScope() {
  if (!myUseFileMask.isSelected()) return null;
  String text = (String)myFileMask.getSelectedItem();
  if (text == null) return null;

  final Condition<CharSequence> patternCondition = FindInProjectUtil.createFileMaskCondition(text);
  return new GlobalSearchScope() {
    @Override
    public boolean contains(@Nonnull VirtualFile file) {
      return patternCondition.value(file.getNameSequence());
    }

    @Override
    public int compare(@Nonnull VirtualFile file1, @Nonnull VirtualFile file2) {
      return 0;
    }

    @Override
    public boolean isSearchInModuleContent(@Nonnull Module aModule) {
      return true;
    }

    @Override
    public boolean isSearchInLibraries() {
      return true;
    }
  };
}
 
Example #25
Source File: HaxePsiFieldImpl.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@NotNull
@Override
public SearchScope getUseScope() {
  final PsiElement localVar = UsefulPsiTreeUtil.getParentOfType(this, HaxeLocalVarDeclaration.class);
  if (localVar != null) {
    final PsiElement outerBlock = UsefulPsiTreeUtil.getParentOfType(localVar, HaxeBlockStatement.class);
    if (outerBlock != null) {
      return new LocalSearchScope(outerBlock);
    }
  }
  return super.getUseScope();
}
 
Example #26
Source File: LayoutProjectCodeDialog.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public SearchScope getSearchScope() {
  if (myUseScopeFilteringCb.isSelected()) {
    return myScopeCombo.getSelectedScope();
  }

  return null;
}
 
Example #27
Source File: ReferenceSearchHelperTest.java    From Intellij-Plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
    super.setUp();
    project = myFixture.getProject();
    moduleHelper = mock(ModuleHelper.class);
    scope = mock(SearchScope.class);
    collector = mock(StepCollector.class);
}
 
Example #28
Source File: CSharpParameterImpl.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public SearchScope getUseScope()
{
	PsiElement parent = getParent();
	if(parent instanceof DotNetParameterList)
	{
		return new LocalSearchScope(parent.getParent());
	}
	return super.getUseScope();
}
 
Example #29
Source File: AnalysisScope.java    From consulo with Apache License 2.0 5 votes vote down vote up
public AnalysisScope(@Nonnull SearchScope scope, @Nonnull Project project) {
  myProject = project;
  myElement = null;
  myModule = null;
  myModules = null;
  myScope = scope;
  myType = CUSTOM;
  mySearchInLibraries = scope instanceof GlobalSearchScope && ((GlobalSearchScope)scope).isSearchInLibraries();
  myVFiles = null;
}
 
Example #30
Source File: ShowUsagesAction.java    From dagger-intellij-plugin with Apache License 2.0 5 votes vote down vote up
@NotNull
private static SearchScope notNullizeScope(@NotNull FindUsagesOptions options,
    @NotNull Project project) {
  SearchScope scope = options.searchScope;
  if (scope == null) return ProjectScope.getAllScope(project);
  return scope;
}