@Nullable public static String getReferencePrefix(@NotNull PsiElement insertedElement, int offsetInFile) { final PsiReference ref = insertedElement.getContainingFile().findReferenceAt(offsetInFile); if (ref != null) { final PsiElement element = ref.getElement(); final int endIndex = offsetInFile - element.getTextRange().getStartOffset(); final int beginIndex = ref.getRangeInElement().getStartOffset(); if (beginIndex > endIndex) { LOG.error( "Inconsistent reference (found at offset not included in its range): ref=" + ref + " element=" + element + " text=" + element.getText()); } if (beginIndex < 0) { LOG.error( "Inconsistent reference (begin < 0): ref=" + ref + " element=" + element + "; begin=" + beginIndex + " text=" + element.getText()); } LOG.assertTrue(endIndex >= 0); return element.getText().substring(beginIndex, endIndex); } return null; }
public void doClone(PsiElement element) { FeatureUsageTracker.getInstance().triggerFeatureUsed("refactoring.copyClass"); PsiClass[] classes = getTopLevelClasses(element); if (classes == null) { CopyFilesOrDirectoriesHandler.doCloneFile(element); return; } Project project = element.getProject(); CopyClassDialog dialog = new CopyClassDialog(classes[0], null, project, true); dialog.setTitle(RefactoringBundle.message("copy.handler.clone.class")); dialog.show(); if (dialog.isOK()) { String className = dialog.getClassName(); PsiDirectory targetDirectory = element.getContainingFile().getContainingDirectory(); copyClassesImpl( className, project, Collections.singletonMap(classes[0].getContainingFile(), classes), null, targetDirectory, targetDirectory, RefactoringBundle.message("copy.handler.clone.class"), true, true); } }
private void processUsagesPerFile(UsageInfo[] usages) { Map<PsiFile, List<EncapsulateFieldUsageInfo>> usagesInFiles = new HashMap<PsiFile, List<EncapsulateFieldUsageInfo>>(); for (UsageInfo usage : usages) { PsiElement element = usage.getElement(); if (element == null) continue; final PsiFile file = element.getContainingFile(); List<EncapsulateFieldUsageInfo> usagesInFile = usagesInFiles.get(file); if (usagesInFile == null) { usagesInFile = new ArrayList<EncapsulateFieldUsageInfo>(); usagesInFiles.put(file, usagesInFile); } usagesInFile.add(((EncapsulateFieldUsageInfo) usage)); } for (List<EncapsulateFieldUsageInfo> usageInfos : usagesInFiles.values()) { // this is to avoid elements to become invalid as a result of processUsage final EncapsulateFieldUsageInfo[] infos = usageInfos.toArray(new EncapsulateFieldUsageInfo[usageInfos.size()]); CommonRefactoringUtil.sortDepthFirstRightLeftOrder(infos); for (EncapsulateFieldUsageInfo info : infos) { EncapsulateFieldHelper helper = EncapsulateFieldHelper.getHelper(info.getElement().getLanguage()); helper.processUsage( info, myDescriptor, myNameToSetter.get(info.getFieldDescriptor().getSetterName()), myNameToGetter.get(info.getFieldDescriptor().getGetterName())); } } }
@Override @Nullable public List<Pair<PsiElement, TextRange>> getInjectedPsiFiles(@NotNull final PsiElement host) { if (!(host instanceof PsiLanguageInjectionHost) || !((PsiLanguageInjectionHost) host).isValidHost()) { return null; } final PsiElement inTree = InjectedLanguageUtil.loadTree(host, host.getContainingFile()); final List<Pair<PsiElement, TextRange>> result = new SmartList<Pair<PsiElement, TextRange>>(); InjectedLanguageUtil.enumerate( inTree, new PsiLanguageInjectionHost.InjectedPsiVisitor() { @Override public void visit( @NotNull PsiFile injectedPsi, @NotNull List<PsiLanguageInjectionHost.Shred> places) { for (PsiLanguageInjectionHost.Shred place : places) { if (place.getHost() == inTree) { result.add( new Pair<PsiElement, TextRange>(injectedPsi, place.getRangeInsideHost())); } } } }); return result.isEmpty() ? null : result; }
public boolean commitTransaction(final Document document) { ApplicationManager.getApplication().assertIsDispatchThread(); final DocumentChangeTransaction documentChangeTransaction = removeTransaction(document); if (documentChangeTransaction == null) return false; final PsiElement changeScope = documentChangeTransaction.getChangeScope(); try { mySyncDocument = document; final PsiTreeChangeEventImpl fakeEvent = new PsiTreeChangeEventImpl(changeScope.getManager()); fakeEvent.setParent(changeScope); fakeEvent.setFile(changeScope.getContainingFile()); doSync( fakeEvent, true, new DocSyncAction() { @Override public void syncDocument(Document document, PsiTreeChangeEventImpl event) { doCommitTransaction(document, documentChangeTransaction); } }); myBus .syncPublisher(PsiDocumentTransactionListener.TOPIC) .transactionCompleted(document, (PsiFile) changeScope); } finally { mySyncDocument = null; } return true; }
@Override public final void actionPerformed(final AnActionEvent event) { final DataContext dataContext = event.getDataContext(); final HierarchyBrowserBaseEx browser = (HierarchyBrowserBaseEx) dataContext.getData(myBrowserDataKey); if (browser == null) return; final PsiElement selectedElement = browser.getSelectedElement(); if (selectedElement == null || !browser.isApplicableElement(selectedElement)) return; final String currentViewType = browser.myCurrentViewType; Disposer.dispose(browser); final HierarchyProvider provider = BrowseHierarchyActionBase.findProvider( myProviderLanguageExtension, selectedElement, selectedElement.getContainingFile(), event.getDataContext()); final HierarchyBrowser newBrowser = BrowseHierarchyActionBase.createAndAddToPanel( selectedElement.getProject(), provider, selectedElement); ApplicationManager.getApplication() .invokeLater( () -> ((HierarchyBrowserBaseEx) newBrowser) .changeView(correctViewType(browser, currentViewType))); }
@Override public PsiType[] guessContainerElementType(PsiExpression containerExpr, TextRange rangeToIgnore) { HashSet<PsiType> typesSet = new HashSet<>(); PsiType type = containerExpr.getType(); PsiType elemType; if ((elemType = getGenericElementType(type)) != null) return new PsiType[] {elemType}; if (containerExpr instanceof PsiReferenceExpression) { PsiElement refElement = ((PsiReferenceExpression) containerExpr).resolve(); if (refElement instanceof PsiVariable) { PsiFile file = refElement.getContainingFile(); if (file == null) { file = containerExpr.getContainingFile(); // implicit variable in jsp } HashSet<PsiVariable> checkedVariables = new HashSet<>(); addTypesByVariable( typesSet, (PsiVariable) refElement, file, checkedVariables, CHECK_USAGE | CHECK_DOWN, rangeToIgnore); checkedVariables.clear(); addTypesByVariable( typesSet, (PsiVariable) refElement, file, checkedVariables, CHECK_UP, rangeToIgnore); } } return typesSet.toArray(PsiType.createArray(typesSet.size())); }
public static boolean isValidName( final Project project, final PsiElement psiElement, final String newName) { if (newName == null || newName.length() == 0) { return false; } final Condition<String> inputValidator = RenameInputValidatorRegistry.getInputValidator(psiElement); if (inputValidator != null) { return inputValidator.value(newName); } if (psiElement instanceof PsiFile || psiElement instanceof PsiDirectory) { return newName.indexOf('\\') < 0 && newName.indexOf('/') < 0; } if (psiElement instanceof PomTargetPsiElement) { return !StringUtil.isEmptyOrSpaces(newName); } final PsiFile file = psiElement.getContainingFile(); final Language elementLanguage = psiElement.getLanguage(); final Language fileLanguage = file == null ? null : file.getLanguage(); Language language = fileLanguage == null ? elementLanguage : fileLanguage.isKindOf(elementLanguage) ? fileLanguage : elementLanguage; return LanguageNamesValidation.INSTANCE .forLanguage(language) .isIdentifier(newName.trim(), project); }
private JavaResolveResult advancedResolveInner(final PsiElement psiElement, final String qName) { final PsiManager manager = psiElement.getManager(); final GlobalSearchScope scope = getScope(); if (myIndex == myJavaClassReferenceSet.getReferences().length - 1) { final PsiClass aClass = JavaPsiFacade.getInstance(manager.getProject()).findClass(qName, scope); if (aClass != null) { return new ClassCandidateInfo(aClass, PsiSubstitutor.EMPTY, false, psiElement); } else { if (!JavaClassReferenceProvider.ADVANCED_RESOLVE.getBooleanValue(getOptions())) { return JavaResolveResult.EMPTY; } } } PsiElement resolveResult = JavaPsiFacade.getInstance(manager.getProject()).findPackage(qName); if (resolveResult == null) { resolveResult = JavaPsiFacade.getInstance(manager.getProject()).findClass(qName, scope); } if (myInStaticImport && resolveResult == null) { resolveResult = resolveMember(qName, manager, getElement().getResolveScope()); } if (resolveResult == null) { PsiFile containingFile = psiElement.getContainingFile(); if (containingFile instanceof PsiJavaFile) { if (containingFile instanceof JspFile) { containingFile = containingFile.getViewProvider().getPsi(StdLanguages.JAVA); if (containingFile == null) return JavaResolveResult.EMPTY; } final ClassResolverProcessor processor = new ClassResolverProcessor(getCanonicalText(), psiElement); containingFile.processDeclarations(processor, ResolveState.initial(), null, psiElement); if (processor.getResult().length == 1) { final JavaResolveResult javaResolveResult = processor.getResult()[0]; if (javaResolveResult != JavaResolveResult.EMPTY && getOptions() != null) { final Boolean value = JavaClassReferenceProvider.RESOLVE_QUALIFIED_CLASS_NAME.getValue(getOptions()); final PsiClass psiClass = (PsiClass) javaResolveResult.getElement(); if (value != null && value.booleanValue() && psiClass != null) { final String qualifiedName = psiClass.getQualifiedName(); if (!qName.equals(qualifiedName)) { return JavaResolveResult.EMPTY; } } } return javaResolveResult; } } } return resolveResult != null ? new CandidateInfo(resolveResult, PsiSubstitutor.EMPTY, false, false, psiElement) : JavaResolveResult.EMPTY; }
@Nullable protected PsiFile getContainingFile() { final PsiFile file = InjectedLanguageUtil.getTopLevelFile(myElement.getContainingFile()); if (file == null) { LOG.error("Invalid element: " + myElement); } return file.getOriginalFile(); }
@Override public int injectedToHost(@NotNull PsiElement element, int offset) { PsiFile file = element.getContainingFile(); if (file == null) return offset; Document document = PsiDocumentManager.getInstance(file.getProject()).getCachedDocument(file); if (!(document instanceof DocumentWindowImpl)) return offset; DocumentWindowImpl documentWindow = (DocumentWindowImpl) document; return documentWindow.injectedToHost(offset); }
public static boolean isClassEquivalentTo(@NotNull PsiClass aClass, PsiElement another) { if (aClass == another) return true; if (!(another instanceof PsiClass)) return false; String name1 = aClass.getName(); if (name1 == null) return false; if (!another.isValid()) return false; String name2 = ((PsiClass) another).getName(); if (name2 == null) return false; if (name1.hashCode() != name2.hashCode()) return false; if (!name1.equals(name2)) return false; String qName1 = aClass.getQualifiedName(); String qName2 = ((PsiClass) another).getQualifiedName(); if (qName1 == null || qName2 == null) { //noinspection StringEquality if (qName1 != qName2) return false; if (aClass instanceof PsiTypeParameter && another instanceof PsiTypeParameter) { PsiTypeParameter p1 = (PsiTypeParameter) aClass; PsiTypeParameter p2 = (PsiTypeParameter) another; return p1.getIndex() == p2.getIndex() && aClass.getManager().areElementsEquivalent(p1.getOwner(), p2.getOwner()); } else { return false; } } if (qName1.hashCode() != qName2.hashCode() || !qName1.equals(qName2)) { return false; } if (originalElement(aClass).equals(originalElement((PsiClass) another))) { return true; } final PsiFile file1 = aClass.getContainingFile().getOriginalFile(); final PsiFile file2 = another.getContainingFile().getOriginalFile(); // see com.intellij.openapi.vcs.changes.PsiChangeTracker // see com.intellij.psi.impl.PsiFileFactoryImpl#createFileFromText(CharSequence,PsiFile) final PsiFile original1 = file1.getUserData(PsiFileFactory.ORIGINAL_FILE); final PsiFile original2 = file2.getUserData(PsiFileFactory.ORIGINAL_FILE); if (original1 == original2 && original1 != null || original1 == file2 || original2 == file1 || file1 == file2) { return compareClassSeqNumber(aClass, (PsiClass) another); } final FileIndexFacade fileIndex = ServiceManager.getService(file1.getProject(), FileIndexFacade.class); final VirtualFile vfile1 = file1.getViewProvider().getVirtualFile(); final VirtualFile vfile2 = file2.getViewProvider().getVirtualFile(); boolean lib1 = fileIndex.isInLibraryClasses(vfile1); boolean lib2 = fileIndex.isInLibraryClasses(vfile2); return (fileIndex.isInSource(vfile1) || lib1) && (fileIndex.isInSource(vfile2) || lib2); }
private static void findClassUsages( final PsiClass psiClass, final PsiElement[] allElementsToDelete, final List<UsageInfo> usages) { final boolean justPrivates = containsOnlyPrivates(psiClass); final String qualifiedName = psiClass.getQualifiedName(); final boolean annotationType = psiClass.isAnnotationType() && qualifiedName != null; ReferencesSearch.search(psiClass) .forEach( reference -> { final PsiElement element = reference.getElement(); if (!isInside(element, allElementsToDelete)) { PsiElement parent = element.getParent(); if (parent instanceof PsiReferenceList) { final PsiElement pparent = parent.getParent(); if (pparent instanceof PsiClass && element instanceof PsiJavaCodeReferenceElement) { final PsiClass inheritor = (PsiClass) pparent; // If psiClass contains only private members, then it is safe to remove it and // change inheritor's extends/implements accordingly if (justPrivates) { if (parent.equals(inheritor.getExtendsList()) || parent.equals(inheritor.getImplementsList())) { usages.add( new SafeDeleteExtendsClassUsageInfo( (PsiJavaCodeReferenceElement) element, psiClass, inheritor)); return true; } } } } LOG.assertTrue(element.getTextRange() != null); final PsiFile containingFile = psiClass.getContainingFile(); boolean sameFileWithSingleClass = false; if (containingFile instanceof PsiClassOwner) { final PsiClass[] classes = ((PsiClassOwner) containingFile).getClasses(); sameFileWithSingleClass = classes.length == 1 && classes[0] == psiClass && element.getContainingFile() == containingFile; } final boolean safeDelete = sameFileWithSingleClass || isInNonStaticImport(element); if (annotationType && parent instanceof PsiAnnotation) { usages.add( new SafeDeleteAnnotation((PsiAnnotation) parent, psiClass, safeDelete)); } else { usages.add( new SafeDeleteReferenceJavaDeleteUsageInfo(element, psiClass, safeDelete)); } } return true; }); }
@NotNull private static Couple<Collection<TextRange>> getUsages( @NotNull PsiElement target, PsiElement psiElement, boolean withDeclarations, boolean detectAccess) { List<TextRange> readRanges = new ArrayList<TextRange>(); List<TextRange> writeRanges = new ArrayList<TextRange>(); final ReadWriteAccessDetector detector = detectAccess ? ReadWriteAccessDetector.findDetector(target) : null; final FindUsagesManager findUsagesManager = ((FindManagerImpl) FindManager.getInstance(target.getProject())).getFindUsagesManager(); final FindUsagesHandler findUsagesHandler = findUsagesManager.getFindUsagesHandler(target, true); final LocalSearchScope scope = new LocalSearchScope(psiElement); Collection<PsiReference> refs = findUsagesHandler != null ? findUsagesHandler.findReferencesToHighlight(target, scope) : ReferencesSearch.search(target, scope).findAll(); for (PsiReference psiReference : refs) { if (psiReference == null) { LOG.error( "Null reference returned, findUsagesHandler=" + findUsagesHandler + "; target=" + target + " of " + target.getClass()); continue; } List<TextRange> destination; if (detector == null || detector.getReferenceAccess(target, psiReference) == ReadWriteAccessDetector.Access.Read) { destination = readRanges; } else { destination = writeRanges; } HighlightUsagesHandler.collectRangesToHighlight(psiReference, destination); } if (withDeclarations) { final TextRange declRange = HighlightUsagesHandler.getNameIdentifierRange(psiElement.getContainingFile(), target); if (declRange != null) { if (detector != null && detector.isDeclarationWriteAccess(target)) { writeRanges.add(declRange); } else { readRanges.add(declRange); } } } return Couple.<Collection<TextRange>>of(readRanges, writeRanges); }
public JavaCompletionProcessor( PsiElement element, ElementFilter filter, final boolean checkAccess, boolean checkInitialized, @Nullable Condition<String> nameCondition) { myCheckAccess = checkAccess; mySettings = CodeInsightSettings.getInstance(); myResults = new ArrayList<CompletionElement>(); myElement = element; myMatcher = nameCondition; myFilter = filter; PsiElement scope = element; if (JavaResolveUtil.isInJavaDoc(myElement)) myMembersFlag = true; while (scope != null && !(scope instanceof PsiFile) && !(scope instanceof PsiClass)) { scope = scope.getContext(); } myScope = scope; if (!(element.getContainingFile() instanceof PsiJavaFile)) { myMembersFlag = true; } PsiElement elementParent = element.getContext(); if (elementParent instanceof PsiReferenceExpression) { PsiExpression qualifier = ((PsiReferenceExpression) elementParent).getQualifierExpression(); if (qualifier instanceof PsiSuperExpression) { final PsiJavaCodeReferenceElement qSuper = ((PsiSuperExpression) qualifier).getQualifier(); if (qSuper == null) { myQualifierClass = JavaResolveUtil.getContextClass(myElement); } else { final PsiElement target = qSuper.resolve(); myQualifierClass = target instanceof PsiClass ? (PsiClass) target : null; } if (myQualifierClass != null) { myQualifierType = JavaPsiFacade.getInstance(element.getProject()) .getElementFactory() .createType(myQualifierClass); } } else if (qualifier != null) { myQualifierType = qualifier.getType(); myQualifierClass = PsiUtil.resolveClassInType(myQualifierType); if (myQualifierType == null && qualifier instanceof PsiJavaCodeReferenceElement) { final PsiElement target = ((PsiJavaCodeReferenceElement) qualifier).resolve(); if (target instanceof PsiClass) { myQualifierClass = (PsiClass) target; } } } } if (checkInitialized) { myNonInitializedFields.addAll(getNonInitializedFields(element)); } }
@Override @NotNull public TextRange injectedToHost( @NotNull PsiElement injectedContext, @NotNull TextRange injectedTextRange) { PsiFile file = injectedContext.getContainingFile(); if (file == null) return injectedTextRange; Document document = PsiDocumentManager.getInstance(file.getProject()).getCachedDocument(file); if (!(document instanceof DocumentWindowImpl)) return injectedTextRange; DocumentWindowImpl documentWindow = (DocumentWindowImpl) document; return documentWindow.injectedToHost(injectedTextRange); }
@NotNull private static Set<VirtualFile> getLocalScopeFiles(@NotNull LocalSearchScope scope) { Set<VirtualFile> files = new LinkedHashSet<VirtualFile>(); for (PsiElement element : scope.getScope()) { PsiFile file = element.getContainingFile(); if (file != null) { ContainerUtil.addIfNotNull(files, file.getVirtualFile()); } } return files; }
public PomModelEvent runInner() throws IncorrectOperationException { final ASTNode anchor = expandTag(); if (myChild.getElementType() == XmlElementType.XML_TAG) { // compute where to insert tag according to DTD or XSD final XmlElementDescriptor parentDescriptor = getDescriptor(); final XmlTag[] subTags = getSubTags(); final PsiElement declaration = parentDescriptor != null ? parentDescriptor.getDeclaration() : null; // filtring out generated dtds if (declaration != null && declaration.getContainingFile() != null && declaration.getContainingFile().isPhysical() && subTags.length > 0) { final XmlElementDescriptor[] childElementDescriptors = parentDescriptor.getElementsDescriptors(XmlTagImpl.this); int subTagNum = -1; for (final XmlElementDescriptor childElementDescriptor : childElementDescriptors) { final String childElementName = childElementDescriptor.getName(); while (subTagNum < subTags.length - 1 && subTags[subTagNum + 1].getName().equals(childElementName)) { subTagNum++; } if (childElementName.equals( XmlChildRole.START_TAG_NAME_FINDER.findChild(myChild).getText())) { // insert child just after anchor // insert into the position specified by index if (subTagNum >= 0) { final ASTNode subTag = (ASTNode) subTags[subTagNum]; if (subTag.getTreeParent() != XmlTagImpl.this) { // in entity final XmlEntityRef entityRef = PsiTreeUtil.getParentOfType(subTags[subTagNum], XmlEntityRef.class); throw new IncorrectOperationException( "Can't insert subtag to the entity. Entity reference text: " + (entityRef == null ? "" : entityRef.getText())); } myNewElement = XmlTagImpl.super.addInternal(myChild, myChild, subTag, Boolean.FALSE); } else { final ASTNode child = XmlChildRole.START_TAG_END_FINDER.findChild(XmlTagImpl.this); myNewElement = XmlTagImpl.super.addInternal(myChild, myChild, child, Boolean.FALSE); } return null; } } } else { final ASTNode child = XmlChildRole.CLOSING_TAG_START_FINDER.findChild(XmlTagImpl.this); myNewElement = XmlTagImpl.super.addInternal(myChild, myChild, child, Boolean.TRUE); return null; } } myNewElement = XmlTagImpl.super.addInternal(myChild, myChild, anchor, Boolean.TRUE); return null; }
@Nullable private static Map<PsiFile, PsiClass[]> convertToTopLevelClasses( final PsiElement[] elements, final boolean fromUpdate, String relativePath, Map<PsiFile, String> relativeMap) { final Map<PsiFile, PsiClass[]> result = new HashMap<PsiFile, PsiClass[]>(); for (PsiElement element : elements) { final PsiElement navigationElement = element.getNavigationElement(); LOG.assertTrue(navigationElement != null, element); final PsiFile containingFile = navigationElement.getContainingFile(); if (!(containingFile instanceof PsiClassOwner && ProjectRootsUtil.isOutsideSourceRoot(containingFile))) { PsiClass[] topLevelClasses = getTopLevelClasses(element); if (topLevelClasses == null) { if (element instanceof PsiDirectory) { if (!fromUpdate) { final String name = ((PsiDirectory) element).getName(); final String path = relativePath != null ? (relativePath.length() > 0 ? (relativePath + "/") : "") + name : null; final Map<PsiFile, PsiClass[]> map = convertToTopLevelClasses(element.getChildren(), fromUpdate, path, relativeMap); if (map == null) return null; for (Map.Entry<PsiFile, PsiClass[]> entry : map.entrySet()) { fillResultsMap(result, entry.getKey(), entry.getValue()); } } continue; } if (!(element instanceof PsiFileSystemItem)) return null; } fillResultsMap(result, containingFile, topLevelClasses); if (relativeMap != null) { relativeMap.put(containingFile, relativePath); } } } if (result.isEmpty()) { return null; } else { boolean hasClasses = false; for (PsiClass[] classes : result.values()) { if (classes != null) { hasClasses = true; break; } } return hasClasses ? result : null; } }
@Override public boolean isWritableStepLikeFile(@NotNull PsiElement child, @NotNull PsiElement parent) { if (child instanceof PsiJavaFile) { final PsiFile file = child.getContainingFile(); if (file != null) { final VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile != null) { return virtualFile.isWritable(); } } } return false; }
@Override public PsiLanguageInjectionHost getInjectionHost(@NotNull PsiElement element) { final PsiFile file = element.getContainingFile(); final VirtualFile virtualFile = file == null ? null : file.getVirtualFile(); if (virtualFile instanceof VirtualFileWindow) { PsiElement host = FileContextUtil.getFileContext( file); // use utility method in case the file's overridden getContext() if (host instanceof PsiLanguageInjectionHost) { return (PsiLanguageInjectionHost) host; } } return null; }
public void startTransaction(@NotNull Project project, Document doc, PsiElement scope) { LOG.assertTrue(!project.isDisposed()); Pair<DocumentChangeTransaction, Integer> pair = myTransactionsMap.get(doc); if (pair == null) { final PsiFile psiFile = scope != null ? scope.getContainingFile() : null; pair = new Pair<DocumentChangeTransaction, Integer>( new DocumentChangeTransaction(doc, scope != null ? psiFile : null), 0); myBus.syncPublisher(PsiDocumentTransactionListener.TOPIC).transactionStarted(doc, psiFile); } else { pair = new Pair<DocumentChangeTransaction, Integer>( pair.getFirst(), pair.getSecond().intValue() + 1); } myTransactionsMap.put(doc, pair); }
@Nullable public VirtualFile findAppDirectory(@Nullable PsiElement element) { if (element == null) return null; PsiFile containingFile = element.getContainingFile().getOriginalFile(); VirtualFile file = containingFile.getVirtualFile(); if (file == null) return null; ProjectFileIndex index = ProjectRootManager.getInstance(containingFile.getProject()).getFileIndex(); VirtualFile root = index.getContentRootForFile(file); if (root == null) return null; return root.findChild(getApplicationDirectoryName()); }
public static boolean isStaticallyImported( @NotNull PsiMember member, @NotNull PsiElement context) { final PsiClass memberClass = member.getContainingClass(); if (memberClass == null) { return false; } final PsiClass containingClass = PsiTreeUtil.getParentOfType(context, PsiClass.class); if (InheritanceUtil.isInheritorOrSelf(containingClass, memberClass, true)) { return false; } final PsiFile psiFile = context.getContainingFile(); if (!(psiFile instanceof PsiJavaFile)) { return false; } final PsiJavaFile javaFile = (PsiJavaFile) psiFile; final PsiImportList importList = javaFile.getImportList(); if (importList == null) { return false; } final String memberName = member.getName(); if (memberName == null) { return false; } final PsiImportStatementBase existingImportStatement = importList.findSingleImportStatement(memberName); if (existingImportStatement instanceof PsiImportStaticStatement) { final PsiClass importClass = ((PsiImportStaticStatement) existingImportStatement).resolveTargetClass(); if (InheritanceUtil.isInheritorOrSelf(importClass, memberClass, true)) { return true; } } final String memberClassName = memberClass.getQualifiedName(); if (memberClassName == null) { return false; } final PsiImportStaticStatement onDemandImportStatement = findOnDemandImportStaticStatement(importList, memberClassName); if (onDemandImportStatement != null) { if (!hasOnDemandImportStaticConflict(memberClassName, memberName, context)) { return true; } } return false; }
public static void renameNonCodeUsages( @NotNull Project project, @NotNull NonCodeUsageInfo[] usages) { PsiDocumentManager.getInstance(project).commitAllDocuments(); Map<Document, List<UsageOffset>> docsToOffsetsMap = new HashMap<Document, List<UsageOffset>>(); final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project); for (NonCodeUsageInfo usage : usages) { PsiElement element = usage.getElement(); if (element == null) continue; element = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(element, true); if (element == null) continue; final ProperTextRange rangeInElement = usage.getRangeInElement(); if (rangeInElement == null) continue; final PsiFile containingFile = element.getContainingFile(); final Document document = psiDocumentManager.getDocument(containingFile); final Segment segment = usage.getSegment(); LOG.assertTrue(segment != null); int fileOffset = segment.getStartOffset(); List<UsageOffset> list = docsToOffsetsMap.get(document); if (list == null) { list = new ArrayList<UsageOffset>(); docsToOffsetsMap.put(document, list); } list.add(new UsageOffset(fileOffset, fileOffset + rangeInElement.getLength(), usage.newText)); } for (Document document : docsToOffsetsMap.keySet()) { List<UsageOffset> list = docsToOffsetsMap.get(document); LOG.assertTrue(list != null, document); UsageOffset[] offsets = list.toArray(new UsageOffset[list.size()]); Arrays.sort(offsets); for (int i = offsets.length - 1; i >= 0; i--) { UsageOffset usageOffset = offsets[i]; document.replaceString(usageOffset.startOffset, usageOffset.endOffset, usageOffset.newText); } PsiDocumentManager.getInstance(project).commitDocument(document); } PsiDocumentManager.getInstance(project).commitAllDocuments(); }
private static PsiElement getTopmostBlock(PsiElement scope) { assert scope.isValid(); PsiElement lastScope = scope; while (true) { final PsiCodeBlock lastCodeBlock = PsiTreeUtil.getParentOfType(lastScope, PsiCodeBlock.class, true); if (lastCodeBlock == null) { break; } lastScope = lastCodeBlock; } if (lastScope == scope) { PsiFile file = scope.getContainingFile(); if (file instanceof PsiCodeFragment) { return file; } } return lastScope; }
@NotNull private Collection<PsiFileSystemItem> getContextByFile(@NotNull PsiFile file) { final PsiElement context = file.getContext(); if (context != null) file = context.getContainingFile(); if (useIncludingFileAsContext()) { final FileContextProvider contextProvider = FileContextProvider.getProvider(file); if (contextProvider != null) { final Collection<PsiFileSystemItem> folders = contextProvider.getContextFolders(file); if (!folders.isEmpty()) { return folders; } final PsiFile contextFile = contextProvider.getContextFile(file); if (contextFile != null) { return Collections.<PsiFileSystemItem>singleton(contextFile.getParent()); } } } VirtualFile virtualFile = file.getOriginalFile().getVirtualFile(); if (virtualFile != null) { final FileReferenceHelper[] helpers = FileReferenceHelperRegistrar.getHelpers(); final ArrayList<PsiFileSystemItem> list = new ArrayList<PsiFileSystemItem>(); final Project project = file.getProject(); for (FileReferenceHelper helper : helpers) { if (helper.isMine(project, virtualFile)) { list.addAll(helper.getContexts(project, virtualFile)); } } if (list.size() > 0) { return list; } final VirtualFile parent = virtualFile.getParent(); if (parent != null) { final PsiDirectory directory = file.getManager().findDirectory(parent); if (directory != null) { return Collections.<PsiFileSystemItem>singleton(directory); } } } return Collections.emptyList(); }
public static void addImportIfNeeded(@NotNull PsiClass aClass, @NotNull PsiElement context) { final PsiFile file = context.getContainingFile(); if (!(file instanceof PsiJavaFile)) { return; } final PsiJavaFile javaFile = (PsiJavaFile) file; final PsiClass outerClass = aClass.getContainingClass(); if (outerClass == null) { if (PsiTreeUtil.isAncestor(javaFile, aClass, true)) { return; } } else if (PsiTreeUtil.isAncestor(outerClass, context, true)) { final PsiElement brace = outerClass.getLBrace(); if (brace != null && brace.getTextOffset() < context.getTextOffset()) { return; } } final String qualifiedName = aClass.getQualifiedName(); if (qualifiedName == null) { return; } final PsiImportList importList = javaFile.getImportList(); if (importList == null) { return; } final String containingPackageName = javaFile.getPackageName(); @NonNls final String packageName = ClassUtil.extractPackageName(qualifiedName); if (containingPackageName.equals(packageName) || importList.findSingleClassImportStatement(qualifiedName) != null) { return; } if (importList.findOnDemandImportStatement(packageName) != null && !hasDefaultImportConflict(qualifiedName, javaFile) && !hasOnDemandImportConflict(qualifiedName, javaFile)) { return; } final Project project = importList.getProject(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiElementFactory elementFactory = psiFacade.getElementFactory(); final PsiImportStatement importStatement = elementFactory.createImportStatement(aClass); importList.add(importStatement); }
private static Collection<String> suggestKeywords(PsiElement position) { TextRange posRange = position.getTextRange(); BnfFile posFile = (BnfFile) position.getContainingFile(); BnfRule statement = PsiTreeUtil.getTopmostParentOfType(position, BnfRule.class); final TextRange range; if (statement != null) { range = new TextRange(statement.getTextRange().getStartOffset(), posRange.getStartOffset()); } else { int offset = posRange.getStartOffset(); for (PsiElement cur = GrammarUtil.getDummyAwarePrevSibling(position); cur != null; cur = GrammarUtil.getDummyAwarePrevSibling(cur)) { if (cur instanceof BnfAttrs) offset = cur.getTextRange().getEndOffset(); else if (cur instanceof BnfRule) offset = cur.getTextRange().getStartOffset(); else continue; break; } range = new TextRange(offset, posRange.getStartOffset()); } final String text = range.isEmpty() ? CompletionInitializationContext.DUMMY_IDENTIFIER : range.substring(posFile.getText()); PsiFile file = PsiFileFactory.getInstance(posFile.getProject()) .createFileFromText("a.bnf", BnfLanguage.INSTANCE, text, true, false); int completionOffset = posRange.getStartOffset() - range.getStartOffset(); GeneratedParserUtilBase.CompletionState state = new GeneratedParserUtilBase.CompletionState(completionOffset) { @Override public String convertItem(Object o) { // we do not have other keywords return o instanceof String ? (String) o : null; } }; file.putUserData(GeneratedParserUtilBase.COMPLETION_STATE_KEY, state); TreeUtil.ensureParsed(file.getNode()); return state.items; }
public void registerReference( @NotNull PsiJavaReference ref, @NotNull JavaResolveResult resolveResult) { PsiElement refElement = resolveResult.getElement(); PsiFile psiFile = refElement == null ? null : refElement.getContainingFile(); if (psiFile != null) psiFile = (PsiFile) psiFile .getNavigationElement(); // look at navigation elements because all references // resolve into Cls elements when highlighting library // source if (refElement != null && psiFile != null && myFile.getViewProvider().equals(psiFile.getViewProvider())) { registerLocalRef(ref, refElement.getNavigationElement()); } PsiElement resolveScope = resolveResult.getCurrentFileResolveScope(); if (resolveScope instanceof PsiImportStatementBase) { registerImportStatement(ref, (PsiImportStatementBase) resolveScope); } }