Anup Ammanavar
Anup Ammanavar

Reputation: 432

IntelliJ IDEA Plugin - How to modify the contents of an existing file using Kotlin poet

I'm writing an Intellij Plugin. I want to retrieve a file from the project and add a new function to the class using Kotlin poet .

Upvotes: 0

Views: 469

Answers (1)

Abby
Abby

Reputation: 1846

First of, you will need an anchor PsiElement in your psi file. This can probably be a method that comes before the method you want to insert. Finding an anchor element consistently can be tricky and depends on your context. As I'm not familiar with the psi structure of Kotlin files, I'll leave this up to you. I'll assume that you have an element called psiElement.

Then you have to create your new element. You can create a PsiFile using the PsiFileFactory, and then extract the psi element you need. I often like to create a helper class with utility methods that can extract the right kind of psi elements for me, I imagine for your case it could similar to the following. (Once again, I'm not familiar with the Kotlin psi structure, so this is just a gist to give you an idea.)

class KotlinPsiHelper(private val project: Project) {
    fun createFromText(text: String): PsiFile = PsiFileFactory.getInstance(project)
            .createFileFromText("DUMMY.kt", KotlinLanguage.INSTANCE, text, false, true)

    fun PsiFile.extractMethod(): KtFunction? = this.childrenOfType<KtFunction>()
            .firstOrNull()
}

You can then use this to create a new element and add it after psiElement.

val psiHelper = KotlinPsiHelper(project)
val newElement = psiHelper.createFromText("""
    fun bloop(): String {
        return "bleep"
    }
""".trimIndent())
    .extractMethod() ?: return

psiElement.parent.addAfter(psiElement, newElement)

Note that there are multiple ways to insert newElement with respect to psiElement, it will depend on the structure of your file what works best.


Feel free to have a look at LatexPsiHelper to see an example of such a helper class and how it's used.

Upvotes: 0

Related Questions