Cleanest way to insert Java/KDoc above the method or class


I'm developing a plugin, that is capable of creating KDoc/Javadoc comments for given methods and classes, that supports both Java/Kotlin. The tricky part is that as far as I got there is no clean way to support such a technique using the UAST library only, so I'm operating around `PsiElements`, to be able to use the `.addBefore` method. It looks like that:

private fun insertDocumentation(element: PsiElement, documentation: String) {
val factory = JavaPsiFacade.getElementFactory(element.project)
val documentationElement = factory.createDocCommentFromText(documentation, element)

WriteCommandAction.runWriteCommandAction(element.project) {
// Distinguish between class elements and others to correctly position the documentation.
val createdDoc = if (element is PsiClass) {
element.addBefore(documentationElement, element.firstChild)
} else {
element.parent.addBefore(documentationElement, element)

// Formatting the code after adding the documentation.

And it works perfectly with java classes, but for some reason, it's unable to correctly insert a comment for kotlin classes, that perform like this (end of KDoc and class declaration is on the same line, and not being reformated afterall!):

* A class representing a calculator that can perform basic arithmetic operations.
*/class Calculator {

Whitespace insertion is not recommended, there is no way to execute ::addBefore on UElement, is there any clean way to paste a kotlin documentation for a class?

1 comment

Please clarify, are you using above snippet to as well for Kotlin? That won’t work.
Unfortunately, there is currently no support in org.jetbrains.uast.generate.UastCodeGenerationPlugin for UAST-based doc comment manipulation.

​Please see also related API com.intellij.codeInsight.editorActions.FixDocCommentAction#generateOrFixComment, `com.siyeh.ig.psiutils.CommentTracker` and `org.jetbrains.kotlin.idea.util.CommentSaver` (Kotlin plugin) for pointers.

Please sign in to leave a comment.