com.intellij.psi.PsiFile Java Examples

The following examples show how to use com.intellij.psi.PsiFile. 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: JavaClassQualifiedNameReferenceTest.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Test
public void testReferencesJavaClass() {
  PsiFile javaFile =
      workspace.createPsiFile(
          new WorkspacePath("java/com/google/bin/Main.java"),
          "package com.google.bin;",
          "public class Main {",
          "  public void main() {}",
          "}");
  PsiClass javaClass = ((PsiClassOwner) javaFile).getClasses()[0];

  BuildFile file =
      createBuildFile(
          new WorkspacePath("java/com/google/BUILD"),
          "java_binary(",
          "    name = 'binary',",
          "    main_class = 'com.google.bin.Main',",
          ")");

  ArgumentList args = file.firstChildOfClass(FuncallExpression.class).getArgList();
  assertThat(args.getKeywordArgument("main_class").getValue().getReferencedElement())
      .isEqualTo(javaClass);
}
 
Example #2
Source File: BaseHaxeGenerateAction.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
private static Pair<Editor, PsiFile> getEditorAndPsiFile(final AnActionEvent e) {
  final Project project = e.getData(PlatformDataKeys.PROJECT);
  if (project == null) return Pair.create(null, null);
  Editor editor = e.getData(PlatformDataKeys.EDITOR);
  PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE);
  return Pair.create(editor, psiFile);
}
 
Example #3
Source File: HighlightingSessionImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private HighlightingSessionImpl(@Nonnull PsiFile psiFile, @Nonnull DaemonProgressIndicator progressIndicator, EditorColorsScheme editorColorsScheme) {
  myPsiFile = psiFile;
  myProgressIndicator = progressIndicator;
  myEditorColorsScheme = editorColorsScheme;
  myProject = psiFile.getProject();
  myDocument = PsiDocumentManager.getInstance(myProject).getDocument(psiFile);
  myEDTQueue = new TransferToEDTQueue<Runnable>("Apply highlighting results", runnable -> {
    runnable.run();
    return true;
  }, o -> myProject.isDisposed() || getProgressIndicator().isCanceled()) {
    @Override
    protected void schedule(@Nonnull Runnable updateRunnable) {
      ApplicationManager.getApplication().invokeLater(updateRunnable, ModalityState.any());
    }
  };
}
 
Example #4
Source File: CodeInsightAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
@Override
public void update(@Nonnull AnActionEvent e) {
  Presentation presentation = e.getPresentation();

  Project project = e.getProject();
  if (project == null) {
    presentation.setEnabled(false);
    return;
  }

  final DataContext dataContext = e.getDataContext();
  Editor editor = getEditor(dataContext, project, true);
  if (editor == null) {
    presentation.setEnabled(false);
    return;
  }

  final PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
  if (file == null) {
    presentation.setEnabled(false);
    return;
  }

  update(presentation, project, editor, file, dataContext, e.getPlace());
}
 
Example #5
Source File: ControllerActionReferenceTest.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
public void testReferenceCanResolveDefinition() {
    PsiFile file = myFixture.configureByText(PhpFileType.INSTANCE, "<?php \n" +
            "class ActionController {" +
            "public function action() {" +
            "  $this->forward('<caret>baz');" +
            "}" +
            "}"
    );

    PsiElement elementAtCaret = file.findElementAt(myFixture.getCaretOffset()).getParent();
    PsiReference[] references = elementAtCaret.getReferences();
    for (PsiReference reference : references) {
        if (reference instanceof ControllerActionReference) {
            ResolveResult[] resolveResults = ((ControllerActionReference) reference).multiResolve(false);
            for (ResolveResult resolveResult : resolveResults) {
                assertInstanceOf(resolveResult.getElement(), Method.class);

                return;
            }
        }
    }

    fail("No TranslationReference found");
}
 
