Java Code Examples for com.intellij.psi.PsiFile#getFileType()

The following examples show how to use com.intellij.psi.PsiFile#getFileType() . These examples are extracted from open source projects. 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
public static List<HaxeComponent> getItemsByName(String name, Project project, GlobalSearchScope searchScope) {
  HaxeIndexUtil.warnIfDumbMode(project);
  Collection<VirtualFile> files =
    FileBasedIndex.getInstance().getContainingFiles(HAXE_COMPONENT_INDEX, name, searchScope);
  final List<HaxeComponent> result = new ArrayList<HaxeComponent>();
  for (VirtualFile vFile : files) {
    PsiFile file = PsiManager.getInstance(project).findFile(vFile);
    if (file == null || file.getFileType() != HaxeFileType.HAXE_FILE_TYPE) {
      continue;
    }
    final HaxeComponent component = HaxeResolveUtil.findComponentDeclaration(file, name);
    if (component != null) {
      result.add(component);
    }
  }
  return result;
}
 
Example 2
@NotNull
public PsiElementVisitor buildVisitor(final @NotNull ProblemsHolder holder, boolean isOnTheFly) {
    if(!Symfony2ProjectComponent.isEnabled(holder.getProject())) {
        return super.buildVisitor(holder, isOnTheFly);
    }

    return new PsiElementVisitor() {
        @Override
        public void visitFile(PsiFile psiFile) {
            if(psiFile.getFileType() == PhpFileType.INSTANCE) {
                phpVisitor(holder, psiFile);
            } else if(psiFile.getFileType() == YAMLFileType.YML) {
                yamlVisitor(holder, psiFile);
            } else if(psiFile.getFileType() == XmlFileType.INSTANCE) {
                xmlVisitor(holder, psiFile);
            }
        }
    };
}
 
Example 3
@Override
public boolean canPutAt(@NotNull VirtualFile file, int line, @NotNull Project project)
{
    final Document document = FileDocumentManager.getInstance().getDocument(file);
    if (document != null)
    {
        final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
        if (psiFile != null)
        {
            final FileType fileType = psiFile.getFileType();
            if (fileType.equals(WeaveFileType.getInstance()))
            {
                return WeavePsiUtils.getFirstWeaveElement(project, document, line) != null;
            }
        }
    }
    return false;
}
 
Example 4
Source Project: intellij-haxe   File: HaxeSymbolIndex.java    License: Apache License 2.0 6 votes vote down vote up
public static List<HaxeComponentName> getItemsByName(@NotNull final String name,
                                                     @NotNull final Project project,
                                                     @NotNull final GlobalSearchScope searchScope) {
  HaxeIndexUtil.warnIfDumbMode(project);
  final Collection<VirtualFile> files =
    FileBasedIndex.getInstance().getContainingFiles(HAXE_SYMBOL_INDEX, name, searchScope);
  final Set<HaxeComponentName> result = new THashSet<>();
  for (VirtualFile vFile : files) {
    final PsiFile psiFile = PsiManager.getInstance(project).findFile(vFile);
    if (psiFile == null || psiFile.getFileType() != HaxeFileType.HAXE_FILE_TYPE) {
      continue;
    }
    processComponents(psiFile, subComponent -> {
      if (name.equals(subComponent.getName())) {
        result.add(subComponent.getComponentName());
      }
      return true;
    });
  }
  return new ArrayList<>(result);
}
 
Example 5
@Nullable
@RequiredReadAction
public static CSharpTypeDeclaration findTypeDeclaration(@Nonnull Editor editor, @Nonnull PsiFile file)
{
	if(file.getFileType() != CSharpFileType.INSTANCE)
	{
		return null;
	}
	final int offset = editor.getCaretModel().getOffset();
	final PsiElement elementAt = file.findElementAt(offset);
	if(elementAt == null)
	{
		return null;
	}

	PsiElement parent = elementAt.getParent();
	if(parent instanceof CSharpIdentifier)
	{
		parent = parent.getParent();
	}
	return parent instanceof CSharpTypeDeclaration ? (CSharpTypeDeclaration) parent : null;
}
 
