Java Code Examples for com.intellij.psi.PsiFile

The following examples show how to use com.intellij.psi.PsiFile. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: consulo   Source File: MultiCaretCodeInsightAction.java    License: 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 2
@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 3
@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 4
Source Project: consulo   Source File: CodeInsightAction.java    License: 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 Project: ADB-Duang   Source File: PushAction.java    License: 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 6
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 7
Source Project: needsmoredojo   Source File: RenameRefactoringListener.java    License: 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 8
@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 9
Source Project: BashSupport   Source File: BashTemplatesFactory.java    License: 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 10
Source Project: idea-php-symfony2-plugin   Source File: RoutesStubIndex.java    License: 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 11
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 12
Source Project: intellij   Source File: ExternalWorkspaceReferenceTest.java    License: 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 13
Source Project: consulo   Source File: HighlightingSessionImpl.java    License: 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 14
Source Project: intellij   Source File: BuildDocumentationProvider.java    License: 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 15
Source Project: consulo-csharp   Source File: CSharpElementTreeNode.java    License: 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 16
Source Project: consulo   Source File: SummaryNode.java    License: 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;
}
 
Example 17
Source Project: consulo   Source File: ModuleNode.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void fillFiles(Set<PsiFile> set, boolean recursively) {
  super.fillFiles(set, recursively);
  int count = getChildCount();
  for (int i = 0; i < count; i++) {
    PackageDependenciesNode child = (PackageDependenciesNode)getChildAt(i);
    child.fillFiles(set, true);
  }
}
 
Example 18
Source Project: needsmoredojo   Source File: AMDPsiUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Determines if a file has the method in question
 * @param file
 * @param methodName
 * @param useApproximatingVisitor some dojo modules are not straight-forward. So for this case, pass true for this
 *                                and it will search a file for a property or a reference to the method name in question
 * @return
 */
public static @Nullable PsiElement fileHasMethod(PsiFile file, String methodName, boolean useApproximatingVisitor)
{
    DeclareStatementItems declareObject = new DeclareResolver().getDeclareObject(file);

    if((declareObject == null || declareObject.getMethodsToConvert() == null) && !useApproximatingVisitor)
    {
        return null;
    }

    if(declareObject != null && declareObject.getMethodsToConvert() != null)
    {
        for(JSProperty property : declareObject.getMethodsToConvert())
        {
            if(property.getName().equals(methodName))
            {
                return property;
            }
        }
    }

    if(useApproximatingVisitor)
    {
        JSMethodLookupVisitor visitor = new JSMethodLookupVisitor(methodName);
        file.acceptChildren(visitor);
        return visitor.getFoundElement();
    }

    return null;
}
 
Example 19
Source Project: intellij   Source File: BlazeAttachSourceProvider.java    License: Apache License 2.0 5 votes vote down vote up
private static void navigateToSource(PsiFile psiFile) {
  ApplicationManager.getApplication()
      .invokeLater(
          () -> {
            PsiFile psi = refreshPsiFile(psiFile);
            if (psi != null && psi.canNavigate()) {
              psi.navigate(false);
            }
          });
}
 
Example 20
Source Project: consulo   Source File: SelectionQuotingTypedHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Result beforeCharTyped(final char charTyped, final Project project, final Editor editor, final PsiFile file, final FileType fileType) {
  // TODO[oleg] remove this hack when API changes
  if (myReplacedTextRange != null) {
    if (myReplacedTextRange.getEndOffset() <= editor.getDocument().getTextLength()) {
      if (myRestoreStickySelection && editor instanceof EditorEx) {
        EditorEx editorEx = (EditorEx)editor;
        CaretModel caretModel = editorEx.getCaretModel();
        caretModel.moveToOffset(myLtrSelection ? myReplacedTextRange.getStartOffset() : myReplacedTextRange.getEndOffset());
        editorEx.setStickySelection(true);
        caretModel.moveToOffset(myLtrSelection ? myReplacedTextRange.getEndOffset() : myReplacedTextRange.getStartOffset());
      }
      else {
        if (myLtrSelection || editor instanceof EditorWindow) {
          editor.getSelectionModel().setSelection(myReplacedTextRange.getStartOffset(), myReplacedTextRange.getEndOffset());
        }
        else {
          editor.getSelectionModel().setSelection(myReplacedTextRange.getEndOffset(), myReplacedTextRange.getStartOffset());
        }
        if (Registry.is("editor.smarterSelectionQuoting")) {
          editor.getCaretModel().moveToOffset(myLtrSelection ? myReplacedTextRange.getEndOffset() : myReplacedTextRange.getStartOffset());
        }
      }
    }
    myReplacedTextRange = null;
    return Result.STOP;
  }
  return Result.CONTINUE;
}
 