Example #6
Source File: RoutesStubIndex.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
private static boolean isValidForIndex(FileContent inputData, PsiFile psiFile) {

        String fileName = psiFile.getName();
        if(fileName.startsWith(".") || fileName.endsWith("Test")) {
            return false;
        }

        VirtualFile baseDir = ProjectUtil.getProjectDir(inputData.getProject());
        if(baseDir == null) {
            return false;
        }

        // is Test file in path name
        String relativePath = VfsUtil.getRelativePath(inputData.getFile(), baseDir, '/');
        if(relativePath != null && (relativePath.contains("/Test/") || relativePath.contains("/Fixtures/"))) {
            return false;
        }

        return true;
    }
 
Example #7
Source File: ExternalWorkspaceReferenceTest.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Test
public void testFileReferenceWithinExternalWorkspaceResolves() {
  BuildFile externalFile =
      (BuildFile)
          createFileInExternalWorkspace(
              "junit",
              new WorkspacePath("BUILD"),
              "java_import(",
              "    name = 'target',",
              "    jars = ['junit-4.11.jar'],",
              ")");
  PsiFile jarFile = createFileInExternalWorkspace("junit", new WorkspacePath("junit-4.11.jar"));
  FuncallExpression target = externalFile.findRule("target");
  StringLiteral label =
      PsiUtils.findFirstChildOfClassRecursive(
          target.getKeywordArgument("jars"), StringLiteral.class);
  assertThat(label.getReferencedElement()).isEqualTo(jarFile);
}
 
Example #8
Source File: HaxeUnresolvedSymbolInspection.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull final InspectionManager manager, final boolean isOnTheFly) {
  if (!(file instanceof HaxeFile)) return null;
  final List<ProblemDescriptor> result = new ArrayList<ProblemDescriptor>();
  new HaxeAnnotatingVisitor() {
    @Override
    protected void handleUnresolvedReference(HaxeReferenceExpression reference) {
      PsiElement nameIdentifier = reference.getReferenceNameElement();
      if (nameIdentifier == null) return;
      result.add(manager.createProblemDescriptor(
        nameIdentifier,
        TextRange.from(0, nameIdentifier.getTextLength()),
        getDisplayName(),
        ProblemHighlightType.LIKE_UNKNOWN_SYMBOL,
        isOnTheFly
      ));
    }
  }.visitFile(file);
  return ArrayUtil.toObjectArray(result, ProblemDescriptor.class);
}
 
Example #9
Source File: BuildDocumentationProvider.java    From intellij with Apache License 2.0 6 votes vote down vote up
private static void describeFile(PsiFile file, StringBuilder builder, boolean linkToFile) {
  if (!(file instanceof BuildFile)) {
    return;
  }
  BuildFile buildFile = (BuildFile) file;
  Label label = buildFile.getBuildLabel();
  String name = label != null ? label.toString() : buildFile.getPresentableText();
  if (linkToFile) {
    builder
        .append("<a href=\"")
        .append(DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL)
        .append(LINK_TYPE_FILE)
        .append("\">")
        .append(name)
        .append("</a>");
  } else {
    builder.append(String.format("<b>%s</b>", name));
  }
  builder.append("<br><br>");
}
 
Example #10
Source File: PushAction.java    From ADB-Duang with MIT License 6 votes vote down vote up
@Override
protected boolean runEnable(AnActionEvent anActionEvent) {
    Object o = anActionEvent.getDataContext().getData(DataConstants.PSI_FILE);
    if (o instanceof XmlFileImpl) {
        parentFileName = ((XmlFileImpl) o).getVirtualFile().getParent().getName();
        if (isPreference(parentFileName)) {
            return true;
        }

    } else if (o instanceof PsiFile) {
        parentFileName = ((PsiFile) o).getVirtualFile().getParent().getName();
        if (isDataBase(parentFileName)) {
            return true;
        }
    }
    return false;
}
 
