Add a PsiElement without adding text to the PsiFile
Answered
I'm trying to add a method (PsiMethod) to a class (PsiClass) so that IDEA shows this method when typing. I did this, but I ran into a problem: when I add PsiMethod to PsiClass, the text of this method appears in the file, and I don't need it. I need to add a method so that it is highlighted by IDEA, but it is not displayed in the file as text.
How can this be done?
Here is my code how I add PsiMethod to PsiClass:
val module = ModuleManager.getInstance(project).modules.first()
val file = FilenameIndex
.getFilesByName(
project,
"TestPsiFile.java",
module.moduleContentScope)
.first()
val newMethod = PsiElementFactory.getInstance(project).createMethod("testMethod", PsiType.VOID)
WriteCommandAction.runWriteCommandAction(project) {
file.children
.filter { it.elementType == JavaElementType.CLASS }
.map { it.add(newMethod) }
}
Please sign in to leave a comment.
Use com.intellij.psi.augment.PsiAugmentProvider extension to add "fake" elements in Java
Thanks for the answer, but could you tell me how to use PsiAugmentProvider?
I tried to figure it out, but I ran into a problem.
Here's what I did:
class TestPsiAugmentProvider : PsiAugmentProvider() {
override fun <Psi : PsiElement?> getAugments(
element: PsiElement,
type: Class<Psi>,
nameHint: String?
): MutableList<Psi> {
if (element.containingFile.name == "TestPsiFile.java" && element.elementType == JavaElementType.CLASS && type.name == "com.intellij.psi.PsiClass") {
val method = LightMethodBuilder(element.manager, JavaLanguage.INSTANCE, "testMethod").apply {
containingClass = element as PsiClass
setMethodReturnType(PsiType.VOID)
setModifiers("public")
}
return mutableListOf(method as Psi) //So far, I'm only returning a new method for the test
}
return super.getAugments(element, type, nameHint)
}
}
When I test the plugin, IDEA does not highlight the testMethod method in red, but it also does not suggest this method when I type. What could be the problem?
Completion should be supported. see com.intellij.java.codeInsight.completion.NormalCompletionTest#"test member as Java keyword"