Example 6
/**
 * We have to override {@link com.intellij.formatting.templateLanguages.TemplateLanguageFormattingModelBuilder#createModel}
 * since after we delegate to some templated languages, those languages (xml/html for sure, potentially others)
 * delegate right back to us to format the DustTypes.OUTER_TYPE token we tell them to ignore,
 * causing an stack-overflowing loop.
 */
@NotNull
public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) {

  final PsiFile file = element.getContainingFile();
  Block rootBlock;

  ASTNode node = element.getNode();

  if (node.getElementType() == DustFileViewProvider.OUTER_TYPE) {
    // If we're looking at a DustTypes.HTML element, then we've been invoked by our templated
    // language.  Make a dummy block to allow that formatter to continue
    return new SimpleTemplateLanguageFormattingModelBuilder().createModel(element, settings);
  } else {
    rootBlock = getRootBlock(file, file.getViewProvider(), settings);
  }

  return new DocumentBasedFormattingModel(rootBlock, element.getProject(), settings, file.getFileType(), file);
}
 
Example 7
@Nullable
private static Commenter findCommenter(@Nonnull Editor editor, @Nonnull PsiFile file, final int line) {
  final FileType fileType = file.getFileType();
  if (fileType instanceof AbstractFileType) {
    return ((AbstractFileType)fileType).getCommenter();
  }
  final Language lineStartLanguage = getLineStartLanguage(editor, file, line);
  final Language lineEndLanguage = getLineEndLanguage(file, editor, line);
  return CommentByBlockCommentHandler.getCommenter(file, editor, lineStartLanguage, lineEndLanguage);
}
 
Example 8
@Override
protected boolean isValidForFile(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
    if(file.getFileType() != XmlFileType.INSTANCE || !Symfony2ProjectComponent.isEnabled(project)) {
        return false;
    }

    return getMatchXmlTag(editor, file) != null;
}
 
Example 9
Source Project: consulo   File: LightStubBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Override
public StubElement buildStubTree(@Nonnull PsiFile file) {
  LighterAST tree = FORCED_AST.get();
  if (tree == null) {
    FileType fileType = file.getFileType();
    if (!(fileType instanceof LanguageFileType)) {
      LOG.error("File is not of LanguageFileType: " + file + ", " + fileType);
      return null;
    }
    if (!(file instanceof PsiFileImpl)) {
      LOG.error("Unexpected PsiFile instance: " + file + ", " + file.getClass());
      return null;
    }
    if (((PsiFileImpl)file).getElementTypeForStubBuilder() == null) {
      LOG.error("File is not of IStubFileElementType: " + file);
      return null;
    }

    FileASTNode node = file.getNode();
    tree = node.getElementType() instanceof ILightStubFileElementType ? node.getLighterAST() : new TreeBackedLighterAST(node);
  }
  else {
    FORCED_AST.set(null);
  }

  StubElement rootStub = createStubForFile(file, tree);
  buildStubTree(tree, tree.getRoot(), rootStub);
  return rootStub;
}
 
Example 10
private void maybeRecomputeEventClasses() {
  List<VirtualFile> myFilesToScan;
  synchronized (filesToScan) {
    if (filesToScan.isEmpty()) return;

    myFilesToScan = new ArrayList<VirtualFile>(filesToScan);
    filesToScan.clear();
  }

  for (VirtualFile virtualFile : myFilesToScan) {
    synchronized (fileToEventClasses) {
      getEventClasses(virtualFile).clear();
    }
    PsiFile psiFile = PsiManager.getInstance(myProject).findFile(virtualFile);
    if (psiFile == null) throw new IllegalStateException("huh? " + virtualFile);
    if (psiFile.getFileType() instanceof JavaFileType) {

      final long startTime = System.currentTimeMillis();
      psiFile.accept(new PsiRecursiveElementVisitor() {
        @Override public void visitElement(PsiElement element) {
          if (element instanceof PsiMethod
              && SubscriberMetadata.isAnnotatedWithSubscriber((PsiMethod) element)) {
            maybeAddSubscriberMethod((PsiMethod) element);
          } else {
            super.visitElement(element);
          }
        }
      });
      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format("Searched for @Subscribe in %s in %dms",
            virtualFile, System.currentTimeMillis() - startTime));
      }
    }
  }

  optimizeEventClassIndex();
}
 