Example #11
Source File: CSharpElementTreeNode.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@Override
@RequiredUIAccess
protected void updateImpl(PresentationData presentationData)
{
	DotNetNamedElement value = getValue();

	presentationData.setPresentableText(getPresentableText(value));

	if(BitUtil.isSet(myFlags, ALLOW_GRAY_FILE_NAME))
	{
		PsiFile containingFile = value.getContainingFile();
		if(containingFile != null)
		{
			if(!Comparing.equal(FileUtil.getNameWithoutExtension(containingFile.getName()), value.getName()))
			{
				presentationData.setLocationString(containingFile.getName());
			}
		}
	}
}
 
Example #12
Source File: MultiCaretCodeInsightAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void iterateOverCarets(@Nonnull final Project project,
                                      @Nonnull final Editor hostEditor,
                                      @Nonnull final MultiCaretCodeInsightActionHandler handler) {
  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  final PsiFile psiFile = documentManager.getCachedPsiFile(hostEditor.getDocument());
  documentManager.commitAllDocuments();

  hostEditor.getCaretModel().runForEachCaret(new CaretAction() {
    @Override
    public void perform(Caret caret) {
      Editor editor = hostEditor;
      if (psiFile != null) {
        Caret injectedCaret = InjectedLanguageUtil.getCaretForInjectedLanguageNoCommit(caret, psiFile);
        if (injectedCaret != null) {
          caret = injectedCaret;
          editor = caret.getEditor();
        }
      }
      final PsiFile file = PsiUtilBase.getPsiFileInEditor(caret, project);
      if (file != null) {
        handler.invoke(project, editor, caret, file);
      }
    }
  });
}
 
Example #13
Source File: DetectedIndentOptionsNotificationProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void updateIndentNotification(@Nonnull PsiFile file, boolean enforce) {
  VirtualFile vFile = file.getVirtualFile();
  if (vFile == null) return;

  if (!ApplicationManager.getApplication().isHeadlessEnvironment()
      || ApplicationManager.getApplication().isUnitTestMode() && myShowNotificationInTest)
  {
    Project project = file.getProject();
    FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
    if (fileEditorManager == null) return;
    FileEditor fileEditor = fileEditorManager.getSelectedEditor(vFile);
    if (fileEditor != null) {
      Boolean notifiedFlag = fileEditor.getUserData(NOTIFIED_FLAG);
      if (notifiedFlag == null || enforce) {
        fileEditor.putUserData(NOTIFIED_FLAG, Boolean.TRUE);
        EditorNotifications.getInstance(project).updateNotifications(vFile);
      }
    }
  }
}
 
Example #14
Source File: BashTemplatesFactory.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
@NotNull
static PsiFile createFromTemplate(final PsiDirectory directory, String fileName, String templateName) throws IncorrectOperationException {
    Project project = directory.getProject();
    FileTemplateManager templateManager = FileTemplateManager.getInstance(project);
    FileTemplate template = templateManager.getInternalTemplate(templateName);

    Properties properties = new Properties(templateManager.getDefaultProperties());

    String templateText;
    try {
        templateText = template.getText(properties);
    } catch (IOException e) {
        throw new RuntimeException("Unable to load template for " + templateManager.internalTemplateToSubject(templateName), e);
    }

    PsiFile file = PsiFileFactory.getInstance(project).createFileFromText(fileName, BashFileType.BASH_FILE_TYPE, templateText);
    return (PsiFile) directory.add(file);
}
 
