下面列出了com.intellij.psi.PsiFile#getProject ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Nullable
public static RelatedItemLineMarkerInfo<PsiElement> getFileImplementsLineMarker(@NotNull PsiFile psiFile) {
final Project project = psiFile.getProject();
VirtualFile virtualFile = psiFile.getVirtualFile();
if(virtualFile == null) {
return null;
}
String bundleLocateName = FileResourceUtil.getBundleLocateName(project, virtualFile);
if(bundleLocateName == null) {
return null;
}
if(FileResourceUtil.getFileResourceRefers(project, bundleLocateName).size() == 0) {
return null;
}
NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder.create(PhpIcons.IMPLEMENTS).
setTargets(new FileResourceUtil.FileResourceNotNullLazyValue(project, bundleLocateName)).
setTooltipText("Navigate to resource");
return builder.createLineMarkerInfo(psiFile);
}
@Override
public void highlightsOutsideVisiblePartAreProduced(@Nonnull final HighlightingSession session,
@Nullable Editor editor,
@Nonnull final List<? extends HighlightInfo> infos,
@Nonnull final TextRange priorityRange,
@Nonnull final TextRange restrictedRange, final int groupId) {
final PsiFile psiFile = session.getPsiFile();
final Project project = psiFile.getProject();
final Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
if (document == null) return;
final long modificationStamp = document.getModificationStamp();
((HighlightingSessionImpl)session).applyInEDT(() -> {
if (project.isDisposed() || modificationStamp != document.getModificationStamp()) return;
EditorColorsScheme scheme = session.getColorsScheme();
UpdateHighlightersUtil
.setHighlightersOutsideRange(project, document, psiFile, infos, scheme, restrictedRange.getStartOffset(), restrictedRange.getEndOffset(), ProperTextRange.create(priorityRange), groupId);
if (editor != null) {
repaintErrorStripeAndIcon(editor, project);
}
});
}
@Nonnull
public static String getFileFqn(final PsiFile file) {
final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile == null) {
return file.getName();
}
final Project project = file.getProject();
final LogicalRoot logicalRoot = LogicalRootsManager.getLogicalRootsManager(project).findLogicalRoot(virtualFile);
if (logicalRoot != null) {
String logical = FileUtil.toSystemIndependentName(VfsUtil.virtualToIoFile(logicalRoot.getVirtualFile()).getPath());
String path = FileUtil.toSystemIndependentName(VfsUtil.virtualToIoFile(virtualFile).getPath());
return "/" + FileUtil.getRelativePath(logical, path, '/');
}
final VirtualFile contentRoot = ProjectRootManager.getInstance(project).getFileIndex().getContentRootForFile(virtualFile);
if (contentRoot != null) {
return "/" + FileUtil.getRelativePath(VfsUtil.virtualToIoFile(contentRoot), VfsUtil.virtualToIoFile(virtualFile));
}
return virtualFile.getPath();
}
private static void removeUnusedCode(PsiFile file) {
while (true) {
Collection<PsiElement> toDelete = new ArrayList<>();
Project project = file.getProject();
SearchScope scope = GlobalSearchScope.fileScope(project, file.getVirtualFile());
file.acceptChildren(new DeletionMarkingVisitor(toDelete, scope));
if (toDelete.isEmpty()) {
break;
}
WriteCommandAction.writeCommandAction(project).run(
() -> {
for (PsiElement element : toDelete) {
element.delete();
}
}
);
}
}
protected boolean supportsFileType(PsiFile file)
{
if(file == null || file.getProject() == null)
{
return false;
}
DojoSettings settings = ServiceManager.getService(file.getProject(), DojoSettings.class);
String[] fileTypes = settings.getSupportedFileTypes().split(",");
for(String type : fileTypes)
{
if(type.trim().equals(file.getVirtualFile().getExtension()))
{
return true;
}
}
return false;
}
@Override
public boolean preparePsiElementsForWrite(@Nonnull Collection<? extends PsiElement> elements) {
if (elements.isEmpty()) return true;
Set<VirtualFile> files = new THashSet<VirtualFile>();
Project project = null;
for (PsiElement element : elements) {
if (element == null) continue;
PsiFile file = element.getContainingFile();
if (file == null || !file.isPhysical()) continue;
project = file.getProject();
VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile == null) continue;
files.add(virtualFile);
}
if (!files.isEmpty()) {
VirtualFile[] virtualFiles = VfsUtilCore.toVirtualFileArray(files);
ReadonlyStatusHandler.OperationStatus status = ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(virtualFiles);
return !status.hasReadonlyFiles();
}
return true;
}
@Override
public void collectActions(@Nonnull Editor hostEditor, @Nonnull PsiFile hostFile, @Nonnull ShowIntentionsPass.IntentionsInfo intentions, int passIdToShowIntentionsFor, int offset) {
Project project = hostFile.getProject();
final PsiElement psiElement = hostFile.findElementAt(offset);
if (HighlightingLevelManager.getInstance(project).shouldInspect(hostFile)) {
PsiElement intentionElement = psiElement;
int intentionOffset = offset;
if (psiElement instanceof PsiWhiteSpace && offset == psiElement.getTextRange().getStartOffset() && offset > 0) {
final PsiElement prev = hostFile.findElementAt(offset - 1);
if (prev != null && prev.isValid()) {
intentionElement = prev;
intentionOffset = offset - 1;
}
}
if (intentionElement != null && intentionElement.getManager().isInProject(intentionElement)) {
collectIntentionsFromDoNotShowLeveledInspections(project, hostFile, intentionElement, intentionOffset, intentions);
}
}
}
public static PsiElement createEmptyCsvField(PsiFile psiFile) {
final Project project = psiFile.getProject();
final String text = "<undefined>";
final IElementType type = CsvTypes.FIELD;
final PsiManager psiManager = PsiManager.getInstance(project);
final DummyHolder dummyHolder = DummyHolderFactory.createHolder(psiManager, null);
final FileElement fileElement = dummyHolder.getTreeElement();
final FileParserDefinition parserDefinition = (FileParserDefinition) LanguageParserDefinitions.INSTANCE.forLanguage(CsvLanguage.INSTANCE);
final Lexer lexer = parserDefinition.createLexer(psiFile);
final PsiBuilder psiBuilder = PsiBuilderFactory.getInstance().createBuilder(project, fileElement, lexer, CsvLanguage.INSTANCE, text);
final ASTNode node = parserDefinition.createParser(project).parse(type, psiBuilder);
fileElement.rawAddChildren((com.intellij.psi.impl.source.tree.TreeElement) node);
return node.getPsi();
}
@Nullable
private static ExternalLintAnnotationInput collectInformation(@NotNull PsiFile psiFile, @Nullable Editor editor) {
if (psiFile.getContext() != null) {
return null;
}
VirtualFile virtualFile = psiFile.getVirtualFile();
if (virtualFile == null || !virtualFile.isInLocalFileSystem()) {
return null;
}
if (psiFile.getViewProvider() instanceof MultiplePsiFilesPerDocumentFileViewProvider) {
return null;
}
Project project = psiFile.getProject();
ESLintProjectComponent component = project.getComponent(ESLintProjectComponent.class);
if (!component.isSettingsValid() || !component.isEnabled() || !isJavaScriptFile(psiFile, component.ext)) {
return null;
}
Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
if (document == null) {
return null;
}
String fileContent = document.getText();
if (StringUtil.isEmptyOrSpaces(fileContent)) {
return null;
}
EditorColorsScheme colorsScheme = editor == null ? null : editor.getColorsScheme();
// tabSize = getTabSize(editor);
// tabSize = 4;
return new ExternalLintAnnotationInput(project, psiFile, fileContent, colorsScheme);
}
public static boolean availableFor(@Nonnull PsiFile psiFile, @Nonnull Editor editor, @Nonnull IntentionAction action) {
if (!psiFile.isValid()) return false;
try {
Project project = psiFile.getProject();
action = IntentionActionDelegate.unwrap(action);
if (action instanceof SuppressIntentionActionFromFix) {
final ThreeState shouldBeAppliedToInjectionHost = ((SuppressIntentionActionFromFix)action).isShouldBeAppliedToInjectionHost();
if (editor instanceof EditorWindow && shouldBeAppliedToInjectionHost == ThreeState.YES) {
return false;
}
if (!(editor instanceof EditorWindow) && shouldBeAppliedToInjectionHost == ThreeState.NO) {
return false;
}
}
if (action instanceof PsiElementBaseIntentionAction) {
PsiElementBaseIntentionAction psiAction = (PsiElementBaseIntentionAction)action;
if (!psiAction.checkFile(psiFile)) {
return false;
}
PsiElement leaf = psiFile.findElementAt(editor.getCaretModel().getOffset());
if (leaf == null || !psiAction.isAvailable(project, editor, leaf)) {
return false;
}
}
else if (!action.isAvailable(project, editor, psiFile)) {
return false;
}
}
catch (IndexNotReadyException e) {
return false;
}
return true;
}
/**
* Reformats the given {@link PsiFile} using {@code buildifier}, returning true if reformatting
* changed the file.
*/
public static boolean doReformat(PsiFile psiFile) {
Project project = psiFile.getProject();
return Optional.ofNullable(PsiDocumentManager.getInstance(project).getDocument(psiFile))
.map(document -> doReformat(project, document))
.orElse(false);
}
/**
* make undoable action in current document in order to Undo action work from current file
*
* @param file to make editors of to respond to undo action.
*/
public static void markPsiFileForUndo(@Nonnull final PsiFile file) {
Project project = file.getProject();
final Document document = PsiDocumentManager.getInstance(project).getDocument(file);
if (document == null) return;
CommandProcessor.getInstance().addAffectedDocuments(project, document);
}
public CustomTemplateCallback(@Nonnull Editor editor, @Nonnull PsiFile file) {
myProject = file.getProject();
myTemplateManager = TemplateManager.getInstance(myProject);
int parentEditorOffset = getOffset(editor);
PsiElement element = InjectedLanguageManager.getInstance(file.getProject()).findInjectedElementAt(file, parentEditorOffset);
myFile = element != null ? element.getContainingFile() : file;
myInInjectedFragment = InjectedLanguageManager.getInstance(myProject).isInjectedFragment(myFile);
myEditor = myInInjectedFragment ? InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(editor, file, parentEditorOffset) : editor;
myOffset = myInInjectedFragment ? getOffset(myEditor) : parentEditorOffset;
}
private static File generateSourceJar(ProgressIndicator progress, String target, String sourceJarPath, PsiFile psiFile)
throws IOException, URISyntaxException {
Project project = psiFile.getProject();
progress.setText("Getting source paths for target " + target);
List<String> sources = getSourcesForTarget(project, target);
progress.setText("Finding Pants build root");
Path buildRoot = findBuildRoot(project);
progress.setText("Preparing source jar");
Path targetPath = Paths.get(sourceJarPath);
Optional<String> packageName = findPackageName(psiFile);
try (FileSystem zipFileSystem = createZipFileSystem(targetPath)) {
for (String source : sources) {
progress.setText2("Processing " + source);
String sourceRoot = findSourceRoot(source, packageName);
Path pathInZip = zipFileSystem.getPath(source.substring(sourceRoot.length()));
Files.createDirectories(pathInZip.getParent());
Path absoluteSourcePath = buildRoot.resolve(source);
Files.copy(absoluteSourcePath, pathInZip, StandardCopyOption.REPLACE_EXISTING);
}
}
return targetPath.toFile();
}
@NotNull
private List<HaxeCompilerCompletionItem> collectCompletionsFromCompiler(@NotNull PsiFile file,
@NotNull PsiElement element,
@NotNull Editor editor,
ArrayList<String> commandLineArguments,
HaxeDebugTimeLog timeLog) {
// There is a problem here in that the current buffer may not have been saved.
// If that is the case, then the position is also incorrect, and the compiler
// doesn't have access to the correct sources. If the haxe compiler is version 3.4 or
// later, then it has the -D display-stdin parameter available and we can pump the
// unsaved buffer through to the compiler. (Though that does nothing for completion
// from related but also unsaved buffers.) Doing so will also require the compiler
// server (if used) to be started with the "--wait stdin" parameter.
if (null == file) {
// TODO: Handle in-memory files for Haxe 3.4.
advertiseError("Error: Compiler completion requested for in-memory-only file."); // TODO: Externalize string.
return HaxeCompilerCompletionItem.EMPTY_LIST;
}
Project project = file.getProject();
Module moduleForFile = ModuleUtil.findModuleForFile(file.getVirtualFile(), project);
int offset = recalculateFileOffset(file, element, editor);
// TODO: Add libraries that could be referenced.
// Source roots need to be in the classpath, too.
for (VirtualFile root : ModuleRootManager.getInstance(moduleForFile).getSourceRoots()) {
commandLineArguments.add("-cp");
commandLineArguments.add(root.getPath());
}
// Add all of the definitions, so that the compiler can see the code we are dealing with.
HaxeProjectSettings settings = HaxeProjectSettings.getInstance(project);
for (String define : settings.getUserCompilerDefinitions()) {
commandLineArguments.add("-D");
commandLineArguments.add(define);
}
// Tell the compiler we want field completion, adding the type (var or method)
commandLineArguments.add("-D");
commandLineArguments.add("display-details");
commandLineArguments.add("--display");
commandLineArguments.add(file.getVirtualFile().getPath() + "@" + Integer.toString(offset));
timeLog.stamp("Calling compiler");
List<String> stderr = new ArrayList<String>();
List<String> stdout = new ArrayList<String>();
int status = HaxeCompilerUtil.runInterruptibleCompileProcess(commandLineArguments, false,
HaxeCompilerUtil.findCompileRoot(file),
HaxeSdkUtilBase.getSdkData(moduleForFile),
stdout, stderr, timeLog);
timeLog.stamp("Compiler finished. Output found on " + (stdout.isEmpty() ? "" : "stdout ") + (stderr.isEmpty() ? "" : "stderr"));
// LOG.debug("Compiler finished. Output found on " + (stdout.isEmpty() ? "" : "stdout ") + (stderr.isEmpty() ? "" : "stderr"));
if (0 != status) {
return handleCompilerError(project, stderr);
}
return parseCompletionFromXml(project, stderr);
}
protected void addCompletions(@NotNull com.intellij.codeInsight.completion.CompletionParameters completionParameters,
ProcessingContext processingContext,
@NotNull CompletionResultSet completionResultSet) {
PsiFile currentFile = completionParameters.getPosition().getContainingFile();
Project project = currentFile.getProject();
String lang = I18NHelper.getLang(project);
PsiElement position = completionParameters.getPosition();
PsiElement list = (ParameterList) position.getParent().getParent();
PsiElement[] children = list.getChildren();
if (children.length < 2) {
return;
}
if (!children[0].toString().equals("String") || children[1] != position.getParent()) {
return;
}
String fileName = CommonHelper.rmQuotes(children[0].getFirstChild().getText());
String searchString = CommonHelper.cleanCompleterSearchString(completionParameters.getPosition().getText());
VirtualFile originalFile = currentFile.getOriginalFile().getVirtualFile();
Boolean identMatch = false;
if (originalFile != null) {
String path = CommonHelper.getFilePath(currentFile);
String protectedPath = CommonHelper.searchCurrentProtected(path);
protectedPath = CommonHelper.getRelativePath(project, protectedPath);
if (fileName.contains(".")) {
String[] result = I18NHelper.findMessageSource(fileName, protectedPath, project);
if (result != null) {
protectedPath = result[0];
fileName = result[2];
} else {
protectedPath += "/messages/" + lang;
}
} else {
protectedPath += "/messages/" + lang;
}
VirtualFile file = project.getBaseDir().findFileByRelativePath(protectedPath + "/" + fileName + ".php");
if (file == null) {
return;
}
HashMap<String, String> map = CommonHelper.parsePhpArrayConfig(project, file.getCanonicalPath());
completionResultSet.caseInsensitive();
if (map.size() > 0) {
for (String key : map.keySet()) {
if (key.equals(searchString)) {
identMatch = true;
}
completionResultSet.getPrefixMatcher().prefixMatches(key.toLowerCase());
MessageLookupElement exFL = new MessageLookupElement(key, map.get(key),
completionParameters.getPosition().getProject());
completionResultSet.addElement(exFL);
}
}
/*
AUTOCREATE NEW LINES
@FIXME: file sync bug
if (!identMatch) {
ArrayList<String> phpDoc = new ArrayList<String>();
phpDoc.add("Localization file " + lang + "/" + cleanText);
NewArrayValueLookupElement n = new NewArrayValueLookupElement(
cleanText,
path,
fileName,
completionParameters.getPosition().getProject()
);
completionResultSet.addElement(n);
completionResultSet.addElement(new IgnoredLookupElement(cleanText));
} */
}
}
@Nullable
private static TargetInfo getTargetLabel(PsiFile psiFile) {
Project project = psiFile.getProject();
BlazeProjectData projectData =
BlazeProjectDataManager.getInstance(project).getBlazeProjectData();
if (projectData == null) {
return null;
}
VirtualFile virtualFile = psiFile.getVirtualFile();
if (virtualFile == null) {
return null;
}
File file = VfsUtil.virtualToIoFile(virtualFile);
Collection<TargetKey> rulesForFile =
SourceToTargetMap.getInstance(project).getRulesForSourceFile(file);
TargetMap targetMap = projectData.getTargetMap();
List<TargetKey> libraryKeys = new ArrayList<>();
for (TargetKey key : rulesForFile) {
TargetIdeInfo target = targetMap.get(key);
if (target == null || target.getKind().getLanguageClass() != LanguageClass.GO) {
continue;
}
switch (target.getKind().getRuleType()) {
case BINARY:
return target.toTargetInfo();
case LIBRARY:
libraryKeys.add(target.getKey());
break;
case TEST:
case UNKNOWN:
// ignore these
}
}
ImmutableMultimap<TargetKey, TargetKey> rdeps = ReverseDependencyMap.get(project);
return libraryKeys.stream()
.map(rdeps::get)
.flatMap(Collection::stream)
.map(targetMap::get)
.filter(Objects::nonNull)
.filter(t -> t.getKind().getLanguageClass() == LanguageClass.GO)
.filter(t -> t.getKind().getRuleType() == RuleType.BINARY)
.map(TargetIdeInfo::toTargetInfo)
.findFirst()
.orElse(null);
}
@Override
protected void doBeforeCharDeleted(char c, PsiFile file, Editor editor) {
Project project = file.getProject();
Document document = editor.getDocument();
CharSequence charSequence = document.getImmutableCharSequence();
CaretModel caretModel = editor.getCaretModel();
int caretOffset = caretModel.getOffset();
LogicalPosition pos = caretModel.getLogicalPosition();
int lineStartOffset = document.getLineStartOffset(pos.line);
int beforeWhitespaceOffset = CharArrayUtil.shiftBackward(charSequence, caretOffset - 1, " \t") + 1;
if (beforeWhitespaceOffset != lineStartOffset) {
myReplacement = null;
return;
}
PsiDocumentManager.getInstance(project).commitDocument(document);
CodeStyleFacade codeStyleFacade = CodeStyleFacade.getInstance(project);
myReplacement = codeStyleFacade.getLineIndent(document, lineStartOffset);
if (myReplacement == null) {
return;
}
int tabSize = codeStyleFacade.getTabSize(file.getFileType());
int targetColumn = getWidth(myReplacement, tabSize);
int endOffset = CharArrayUtil.shiftForward(charSequence, caretOffset, " \t");
LogicalPosition logicalPosition = caretOffset < endOffset ? editor.offsetToLogicalPosition(endOffset) : pos;
int currentColumn = logicalPosition.column;
if (currentColumn > targetColumn) {
myStartOffset = lineStartOffset;
}
else if (logicalPosition.line == 0) {
myStartOffset = 0;
myReplacement = "";
}
else {
int prevLineEndOffset = document.getLineEndOffset(logicalPosition.line - 1);
myStartOffset = CharArrayUtil.shiftBackward(charSequence, prevLineEndOffset - 1, " \t") + 1;
if (myStartOffset != document.getLineStartOffset(logicalPosition.line - 1)) {
int spacing = CodeStyleManager.getInstance(project).getSpacing(file, endOffset);
myReplacement = StringUtil.repeatSymbol(' ', Math.max(0, spacing));
}
}
}
@Override
@Nonnull
public TextEditorHighlightingPass createHighlightingPass(@Nonnull PsiFile file, @Nonnull final Editor editor) {
return new IndentsPass(file.getProject(), editor, file);
}
public void doInsert(
@NotNull PsiFile buildFile,
@NotNull final String targetName,
@NotNull PantsTargetAddress addressToAdd
) throws IncorrectOperationException {
final PyCallExpression targetDefinitionExpression = PantsPsiUtil.findTargets(buildFile).get(targetName);
if (targetDefinitionExpression == null) {
return;
}
final Project project = buildFile.getProject();
final PyElementGenerator generator = PyElementGenerator.getInstance(project);
final String targetAddressStringToAdd = addressToAdd.toString();
final PyExpression dependenciesArgument = targetDefinitionExpression.getKeywordArgument("dependencies");
if (dependenciesArgument == null) {
final PyKeywordArgument keywordArgument =
generator.createKeywordArgument(LanguageLevel.forElement(buildFile), "dependencies", "['"+ targetAddressStringToAdd + "']");
Optional.ofNullable(targetDefinitionExpression.getArgumentList()).ifPresent(l -> l.addArgument(keywordArgument));
} else if (dependenciesArgument instanceof PyListLiteralExpression) {
PyExpression position = null;
// we assume all elements are sorted.
for (PyExpression expression : ((PyListLiteralExpression)dependenciesArgument).getElements()) {
if (expression instanceof PyStringLiteralExpression &&
targetAddressStringToAdd.compareTo(((PyStringLiteralExpression)expression).getStringValue()) < 0) {
// found a position to insert
break;
}
position = expression;
}
final PyStringLiteralExpression literalToAdd = generator.createStringLiteralAlreadyEscaped("'" + targetAddressStringToAdd + "'");
if (position != null) {
final PsiElement newLine = PsiParserFacade.SERVICE.getInstance(project).createWhiteSpaceFromText("\n");
final PsiElement addedLiteral = dependenciesArgument.addAfter(literalToAdd, position);
dependenciesArgument.getNode().addChild(newLine.getNode(), addedLiteral.getNode());
} else {
dependenciesArgument.add(literalToAdd);
}
CodeStyleManager.getInstance(project).reformat(dependenciesArgument);
}
FileDocumentManager.getInstance().saveAllDocuments(); // dump VFS to FS before refreshing
PantsUtil.refreshAllProjects(project);
}