com.intellij.psi.PsiElement#getContainingFile ( )源码实例Demo

下面列出了com.intellij.psi.PsiElement#getContainingFile ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: spring-javaformat   文件: SpringReformatter.java
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()));
}
 
源代码2 项目: consulo   文件: ToolsImpl.java
@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();
}
 
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);
            }
        }
    }
}
 
源代码4 项目: arma-intellij-plugin   文件: SQFStatement.java
/**
 * 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, &lt;No Statement Parent&gt; will be returned
 *
 * @return the text, or &lt;PsiComment&gt; 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", " ");
}
 
源代码5 项目: consulo-unity3d   文件: Unity3dAssetUtil.java
@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);
}
 
源代码6 项目: intellij-xquery   文件: XQueryPsiImplUtil.java
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;
}
 
源代码7 项目: BashSupport   文件: BashVarVariantsProcessor.java
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;
}
 
@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;
}
 
源代码9 项目: consulo   文件: ExternalFormatProcessor.java
/**
 * @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;
}
 
源代码10 项目: idea-php-symfony2-plugin   文件: TwigBlockUtil.java
/**
 * 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);
}
 
@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;
}
 
源代码12 项目: attic-polygene-java   文件: VirtualFileUtil.java
/**
 * @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();
}
 
源代码13 项目: CppTools   文件: Fix.java
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);
  }
}
 
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");
        }
 
源代码15 项目: elm-plugin   文件: ElmMainCompletionProvider.java
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);
}
 
源代码16 项目: consulo   文件: ElementLocationUtil.java
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);
      }
    }
  }
}
 
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;
}
 
private boolean isDocumentationSupported(PsiElement element) {
    return element.getContainingFile() instanceof GraphQLFile || element.getContainingFile() instanceof JSGraphQLEndpointFile;
}
 
源代码19 项目: intellij   文件: BuildReferenceSearcher.java
@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);
      }
    }
  }
}
 
源代码20 项目: BashSupport   文件: BashRunConfigProducer.java
@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;
}