Example #15
Source File: DoctrinePropertyOrmAnnotationGenerateAction.java    From idea-php-annotation-plugin with MIT License 6 votes vote down vote up
@Override
protected boolean isValidForFile(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {

    if(!(file instanceof PhpFile) || !DoctrineUtil.isDoctrineOrmInVendor(project)) {
        return false;
    }

    int offset = editor.getCaretModel().getOffset();
    if(offset <= 0) {
        return false;
    }

    PsiElement psiElement = file.findElementAt(offset);
    if(psiElement == null) {
        return false;
    }

    if(!PlatformPatterns.psiElement().inside(PhpClass.class).accepts(psiElement)) {
        return false;
    }

    return true;
}
 
Example #16
Source File: RenameRefactoringListener.java    From needsmoredojo with Apache License 2.0 6 votes vote down vote up
@Override
public void elementRenamed(@NotNull final PsiElement psiElement)
{
    final String moduleName = originalFile.substring(0, originalFile.indexOf('.'));

    CommandProcessor.getInstance().executeCommand(psiElement.getProject(), new Runnable() {
        @Override
        public void run() {
            new ModuleImporter(possibleFiles,
                    moduleName,
                    (PsiFile) psiElement,
                    new SourcesLocator().getSourceLibraries(psiElement.getProject()).toArray(new SourceLibrary[0]),
                    ServiceManager.getService(psiElement.getProject(),
                            DojoSettings.class).getNamingExceptionList())
                    .findFilesThatReferenceModule(SourcesLocator.getProjectSourceDirectories(psiElement.getProject(), true), true);
        }
    },
    "Rename Dojo Module",
    "Rename Dojo Module");
}
 
Example #17
Source File: PolyVariantTest.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
public void testPatternMatchConstant() {
    PsiFile file = parseCode("let unwrapValue = fun " +
            "  | `String(s) => toJsUnsafe(s) " +
            "  | `bool(b) => toJsUnsafe(Js.Boolean.to_js_boolean(b));");
    Collection<PsiNameIdentifierOwner> expressions = expressions(file);

    assertEquals(1, expressions.size());

    Collection<PsiPatternMatch> matches = PsiTreeUtil.findChildrenOfType(first(expressions), PsiPatternMatch.class);
    assertEquals(2, matches.size());
}
 
Example #18
Source File: CS0227.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Override
@RequiredUIAccess
public boolean isAvailable(@Nonnull Project project, Editor editor, PsiFile file)
{
	CSharpSimpleModuleExtension extension = ModuleUtilCore.getExtension(file, CSharpSimpleModuleExtension.class);
	return extension != null && !extension.isAllowUnsafeCode();
}
 
Example #19
Source File: AbstractLombokConfigSystemTestCase.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void doTest(final String beforeFileName, final String afterFileName) {
  final PsiFile psiDelombokFile = loadToPsiFile(afterFileName);
  final PsiFile psiLombokFile = loadToPsiFile(beforeFileName);

  if (!(psiLombokFile instanceof PsiJavaFile) || !(psiDelombokFile instanceof PsiJavaFile)) {
    fail("The test file type is not supported");
  }

  compareFiles((PsiJavaFile) psiLombokFile, (PsiJavaFile) psiDelombokFile);
}
 
Example #20
Source File: CreateYamlReferenceIntentionAction.java    From intellij-swagger with MIT License 5 votes vote down vote up
@Override
public void invoke(@NotNull final Project project, final Editor editor, final PsiFile psiFile) {
  final String path = StringUtils.substringAfter(referenceValueWithPrefix, "#/");

  new ReferenceCreator(path, ((YAMLFile) psiFile).getDocuments().get(0), new YamlTraversal())
      .create();
}
 
Example #21
Source File: SuppressIntentionAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public final void invoke(@Nonnull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
  if (!file.getManager().isInProject(file)) return;
  final PsiElement element = getElement(editor, file);
  if (element != null) {
    invoke(project, editor, element);
  }
}
 
Example #22
Source File: TwigUtilTempTest.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
/**
 * @see fr.adrienbrault.idea.symfony2plugin.templating.util.TwigUtil#getPresentableTemplateName
 */
public void testGetPresentableTemplateName() {
    VirtualFile res = createFile("res/foo/foo.html.twig");


    Settings.getInstance(getProject()).twigNamespaces.addAll(Collections.singletonList(
        new TwigNamespaceSetting("Foobar", "res", true, TwigUtil.NamespaceType.BUNDLE, true)
    ));

    PsiFile file = PsiManager.getInstance(getProject()).findFile(res);
    assertEquals("Foobar:foo:foo", TwigUtil.getPresentableTemplateName(file, true));
    assertEquals("Foobar:foo:foo.html.twig", TwigUtil.getPresentableTemplateName(file, false));
}
 
Example #23
Source File: LithoGenerateGroup.java    From litho with Apache License 2.0 5 votes vote down vote up
@Override
public void update(AnActionEvent e) {
  Optional<PsiFile> component =
      Optional.of(e)
          .map(event -> event.getData(CommonDataKeys.PSI_FILE))
          .filter(LithoPluginUtils::isLithoSpec);
  e.getPresentation().setEnabledAndVisible(component.isPresent());
}
 
Example #24
Source File: CmtXmlComponent.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
private void addChildren() {
    PsiFile psiFile = PsiFileFactory.getInstance(m_project).createFileFromText(XHTMLLanguage.INSTANCE, m_xmlDump);
    Document document = PsiDocumentManager.getInstance(m_project).getDocument(psiFile);
    if (document != null) {
        Editor editor = EditorFactory.getInstance().createEditor(document, m_project, HtmlFileType.INSTANCE, true);
        addToCenter(editor.getComponent());
    }
}
 
Example #25
Source File: BuildEnterHandler.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static boolean isApplicable(PsiFile file, DataContext dataContext) {
  if (!(file instanceof BuildFile)) {
    return false;
  }
  Boolean isSplitLine =
      DataManager.getInstance().loadFromDataContext(dataContext, SplitLineAction.SPLIT_LINE_KEY);
  if (isSplitLine != null) {
    return false;
  }
  return true;
}
 
Example #26
Source File: FlutterTestLocationProvider.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nullable
@Override
protected Location<PsiElement> getLocationByLineAndColumn(@NotNull PsiFile file, int line, int column) {
  try {
    return super.getLocationByLineAndColumn(file, line, column);
  }
  catch (IndexOutOfBoundsException e) {
    // Line and column info can be wrong, in which case we fall-back on test and group name for test discovery.
  }

  return null;
}
 
Example #27
Source File: ANTLRv4ExternalAnnotator.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void annotateIssue(@NotNull PsiFile file, @NotNull AnnotationHolder holder, GrammarIssue issue) {
	for ( Token t : issue.getOffendingTokens() ) {
		if ( t instanceof CommonToken && tokenBelongsToFile(t, file) ) {
			TextRange range = getTokenRange((CommonToken) t, file);
			ErrorSeverity severity = getIssueSeverity(issue);

			Optional<Annotation> annotation = annotate(holder, issue, range, severity);
			annotation.ifPresent(a -> registerFixForAnnotation(a, issue, file));
		}
	}
}
 
Example #28
Source File: CSharpFormattingModelBuilder.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public FormattingModel createModel(PsiElement element, CodeStyleSettings settings)
{
	final PsiFile file = element.getContainingFile();
	FormattingDocumentModelImpl model = FormattingDocumentModelImpl.createOn(element.getContainingFile());
	Block rootBlock = new CSharpFormattingBlock(file.getNode(), null, null, settings);
	return new PsiBasedFormattingModel(file, rootBlock, model);
}
 
Example #29
Source File: AbstractBaseIntention.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
@Override
public void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) throws IncorrectOperationException {
    if (!FileModificationService.getInstance().prepareFileForWrite(file)) {
        return;
    }

    PsiDocumentManager.getInstance(project).commitAllDocuments();
    T parentAtCaret = getParentAtCaret(editor, file);
    if (parentAtCaret != null) {
        ApplicationManager.getApplication().runWriteAction(() -> runInvoke(project, parentAtCaret));
    }
}
 
Example #30
Source File: SummaryNode.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public int getFileCount(ToDoSummary summary) {
  int count = 0;
  for (Iterator i = myBuilder.getAllFiles(); i.hasNext(); ) {
    PsiFile psiFile = (PsiFile)i.next();
    if (psiFile == null) { // skip invalid PSI files
      continue;
    }
    if (getTreeStructure().accept(psiFile)) {
      count++;
    }
  }
  return count;
}