Java Code Examples for com.intellij.psi.PsiFile#getUserData()

The following examples show how to use com.intellij.psi.PsiFile#getUserData() . 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: JavaScriptUtil.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
@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;
}
 
Example 2
Source File: HtmlNSNamespaceProvider.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
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();
}
 
Example 3
Source File: GraphQLTreeNodeNavigationUtil.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
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);
        }
    }
}
 
Example 4
Source File: AddShebangInspection.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 5
Source File: PsiBuilderImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 6
Source File: HighlightUtils.java    From CppTools with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 7
Source File: GeneratedParserUtilBase.java    From Intellij-Dust with MIT License 5 votes vote down vote up
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;
}
 
Example 8
Source File: CompletionContributorForTextField.java    From consulo with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 9
Source File: TextCompletionUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 10
Source File: GeneratedParserUtilBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 11
Source File: VcsAwareFormatChangedTextUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 12
Source File: InferredTypesService.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
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
    }
}
 
Example 13
Source File: GeneratedParserUtilBase.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 14
Source File: HaxeFileModel.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 15
Source File: CSharpFileStubElementType.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 16
Source File: GeneratedParserUtilBase.java    From intellij-latte with MIT License 5 votes vote down vote up
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;
}
 
Example 17
Source File: DocumentationProvider.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
@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;
}
 
Example 18
Source File: FileContextUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nullable
public static PsiElement getFileContext(@Nonnull PsiFile file) {
  SmartPsiElementPointer pointer = file.getUserData(INJECTED_IN_ELEMENT);
  return pointer == null ? null : pointer.getElement();
}
 
Example 19
Source File: CodeFoldingPass.java    From consulo with Apache License 2.0 4 votes vote down vote up
static boolean isFirstTime(PsiFile file, Editor editor, Key<Boolean> key) {
  return file.getUserData(key) == null || editor.getUserData(key) == null;
}
 
Example 20
Source File: TextFieldWithAutoCompletionContributor.java    From consulo with Apache License 2.0 4 votes vote down vote up
@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();
  }
}