Example 11
@Override
public boolean canPutAt(@NotNull VirtualFile file, int line, @NotNull Project project) {
    final Document document = FileDocumentManager.getInstance().getDocument(file);
    if (document == null) return false;
    final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
    if (psiFile == null) {
        return false;
    }
    final FileType fileType = psiFile.getFileType();
    return fileType == XQueryFileType.INSTANCE && hasAnExpression(project, document, line);
}
 
Example 12
@Override
public Result acceptChar(char c, final int prefixLength, final Lookup lookup)
{
	if(!lookup.isCompletion())
	{
		return null;
	}

	PsiFile psiFile = lookup.getPsiFile();
	if(psiFile.getFileType() != CSharpFileType.INSTANCE)
	{
		return null;
	}

	if(Character.isJavaIdentifierPart(c))
	{
		return Result.ADD_TO_PREFIX;
	}

	switch(c)
	{
		case '@':
			return Result.ADD_TO_PREFIX;
		case '{':
		case '<':
			return Result.SELECT_ITEM_AND_FINISH_LOOKUP;
		default:
			return null;
	}
}
 
Example 13
@Override
public boolean isVisible(@Nonnull Usage usage, @Nonnull UsageTarget[] targets)
{
	if(usage instanceof PsiElementUsage)
	{
		PsiFile containingFile = ((PsiElementUsage) usage).getElement().getContainingFile();
		if(containingFile != null && containingFile.getFileType() == Unity3dYMLAssetFileType.INSTANCE)
		{
			return false;
		}
	}
	return true;
}
 
Example 14
@Nullable
public static DotNetVirtualImplementOwner findVirtualImplementOwner(@Nonnull Editor editor, @Nonnull PsiFile file)
{
	if(file.getFileType() != CSharpFileType.INSTANCE)
	{
		return null;
	}
	final int offset = editor.getCaretModel().getOffset();
	final PsiElement elementAt = file.findElementAt(offset);
	if(elementAt == null)
	{
		return null;
	}
	return PsiTreeUtil.getParentOfType(elementAt, DotNetVirtualImplementOwner.class);
}
 
Example 15
@Override
@Nonnull
public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) {
  final PsiFile file = element.getContainingFile();
  Block rootBlock = getRootBlock(file, file.getViewProvider(), settings);
  return new DocumentBasedFormattingModel(rootBlock, element.getProject(), settings, file.getFileType(), file);
}
 
Example 16
Source Project: consulo   File: CodeBlockUtil.java    License: Apache License 2.0 4 votes vote down vote up
private static int calcBlockStartOffset(Editor editor, PsiFile file) {
  int offset = editor.getCaretModel().getOffset() - 1;
  if (offset < 0) return -1;

  Document document = editor.getDocument();
  final FileType fileType = file.getFileType();
  HighlighterIterator iterator = ((EditorEx)editor).getHighlighter().createIterator(offset);

  int depth = 0;
  Language braceType;
  boolean isAfterRBrace = false;
  if (isRStructuralBrace(fileType, iterator, document.getCharsSequence())) {
    isAfterRBrace = true;
    depth = -1;
    braceType = getBraceType(iterator);
  }
  else {
    braceType = null;
  }

  boolean moved = false;
  while (true) {
    if (iterator.atEnd()) return -1;

    if (isLStructuralBrace(fileType, iterator, document.getCharsSequence()) &&
        (braceType == getBraceType(iterator) || braceType == null)) {
      if (braceType == null) {
        braceType = getBraceType(iterator);
      }

      if (moved) {
        if (depth == 0) break;
        depth--;
      }
    }
    else if (isRStructuralBrace(fileType, iterator, document.getCharsSequence()) &&
             (braceType == getBraceType(iterator) || braceType == null)) {
      if (braceType == null) {
        braceType = getBraceType(iterator);
      }
      depth++;
    }

    moved = true;
    iterator.retreat();
  }

  return isAfterRBrace ? iterator.getStart() : iterator.getEnd();
}
 
