KtScript add top level statements with linebreaks Follow
I am trying to add a new top level statement to the beginning of a kts script file by manipulating the PSI.
The file initailly looks like:
rootProject.name = "kappa"
The PSI tree initially looks like this
KtFile(rootProject.name = "kappa")
KtPackageDirective()
KtImportList()
KtScript(rootProject.name = "kappa")
KtBlockExpression(rootProject.name = "kappa")
KtScriptInitializer(rootProject.name = "kappa")
KtBinaryExpression(rootProject.name = "kappa")
KtDotQualifiedExpression(rootProject.name)
KtNameReferenceExpression(rootProject)
KtNameReferenceExpression(name)
KtOperationReferenceExpression(=)
KtStringTemplateExpression("kappa")
KtLiteralStringTemplateEntry(kappa)
I would like to add "foo()" to the beginning to the script. I have tried
val newPMBlock = ktPsiFactory.createExpression("foo()")
val script = psiFile.script?.blockExpression!!
script.addBefore(newPMBlock, script.firstChild)
script.addAfter(ktPsiFactory.createNewLine(2), newPMBlock)
But this produces
foo()rootProject.name = "kappa"
And no amount of code reformatting (CodeStyleManager.reformat) will fix it.
The desired output is
foo()
rootProject.name = "kappa"
Is there a better way of adding new top level statements to a kts script with PSI? Is there a way to do it without PSI?
Please sign in to leave a comment.
I was able to get this to work by using the return value of addBefore