Example 21
Source Project: intellij-haxe   Source File: BaseHaxeGenerateAction.java    License: Apache License 2.0 5 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 22
Source Project: consulo   Source File: ConfigureHighlightingLevel.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void setSelected(@Nonnull AnActionEvent e, boolean state) {
  if (!state) return;
  PsiFile file = provider.getPsi(language);
  if (file == null) {
    return;
  }

  FileHighlightingSetting target;

  switch (level) {
    case NONE:
      target = FileHighlightingSetting.SKIP_HIGHLIGHTING;
      break;
    case ERRORS:
      target = FileHighlightingSetting.SKIP_INSPECTION;
      break;
    case ALL:
      target = FileHighlightingSetting.FORCE_HIGHLIGHTING;
      break;
    default:
      throw new UnsupportedOperationException();
  }

  HighlightLevelUtil.forceRootHighlighting(file, target);

  InjectedLanguageManager.getInstance(file.getProject()).dropFileCaches(file);
  DaemonCodeAnalyzer.getInstance(file.getProject()).restart();
}
 
Example 23
Source Project: BashSupport   Source File: BashIndexPatternBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public Lexer getIndexingLexer(@NotNull PsiFile file) {
    if (file instanceof BashFile) {
        return BashParserDefinition.createBashLexer(file.getProject());
    }
    return null;
}
 
Example 24
Source Project: needsmoredojo   Source File: DependencyNode.java    License: Apache License 2.0 5 votes vote down vote up
public DependencyNode(PsiFile file, DependencyNode parent, String modulePath, boolean unused)
{
    nodes = new ArrayList<DependencyNode>();
    this.parent = parent;
    this.file = file;
    this.modulePath = modulePath;
    this.unused = unused;
}
 
Example 25
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
    final Project project = (Project) anActionEvent.getData(CommonDataKeys.PROJECT);

    PsiFile psiFile = anActionEvent.getData(CommonDataKeys.PSI_FILE);

    IProperty selectedProperty = getSelectedProperty(anActionEvent.getDataContext());

    final EncryptDialog form = new EncryptDialog();
    form.setTitle("Decrypt Property: " + selectedProperty.getKey());
    form.show();
    boolean isOk = form.getExitCode() == DialogWrapper.OK_EXIT_CODE;

    logger.debug("**** ALGORITHM " + form.getAlgorithm().getSelectedItem());
    logger.debug("**** MODE " + form.getMode().getSelectedItem());

    if (isOk) {
        new WriteCommandAction.Simple(project, psiFile) {
            @Override
            protected void run() throws Throwable {
                EncryptionAlgorithm algorithm = (EncryptionAlgorithm) form.getAlgorithm().getSelectedItem();
                EncryptionMode mode = (EncryptionMode) form.getMode().getSelectedItem();

                try {
                    String originalValue = selectedProperty.getValue();
                    String encryptedProperty = originalValue.substring(2, originalValue.length() - 1);

                    byte[] decryptedBytes = algorithm.getBuilder().forKey(form.getEncryptionKey().getText()).using(mode)
                            .build().decrypt(Base64.decode(encryptedProperty));

                    selectedProperty.setValue(new String(decryptedBytes));
                } catch (Exception e) {
                    Notification notification = MuleUIUtils.MULE_NOTIFICATION_GROUP.createNotification("Unable to decrypt property",
                            "Property '" + selectedProperty.getKey() + "' cannot be decrypted : " + e, NotificationType.ERROR, null);
                    Notifications.Bus.notify(notification, project);
                }
            }
        }.execute();
    }
}
 
Example 26
Source Project: consulo   Source File: FormattingDocumentModelImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
public static Document getDocumentToBeUsedFor(final PsiFile file) {
  final Project project = file.getProject();
  final Document document = PsiDocumentManager.getInstance(project).getDocument(file);
  if (document == null) return null;
  if (PsiDocumentManager.getInstance(project).isUncommited(document)) return null;
  PsiToDocumentSynchronizer synchronizer = ((PsiDocumentManagerImpl)PsiDocumentManager.getInstance(file.getProject())).getSynchronizer();
  if (synchronizer.isDocumentAffectedByTransactions(document)) return null;

  return document;
}
 
Example 27
Source Project: IntelliJDeodorant   Source File: ScopeChooserCombo.java    License: MIT License 5 votes vote down vote up
private AnalysisScope getCurrentFileScope() {
    FileEditor currentEditor = FileEditorManager.getInstance(project).getSelectedEditor();
    if (currentEditor != null) {
        VirtualFile currentFile = currentEditor.getFile();
        PsiFile file = PsiManager.getInstance(project).findFile(currentFile);
        if (file instanceof PsiJavaFile)
            return new AnalysisScope(project, Collections.singletonList(currentFile));
    }
    return null;
}
 
Example 28
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 29
Source Project: reasonml-idea-plugin   Source File: AbstractBaseIntention.java    License: 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
@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);
}