Example 17
Source Project: CppTools   File: CppSupportLoader.java    License: Apache License 2.0 4 votes vote down vote up
private boolean isAcceptableDocument(Document document) {
  final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
  return psiFile != null && CPP_FILETYPE == psiFile.getFileType();
}
 
Example 18
Source Project: consulo   File: CodeBlockUtil.java    License: Apache License 2.0 4 votes vote down vote up
private static int calcBlockEndOffset(Editor editor, PsiFile file) {

    Document document = editor.getDocument();
    int offset = editor.getCaretModel().getOffset();
    final FileType fileType = file.getFileType();
    HighlighterIterator iterator = ((EditorEx)editor).getHighlighter().createIterator(offset);
    if (iterator.atEnd()) return -1;

    int depth = 0;
    Language braceType;
    boolean isBeforeLBrace = false;
    if (isLStructuralBrace(fileType, iterator, document.getCharsSequence())) {
      isBeforeLBrace = true;
      depth = -1;
      braceType = getBraceType(iterator);
    } else {
      braceType = null;
    }

    boolean moved = false;
    while (true) {
      if (iterator.atEnd()) return -1;

      if (isRStructuralBrace(fileType, iterator,document.getCharsSequence()) &&
          ( braceType == getBraceType(iterator) ||
            braceType == null
          )
          ) {
        if (moved) {
          if (depth == 0) break;
          depth--;
        }

        if (braceType == null) {
          braceType = getBraceType(iterator);
        }
      }
      else if (isLStructuralBrace(fileType, iterator,document.getCharsSequence()) &&
               ( braceType == getBraceType(iterator) ||
                 braceType == null
               )
              ) {
        if (braceType == null) {
          braceType = getBraceType(iterator);
        }
        depth++;
      }

      moved = true;
      iterator.advance();
    }

    return isBeforeLBrace? iterator.getEnd() : iterator.getStart();
  }
 
Example 19
@Nullable
@Override
public VirtualFile findClassFile(String fqcn) {
  GlobalSearchScope searchScope = module.getModuleRuntimeScope(false);

  PsiClass[] psiClasses =
      ReadAction.compute(
          () ->
              JavaPsiFacade.getInstance(project)
                  .findClasses(getContainingClassName(fqcn), searchScope));
  if (psiClasses.length == 0) {
    return null;
  }

  BlazeProjectData projectData =
      BlazeProjectDataManager.getInstance(project).getBlazeProjectData();
  if (projectData == null) {
    return null;
  }

  // It's possible that there's more than one source file in the project corresponding to
  // the same fully-qualified class name, with Blaze choosing the appropriate source to use
  // according to some configuration flags. Here we check each of them until we find the one
  // that was chosen during Blaze sync.
  for (PsiClass psiClass : psiClasses) {
    PsiFile psiFile = psiClass.getContainingFile();
    if (psiFile == null) {
      continue;
    }

    VirtualFile virtualFile = psiFile.getVirtualFile();
    if (virtualFile == null) {
      continue;
    }

    FileType fileType = psiFile.getFileType();
    VirtualFile classFile = null;

    if (fileType == StdFileTypes.JAVA) {
      classFile =
          findClassFileForSourceAndRegisterResourcePackage(projectData, virtualFile, fqcn);
    } else if (fileType == StdFileTypes.CLASS) {
      classFile = findClassFileForIJarClass(projectData, virtualFile, fqcn);
    }

    if (classFile != null) {
      return classFile;
    }
  }

  return null;
}
 
Example 20
@Override
public boolean isInContext(@Nonnull final PsiFile file, final int offset) {
  return myFileType == file.getFileType();
}