Java Code Examples for com.intellij.psi.PsiElement#getContainingFile()
The following examples show how to use
com.intellij.psi.PsiElement#getContainingFile() .
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: TwigBlockUtil.java From idea-php-symfony2-plugin with MIT License | 6 votes |
/** * Withs a file that extends given file scope and search for block names; based in indexed so its fast */ public static boolean hasBlockImplementations(@NotNull PsiElement blockPsiName, @NotNull FileImplementsLazyLoader implementsLazyLoader) { String blockName = blockPsiName.getText(); if(StringUtils.isBlank(blockName)) { return false; } PsiFile psiFile = blockPsiName.getContainingFile(); if(psiFile == null) { return false; } Collection<VirtualFile> twigChild = implementsLazyLoader.getFiles(); if(twigChild.size() == 0) { return false; } return hasBlockNamesForFiles(blockPsiName.getProject(), blockName, twigChild); }
Example 2
Source File: SpringReformatter.java From spring-javaformat with Apache License 2.0 | 6 votes |
private void throwNotWritableException(PsiElement element) throws IncorrectOperationException { if (element instanceof PsiDirectory) { String url = ((PsiDirectory) element).getVirtualFile().getPresentableUrl(); throw new IncorrectOperationException(PsiBundle.message("cannot.modify.a.read.only.directory", url)); } PsiFile file = element.getContainingFile(); if (file == null) { throw new IncorrectOperationException(); } VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile == null) { throw new IncorrectOperationException(); } throw new IncorrectOperationException( PsiBundle.message("cannot.modify.a.read.only.file", virtualFile.getPresentableUrl())); }
Example 3
Source File: ToolsImpl.java From consulo with Apache License 2.0 | 6 votes |
@Nonnull @Override public InspectionToolWrapper getInspectionTool(PsiElement element) { if (myTools != null) { final PsiFile containingFile = element == null ? null : element.getContainingFile(); final Project project = containingFile == null ? null : containingFile.getProject(); for (ScopeToolState state : myTools) { if (element == null) { return state.getTool(); } NamedScope scope = state.getScope(project); if (scope != null) { final PackageSet packageSet = scope.getValue(); if (packageSet != null) { if (containingFile != null && packageSet.contains(containingFile, DependencyValidationManager.getInstance(project))) { return state.getTool(); } } } } } return myDefaultState.getTool(); }
Example 4
Source File: PropertySuppressableInspectionBase.java From eslint-plugin with MIT License | 6 votes |
protected void createSuppression(@NotNull Project project, @NotNull PsiElement element, @NotNull PsiElement container) throws IncorrectOperationException { if (element.isValid()) { PsiFile psiFile = element.getContainingFile(); if (psiFile != null) { psiFile = psiFile.getOriginalFile(); } if (psiFile != null && psiFile.isValid()) { final Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile); if (document != null) { int lineNo = document.getLineNumber(element.getTextOffset()); final int lineEndOffset = document.getLineEndOffset(lineNo); CommandProcessor.getInstance().executeCommand(project, new Runnable() { public void run() { document.insertString(lineEndOffset, " //eslint-disable-line"); } }, null, null); } } } }
Example 5
Source File: SQFStatement.java From arma-intellij-plugin with MIT License | 6 votes |
/** * Used for debugging. Will return the statement the given element is contained in. * If the element is a PsiComment, <PsiComment> will be returned. Otherwise, the element's ancestor statement * text will be returned with all newlines replaced with spaces. * <p> * If the element has no parent or no {@link SQFStatement} parent, <No Statement Parent> will be returned * * @return the text, or <PsiComment> if element is a PsiComment */ @NotNull public static String debug_getStatementTextForElement(@NotNull PsiElement element) { if (element instanceof PsiComment) { return "<PsiComment>"; } if (element.getContainingFile() == null || !(element.getContainingFile() instanceof SQFFile)) { throw new IllegalArgumentException("element isn't in an SQFFile"); } while (!(element instanceof SQFStatement)) { element = element.getParent(); if (element == null) { return "<No Statement Parent>"; } } return element.getText().replaceAll("\n", " "); }
Example 6
Source File: Unity3dAssetUtil.java From consulo-unity3d with Apache License 2.0 | 6 votes |
@RequiredReadAction public static boolean isPrimaryType(@Nullable PsiElement element) { if(element == null) { return false; } PsiFile containingFile = element.getContainingFile(); if(containingFile == null) { return false; } CSharpTypeDeclaration primaryType = findPrimaryType(containingFile); return primaryType != null && PsiManager.getInstance(containingFile.getProject()).areElementsEquivalent(primaryType, element); }
Example 7
Source File: XQueryPsiImplUtil.java From intellij-xquery with Apache License 2.0 | 6 votes |
private static boolean isEquivalentPrefix(XQueryPsiElement element, PsiElement another) { boolean isElementContainingNamespace = another instanceof XQueryPrefix || another instanceof XQueryXmlTagNamespace || another instanceof XQueryAttrNamespace; if (!isElementContainingNamespace) { return false; } if (element.getContainingFile() instanceof XQueryFile && another.getContainingFile() instanceof XQueryFile) { XQueryFile elementFile = (XQueryFile) element.getContainingFile(); XQueryFile anotherFile = (XQueryFile) another.getContainingFile(); String elementNamespace = elementFile.mapFunctionPrefixToNamespace(element.getText()); String anotherNamespace = anotherFile.mapFunctionPrefixToNamespace(another.getText()); return elementFile.equals(anotherFile) && elementNamespace.equals(anotherNamespace); } return false; }
Example 8
Source File: ExternalFormatProcessor.java From consulo with Apache License 2.0 | 6 votes |
/** * @param elementToFormat the element from code file * @param range the range for formatting * @param canChangeWhiteSpacesOnly procedure can change only whitespaces * @return the element after formatting */ @Nonnull static PsiElement formatElement(@Nonnull PsiElement elementToFormat, @Nonnull TextRange range, boolean canChangeWhiteSpacesOnly) { final PsiFile file = elementToFormat.getContainingFile(); final Document document = file.getViewProvider().getDocument(); if (document != null) { final TextRange rangeAfterFormat = formatRangeInFile(file, range, canChangeWhiteSpacesOnly); if (rangeAfterFormat != null) { PsiDocumentManager.getInstance(file.getProject()).commitDocument(document); if (!elementToFormat.isValid()) { PsiElement elementAtStart = file.findElementAt(rangeAfterFormat.getStartOffset()); if (elementAtStart instanceof PsiWhiteSpace) { elementAtStart = PsiTreeUtil.nextLeaf(elementAtStart); } if (elementAtStart != null) { PsiElement parent = PsiTreeUtil.getParentOfType(elementAtStart, elementToFormat.getClass()); if (parent != null) { return parent; } return elementAtStart; } } } } return elementToFormat; }
Example 9
Source File: XmlGotoCompletionRegistrar.java From idea-php-symfony2-plugin with MIT License | 6 votes |
@NotNull @Override public Collection<PsiElement> getPsiTargets(PsiElement element) { String xmlAttributeValue = GotoCompletionUtil.getXmlAttributeValue(element); if(xmlAttributeValue == null) { return Collections.emptyList(); } Collection<PsiElement> targets = new ArrayList<>(); targets.addAll(FileResourceUtil.getFileResourceTargetsInBundleScope(element.getProject(), xmlAttributeValue)); targets.addAll(FileResourceUtil.getFileResourceTargetsInBundleDirectory(element.getProject(), xmlAttributeValue)); PsiFile containingFile = element.getContainingFile(); if(containingFile != null) { targets.addAll(FileResourceUtil.getFileResourceTargetsInDirectoryScope(containingFile, xmlAttributeValue)); } return targets; }
Example 10
Source File: BashVarVariantsProcessor.java From BashSupport with Apache License 2.0 | 6 votes |
public boolean execute(@NotNull PsiElement psiElement, @NotNull ResolveState resolveState) { ProgressManager.checkCanceled(); if (startFile != null) { PsiFile file = psiElement.getContainingFile(); if (!allowSameFile && startFile.isEquivalentTo(file)) { return true; } if (!allowOtherFiles && !startFile.isEquivalentTo(file)) { return true; } } if (psiElement instanceof BashVarDef) { BashVarDef varDef = (BashVarDef) psiElement; if (varDef.isStaticAssignmentWord() && !varDef.isCommandLocal() && !variableNames.contains(varDef.getName()) && BashVarUtils.isInDefinedScope(startElement, varDef)) { variables.add(varDef); variableNames.add(varDef.getName()); } } return true; }
Example 11
Source File: VirtualFileUtil.java From attic-polygene-java with Apache License 2.0 | 5 votes |
/** * @param element element to process. * @return The containing virtual file of the element. * @since 0.1 */ @Nullable public static VirtualFile getVirtualFile( @NotNull PsiElement element ) { if( element instanceof PsiFileSystemItem ) { PsiFileSystemItem fileSystemItem = (PsiFileSystemItem) element; return fileSystemItem.getVirtualFile(); } // If it's not a file system, assume that this is an element within a file PsiFile containingFile = element.getContainingFile(); if( containingFile == null ) { return null; } VirtualFile virtualFile = containingFile.getVirtualFile(); if( virtualFile != null ) { return virtualFile; } PsiFile originalFile = containingFile.getOriginalFile(); if( originalFile == null ) { return null; } return originalFile.getVirtualFile(); }
Example 12
Source File: ElementLocationUtil.java From consulo with Apache License 2.0 | 5 votes |
public static void customizeElementLabel(final PsiElement element, final JLabel label) { if (element != null) { PsiFile file = element.getContainingFile(); VirtualFile vfile = file == null ? null : file.getVirtualFile(); if (vfile == null) { label.setText(""); label.setIcon(null); return; } final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(element.getProject()).getFileIndex(); final Module module = fileIndex.getModuleForFile(vfile); if (module != null) { label.setText(module.getName()); label.setIcon(AllIcons.Nodes.Module); } else { final List<OrderEntry> entries = fileIndex.getOrderEntriesForFile(vfile); OrderEntry entry = null; for (OrderEntry order : entries) { if (order instanceof LibraryOrderEntry || order instanceof ModuleExtensionWithSdkOrderEntry) { entry = order; break; } } if (entry != null) { label.setText(entry.getPresentableName()); label.setIcon(AllIcons.Nodes.PpLibFolder); } } } }
Example 13
Source File: ElmMainCompletionProvider.java From elm-plugin with MIT License | 5 votes |
private static boolean isAfterLowerCaseOrWhiteSpace(PsiElement element) { if (!(element instanceof LeafPsiElement)) { return false; } int i = ((LeafPsiElement) element).getStartOffset(); PsiFile file = element.getContainingFile(); PsiElement prev = file.findElementAt(i - 1); if (!isElementOfType(prev, ElmTypes.DOT) || !(prev instanceof LeafPsiElement)) { return false; } PsiElement prevPrev = file.findElementAt(((LeafPsiElement) prev).getStartOffset() - 1); return prevPrev instanceof PsiWhiteSpace || isElementOfType(prevPrev, ElmTypes.LOWER_CASE_IDENTIFIER); }
Example 14
Source File: PropertySuppressableInspectionBase.java From eslint-plugin with MIT License | 5 votes |
public void invoke(@NotNull final Project project, final Editor editor, @NotNull final PsiElement element) throws IncorrectOperationException { final PsiFile file = element.getContainingFile(); if (!FileModificationService.getInstance().prepareFileForWrite(file)) return; @NonNls final Document doc = PsiDocumentManager.getInstance(project).getDocument(file); LOG.assertTrue(doc != null, file); // doc.insertString(0, "// eslint suppress inspection \"" + rule + "\" for whole file\n"); doc.insertString(0, "/* eslint-disable */\n"); }
Example 15
Source File: Fix.java From CppTools with Apache License 2.0 | 5 votes |
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor problemDescriptor) { final PsiElement psiElement = problemDescriptor.getPsiElement(); final PsiFile psiFile = psiElement.getContainingFile(); final Editor editor = FileEditorManager.getInstance(project).openTextEditor( new OpenFileDescriptor(project, psiFile.getVirtualFile(), psiElement.getTextOffset()), false ); try { invoke(project, editor, psiFile); } catch (IncorrectOperationException e) { Logger.getInstance(getClass().getName()).error(e); } }
Example 16
Source File: PhpBundleCompilerPassIntention.java From idea-php-symfony2-plugin with MIT License | 5 votes |
@Override public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement psiElement) { if(!Symfony2ProjectComponent.isEnabled(project)) { return false; } if(!(psiElement.getContainingFile() instanceof PhpFile)) { return false; } return PhpBundleFileFactory.getPhpClassForCreateCompilerScope(PsiTreeUtil.getParentOfType(psiElement, PhpClass.class)) != null; }
Example 17
Source File: BuildReferenceSearcher.java From intellij with Apache License 2.0 | 4 votes |
@Override public void processQuery(SearchParameters params, Processor<? super PsiReference> consumer) { PsiElement element = params.getElementToSearch(); if (element instanceof NamedBuildElement) { String fnName = ((NamedBuildElement) element).getName(); if (fnName != null) { searchForString(params, element, fnName); } return; } PsiFile file = ResolveUtil.asFileSearch(element); if (file != null) { processFileReferences(params, file); return; } if (!(element instanceof FuncallExpression)) { return; } FuncallExpression funcall = (FuncallExpression) element; PsiFile localFile = element.getContainingFile(); if (localFile == null) { return; } Label label = funcall.resolveBuildLabel(); if (label == null) { searchForExternalWorkspace(params, localFile, funcall); return; } List<String> stringsToSearch = LabelUtils.getAllValidLabelStrings(label, true); for (String string : stringsToSearch) { if (LabelUtils.isAbsolute(string)) { searchForString(params, element, string); } else { // only a valid reference from local package -- restrict the search scope accordingly SearchScope scope = limitScopeToFile(params.getScopeDeterminedByUser(), localFile); if (scope != null) { searchForString(params, scope, element, string); } } } }
Example 18
Source File: GraphQLDocumentationProvider.java From js-graphql-intellij-plugin with MIT License | 4 votes |
private boolean isDocumentationSupported(PsiElement element) { return element.getContainingFile() instanceof GraphQLFile || element.getContainingFile() instanceof JSGraphQLEndpointFile; }
Example 19
Source File: BashRunConfigProducer.java From BashSupport with Apache License 2.0 | 4 votes |
@Override protected boolean setupConfigurationFromContext(BashRunConfiguration configuration, ConfigurationContext context, Ref<PsiElement> sourceElement) { Location location = context.getLocation(); if (location == null) { return false; } PsiElement psiElement = location.getPsiElement(); if (!psiElement.isValid()) { return false; } PsiFile psiFile = psiElement.getContainingFile(); if (!(psiFile instanceof BashFile)) { return false; } sourceElement.set(psiFile); VirtualFile file = location.getVirtualFile(); if (file == null) { return false; } configuration.setName(file.getPresentableName()); configuration.setScriptName(VfsUtilCore.virtualToIoFile(file).getAbsolutePath()); if (file.getParent() != null) { configuration.setWorkingDirectory(VfsUtilCore.virtualToIoFile(file.getParent()).getAbsolutePath()); } Module module = context.getModule(); if (module != null) { configuration.setModule(module); } // check the location given by the shebang line // do this only if the project interpreter isn't used because we don't want to add the options // because it would mess up the execution when the project interpreter was used. // options might be added by a shebang like "/usr/bin/env bash". // also, we don't want to override the defaults of the template run configuration if (!configuration.isUseProjectInterpreter() && configuration.getInterpreterPath().isEmpty()) { BashFile bashFile = (BashFile) psiFile; BashShebang shebang = bashFile.findShebang(); if (shebang != null) { String shebandShell = shebang.shellCommand(false); if ((BashInterpreterDetection.instance().isSuitable(shebandShell))) { configuration.setInterpreterPath(shebandShell); configuration.setInterpreterOptions(shebang.shellCommandParams()); } } } return true; }
Example 20
Source File: ControllerRenderViewReferenceProvider.java From yiistorm with MIT License | 4 votes |
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull final ProcessingContext context) { project = element.getProject(); String elname = element.getClass().getName(); properties = PropertiesComponent.getInstance(project); VirtualFile baseDir = project.getBaseDir(); projectPath = baseDir.getCanonicalPath(); if (elname.endsWith("StringLiteralExpressionImpl")) { try { PsiFile file = element.getContainingFile(); VirtualFile vfile = file.getVirtualFile(); if (vfile != null) { String path = vfile.getPath(); String basePath = project.getBasePath(); if (basePath != null) { String themeName = properties.getValue("themeName"); Class elementClass = element.getClass(); String protectedPath = YiiRefsHelper.getCurrentProtected(path); path = path.replace(projectPath, ""); String viewPathTheme = YiiRefsHelper.getRenderViewPath(path, themeName); String viewPath = YiiRefsHelper.getRenderViewPath(path, null); protectedPath = protectedPath.replace(projectPath, "") .replaceAll("/controllers/[a-zA-Z0-9_]+?.(php|tpl)+", ""); Method method = elementClass.getMethod("getValueRange"); Object obj = method.invoke(element); TextRange textRange = (TextRange) obj; Class _PhpPsiElement = elementClass.getSuperclass().getSuperclass().getSuperclass(); Method phpPsiElementGetText = _PhpPsiElement.getMethod("getText"); Object obj2 = phpPsiElementGetText.invoke(element); String str = obj2.toString(); String uri = str.substring(textRange.getStartOffset(), textRange.getEndOffset()); int start = textRange.getStartOffset(); int len = textRange.getLength(); String controllerName = YiiRefsHelper.getControllerClassName(path); if (controllerName != null) { if (baseDir != null) { String inThemeFullPath = viewPathTheme + controllerName + "/" + uri + (uri.endsWith(".tpl") ? "" : ".php"); if (baseDir.findFileByRelativePath(inThemeFullPath) != null) { viewPath = viewPathTheme; } VirtualFile appDir = baseDir.findFileByRelativePath(viewPath); VirtualFile protectedPathDir = (!protectedPath.equals("")) ? baseDir.findFileByRelativePath(protectedPath) : null; if (appDir != null) { PsiReference ref = new ViewsReference(controllerName, uri, element, new TextRange(start, start + len), project, protectedPathDir, appDir); return new PsiReference[]{ref}; } } return PsiReference.EMPTY_ARRAY; } } } } catch (Exception e) { System.err.println("error" + e.getMessage()); } } return PsiReference.EMPTY_ARRAY; }