0

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 .

Anup Ammanavar
  • 432
  • 1
  • 3
  • 16
  • What have you tried? You can add elements to a file by [modifying the psi](https://plugins.jetbrains.com/docs/intellij/modifying-psi.html), I don't think KotlinPoet adds any value here. – Abby Apr 27 '23 at 13:59
  • Got it, thanks. Was of the opinion that Kotlin poet can also parse the file and allows to edit the file. Coming to the solution of using K-PSI, How can I add a function after parsing the file? – Anup Ammanavar Apr 27 '23 at 14:19

1 Answers1

0

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.

Abby
  • 1,610
  • 3
  • 19
  • 35