下面列出了com.intellij.psi.PsiFile#getUserData ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@NotNull
private static Map<String, List<PsiFile>> doGetModuleMap(@NotNull Project project) {
Map<String, List<PsiFile>> map = new HashMap<>();
for (PsiFile psiFile : findModuleFiles(project)) {
if (psiFile.getUserData(MODULE_NAME_DATA_KEY) != null) {
map.put(psiFile.getUserData(MODULE_NAME_DATA_KEY), Collections.singletonList(psiFile));
continue;
}
String name = calculateModuleName(psiFile);
if (name != null) {
psiFile.putUserData(MODULE_NAME_DATA_KEY, name);
map.put(name, Collections.singletonList(psiFile));
}
}
return map;
}
private synchronized Collection<FluidNamespace> doProvide(@NotNull PsiElement element) {
FileViewProvider viewProvider = element.getContainingFile().getViewProvider();
if (!viewProvider.getLanguages().contains(HTMLLanguage.INSTANCE)) {
return ContainerUtil.emptyList();
}
PsiFile htmlFile = viewProvider.getPsi(HTMLLanguage.INSTANCE);
CachedValue userData = htmlFile.getUserData(HTML_NS_KEY);
if (userData != null) {
return (Collection<FluidNamespace>) userData.getValue();
}
CachedValue<Collection<FluidNamespace>> cachedValue = CachedValuesManager.getManager(element.getProject()).createCachedValue(() -> {
HtmlNSVisitor visitor = new HtmlNSVisitor();
htmlFile.accept(visitor);
return CachedValueProvider.Result.createSingleDependency(visitor.namespaces, htmlFile);
}, false);
htmlFile.putUserData(HTML_NS_KEY, cachedValue);
return cachedValue.getValue();
}
public static void openSourceLocation(Project myProject, SourceLocation location, boolean resolveSDLFromJSON) {
VirtualFile sourceFile = StandardFileSystems.local().findFileByPath(location.getSourceName());
if (sourceFile != null) {
PsiFile file = PsiManager.getInstance(myProject).findFile(sourceFile);
if (file != null) {
if (file instanceof JsonFile && resolveSDLFromJSON) {
GraphQLFile graphQLFile = file.getUserData(GraphQLSchemaKeys.GRAPHQL_INTROSPECTION_JSON_TO_SDL);
if (graphQLFile != null) {
// open the SDL file and not the JSON introspection file it was based on
file = graphQLFile;
sourceFile = file.getVirtualFile();
}
}
new OpenFileDescriptor(myProject, sourceFile, location.getLine() - 1, location.getColumn() - 1).navigate(true);
}
}
}
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) {
PsiFile checkedFile = BashPsiUtils.findFileContext(file);
if (checkedFile instanceof BashFile && !BashPsiUtils.isInjectedElement(file)
&& !isSpecialBashFile(checkedFile.getName())) {
BashFile bashFile = (BashFile) checkedFile;
Boolean isLanguageConsole = checkedFile.getUserData(BashFile.LANGUAGE_CONSOLE_MARKER);
if ((isLanguageConsole == null || !isLanguageConsole) && !bashFile.hasShebangLine()) {
return new ProblemDescriptor[]{
manager.createProblemDescriptor(checkedFile, "Add shebang line", new AddShebangQuickfix(), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly)
};
}
}
return null;
}
public static void queryForSelectedTextEditor(@NotNull Project project) {
try {
Editor selectedTextEditor = FileEditorManager.getInstance(project).getSelectedTextEditor();
if (selectedTextEditor != null) {
Document document = selectedTextEditor.getDocument();
PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
if (psiFile instanceof FileBase && !FileHelper.isInterface(psiFile.getFileType())) {
// Try to get the inferred types cached at the psi file user data
VirtualFile sourceFile = psiFile.getVirtualFile();
Application application = ApplicationManager.getApplication();
SignatureProvider.InferredTypesWithLines sigContext = psiFile.getUserData(SignatureProvider.SIGNATURE_CONTEXT);
InferredTypes signatures = sigContext == null ? null : sigContext.getTypes();
if (signatures == null) {
FileType fileType = sourceFile.getFileType();
if (FileHelper.isCompilable(fileType)) {
InsightManager insightManager = ServiceManager.getService(project, InsightManager.class);
if (!DumbService.isDumb(project)) {
LOG.debug("Reading types from file", psiFile);
PsiFile cmtFile = findCmtFileFromSource(project, sourceFile.getNameWithoutExtension());
if (cmtFile != null) {
Path cmtPath = FileSystems.getDefault().getPath(cmtFile.getVirtualFile().getPath());
insightManager.queryTypes(sourceFile, cmtPath, types -> application
.runReadAction(() -> annotatePsiFile(project, psiFile.getLanguage(), sourceFile, types)));
}
}
}
} else {
LOG.debug("Signatures found in user data cache");
application.runReadAction(() -> annotatePsiFile(project, psiFile.getLanguage(), sourceFile, signatures));
}
}
}
} catch (Error e) {
// might produce an AssertionError when project is being disposed, but the invokeLater still process that code
}
}
@Nullable
private String getInferredSignature(@NotNull PsiElement element, @NotNull PsiFile psiFile, @NotNull Language language) {
SignatureProvider.InferredTypesWithLines signaturesContext = psiFile.getUserData(SignatureProvider.SIGNATURE_CONTEXT);
if (signaturesContext != null) {
ORSignature elementSignature = signaturesContext.getSignatureByOffset(element.getTextOffset());
if (elementSignature != null) {
return elementSignature.asString(language);
}
}
return null;
}
public static void initState(ErrorState state, PsiBuilder builder, IElementType root, TokenSet[] extendsSets) {
state.extendsSets = extendsSets;
PsiFile file = builder.getUserDataUnprotected(FileContextUtil.CONTAINING_FILE_KEY);
state.completionState = file == null? null: file.getUserData(COMPLETION_STATE_KEY);
Language language = file == null? root.getLanguage() : file.getLanguage();
state.caseSensitive = language.isCaseSensitive();
PairedBraceMatcher matcher = LanguageBraceMatching.INSTANCE.forLanguage(language);
state.braces = matcher == null ? null : matcher.getPairs();
if (state.braces != null && state.braces.length == 0) state.braces = null;
}
@Nonnull
@RequiredReadAction
public static Set<String> getStableDefines(@Nonnull PsiFile psi)
{
FileViewProvider viewProvider = psi.getViewProvider();
VirtualFile virtualFile = viewProvider.getVirtualFile();
if(virtualFile instanceof LightVirtualFile)
{
virtualFile = ((LightVirtualFile) virtualFile).getOriginalFile();
// we need call second time, due second original file will be light
if(virtualFile instanceof LightVirtualFile)
{
virtualFile = ((LightVirtualFile) virtualFile).getOriginalFile();
}
}
if(virtualFile == null)
{
virtualFile = psi.getUserData(IndexingDataKeys.VIRTUAL_FILE);
}
Set<String> defVariables = Collections.emptySet();
if(virtualFile != null)
{
List<String> variables = findVariables(virtualFile, psi.getProject());
if(variables != null)
{
defVariables = new HashSet<>(variables);
}
}
return defVariables;
}
@Nullable
static public HaxeFileModel fromElement(PsiElement element) {
if (element == null) return null;
final PsiFile file = element instanceof PsiFile ? (PsiFile)element : element.getContainingFile();
if (file instanceof HaxeFile) {
HaxeFileModel model = file.getUserData(HAXE_FILE_MODEL_KEY);
if (model == null) {
model = new HaxeFileModel((HaxeFile)file);
file.putUserData(HAXE_FILE_MODEL_KEY, model);
}
return model;
}
return null;
}
public static void initState(ErrorState state, PsiBuilder builder, IElementType root, TokenSet[] extendsSets) {
state.extendsSets = extendsSets;
PsiFile file = builder.getUserDataUnprotected(FileContextUtil.CONTAINING_FILE_KEY);
state.completionState = file == null? null: file.getUserData(COMPLETION_STATE_KEY);
Language language = file == null? root.getLanguage() : file.getLanguage();
state.caseSensitive = language.isCaseSensitive();
PairedBraceMatcher matcher = LanguageBraceMatching.INSTANCE.forLanguage(language);
state.braces = matcher == null ? null : matcher.getPairs();
if (state.braces != null && state.braces.length == 0) state.braces = null;
}
private void checkTreeDepth(final int maxDepth, final boolean isFileRoot) {
if (myFile == null) return;
final PsiFile file = myFile.getOriginalFile();
final Boolean flag = file.getUserData(BlockSupport.TREE_DEPTH_LIMIT_EXCEEDED);
if (maxDepth > BlockSupport.INCREMENTAL_REPARSE_DEPTH_LIMIT) {
if (!Boolean.TRUE.equals(flag)) {
file.putUserData(BlockSupport.TREE_DEPTH_LIMIT_EXCEEDED, Boolean.TRUE);
}
}
else if (isFileRoot && flag != null) {
file.putUserData(BlockSupport.TREE_DEPTH_LIMIT_EXCEEDED, null);
}
}
@Override
@Nonnull
public List<TextRange> getChangedTextRanges(@Nonnull Project project, @Nonnull PsiFile file) throws FilesTooBigForDiffException {
Document document = PsiDocumentManager.getInstance(project).getDocument(file);
if (document == null) return ContainerUtil.emptyList();
List<TextRange> cachedChangedLines = getCachedChangedLines(project, document);
if (cachedChangedLines != null) {
return cachedChangedLines;
}
if (ApplicationManager.getApplication().isUnitTestMode()) {
CharSequence testContent = file.getUserData(TEST_REVISION_CONTENT);
if (testContent != null) {
return calculateChangedTextRanges(document, testContent);
}
}
Change change = ChangeListManager.getInstance(project).getChange(file.getVirtualFile());
if (change == null) {
return ContainerUtilRt.emptyList();
}
if (change.getType() == Change.Type.NEW) {
return ContainerUtil.newArrayList(file.getTextRange());
}
String contentFromVcs = getRevisionedContentFrom(change);
return contentFromVcs != null ? calculateChangedTextRanges(document, contentFromVcs)
: ContainerUtil.<TextRange>emptyList();
}
public static void initState(ErrorState state, PsiBuilder builder, IElementType root, TokenSet[] extendsSets) {
state.extendsSets = extendsSets;
PsiFile file = builder.getUserData(FileContextUtil.CONTAINING_FILE_KEY);
state.completionState = file == null? null: file.getUserData(COMPLETION_STATE_KEY);
Language language = file == null? root.getLanguage() : file.getLanguage();
state.caseSensitive = language.isCaseSensitive();
PairedBraceMatcher matcher = LanguageBraceMatching.INSTANCE.forLanguage(language);
state.braces = matcher == null ? null : matcher.getPairs();
if (state.braces != null && state.braces.length == 0) state.braces = null;
}
@Nullable
public static TextCompletionProvider getProvider(@Nonnull PsiFile file) {
TextCompletionProvider provider = file.getUserData(COMPLETING_TEXT_FIELD_KEY);
if (provider == null || (DumbService.isDumb(file.getProject()) && !DumbService.isDumbAware(provider))) {
return null;
}
return provider;
}
@RequiredReadAction
@Override
public void fillCompletionVariants(CompletionParameters parameters, CompletionResultSet result) {
PsiFile file = parameters.getOriginalFile();
if (!(file instanceof PsiPlainTextFile)) return;
TextFieldCompletionProvider field = file.getUserData(TextFieldCompletionProvider.COMPLETING_TEXT_FIELD_KEY);
if (field == null) return;
if (!(field instanceof DumbAware) && DumbService.isDumb(file.getProject())) return;
String text = file.getText();
int offset = Math.min(text.length(), parameters.getOffset());
String prefix = field.getPrefix(text.substring(0, offset));
CompletionResultSet activeResult;
if (!result.getPrefixMatcher().getPrefix().equals(prefix)) {
activeResult = result.withPrefixMatcher(prefix);
}
else {
activeResult = result;
}
if (field.isCaseInsensitivity()) {
activeResult = activeResult.caseInsensitive();
}
field.addCompletionVariants(text, offset, prefix, activeResult);
}
private static void initState(IElementType root, PsiBuilder builder, ErrorState state) {
PsiFile file = builder.getUserDataUnprotected(FileContextUtil.CONTAINING_FILE_KEY);
state.completionState = file == null? null: file.getUserData(COMPLETION_STATE_KEY);
Language language = file == null? root.getLanguage() : file.getLanguage();
state.caseSensitive = language.isCaseSensitive();
ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(language);
if (parserDefinition != null) {
state.commentTokens = parserDefinition.getCommentTokens();
state.whitespaceTokens = parserDefinition.getWhitespaceTokens();
}
PairedBraceMatcher matcher = LanguageBraceMatching.INSTANCE.forLanguage(language);
state.braces = matcher == null ? null : matcher.getPairs();
if (state.braces != null && state.braces.length == 0) state.braces = null;
}
public static HighlightCommand getUpToDateHighlightCommand(PsiFile psiFile, Project project) {
HighlightCommand command = psiFile.getUserData(ourCurrentHighlightingCommandKey);
if (command == null || !command.isUpToDate() || command.isFailedOrCancelled()) {
command = new HighlightCommand(psiFile);
psiFile.putUserData(ourCurrentHighlightingCommandKey, command);
command.nonblockingPost(project);
}
return command;
}
@Nullable
public static PsiElement getFileContext(@Nonnull PsiFile file) {
SmartPsiElementPointer pointer = file.getUserData(INJECTED_IN_ELEMENT);
return pointer == null ? null : pointer.getElement();
}
static boolean isFirstTime(PsiFile file, Editor editor, Key<Boolean> key) {
return file.getUserData(key) == null || editor.getUserData(key) == null;
}
@RequiredReadAction
@Override
public void fillCompletionVariants(final CompletionParameters parameters, CompletionResultSet result) {
PsiFile file = parameters.getOriginalFile();
final TextFieldWithAutoCompletionListProvider<T> provider = file.getUserData(KEY);
if (provider == null) {
return;
}
String adv = provider.getAdvertisement();
if (adv == null) {
final String shortcut = getActionShortcut(IdeActions.ACTION_QUICK_JAVADOC);
if (shortcut != null) {
adv = provider.getQuickDocHotKeyAdvertisement(shortcut);
}
}
if (adv != null) {
result.addLookupAdvertisement(adv);
}
final String prefix = provider.getPrefix(parameters);
if (prefix == null) {
return;
}
if (parameters.getInvocationCount() == 0 && !file.getUserData(AUTO_POPUP_KEY)) { // is autopopup
return;
}
final PrefixMatcher prefixMatcher = provider.createPrefixMatcher(prefix);
if (prefixMatcher != null) {
result = result.withPrefixMatcher(prefixMatcher);
}
Collection<T> items = provider.getItems(prefix, true, parameters);
addCompletionElements(result, provider, items, -10000);
Future<Collection<T>>
future =
ApplicationManager.getApplication().executeOnPooledThread(new Callable<Collection<T>>() {
@Override
public Collection<T> call() {
return provider.getItems(prefix, false, parameters);
}
});
while (true) {
try {
Collection<T> tasks = future.get(100, TimeUnit.MILLISECONDS);
if (tasks != null) {
addCompletionElements(result, provider, tasks, 0);
return;
}
}
catch (ProcessCanceledException e) {
throw e;
}
catch (Exception ignore) {
}
ProgressManager.checkCanceled();
}
}