下面列出了怎么用com.intellij.psi.PsiFile的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
}
});
}
@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);
}
@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);
}
@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());
}
@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;
}
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);
}
}
}
}
@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");
}
@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;
}
@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);
}
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;
}
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");
}
@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);
}
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());
}
};
}
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>");
}
@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());
}
}
}
}
@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;
}
@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);
}
}
/**
* 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;
}
private static void navigateToSource(PsiFile psiFile) {
ApplicationManager.getApplication()
.invokeLater(
() -> {
PsiFile psi = refreshPsiFile(psiFile);
if (psi != null && psi.canNavigate()) {
psi.navigate(false);
}
});
}
@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;
}
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);
}
@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();
}
@Nullable
@Override
public Lexer getIndexingLexer(@NotNull PsiFile file) {
if (file instanceof BashFile) {
return BashParserDefinition.createBashLexer(file.getProject());
}
return null;
}
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;
}
@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();
}
}
@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;
}
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;
}
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));
}
}
}
@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));
}
}
@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);
}