2
votes

I've created this very simple Intellij Idea plugin which folds some reference expressions. It works great for Java files but it doesn't work for Kotlin.

Here is the source: https://github.com/nodes-android/nstack-translation-folding.
I will include here the important parts:
plugin.xml

</idea-plugin>
    <depends>com.intellij.modules.all</depends>

    <application-components>
        <component>
            <implementation-class>com.nodes.folding.TranslationFoldingBuilder</implementation-class>
        </component>
    </application-components>

    <extensions defaultExtensionNs="com.intellij">
        <lang.foldingBuilder language="JAVA" implementationClass="com.nodes.folding.TranslationFoldingBuilder"/>
    </extensions>

</idea-plugin>

TranslationFoldingBuilder.kt

class TranslationFoldingBuilder : FoldingBuilderEx() {

    override fun buildFoldRegions(root: PsiElement, document: Document, quick: Boolean): Array<FoldingDescriptor> {
        if (root !is PsiJavaFile) {
            return FoldingDescriptor.EMPTY
        }

        val descriptors = ArrayList<FoldingDescriptor>()
        // Get all the reference expressions in this Java file
        val referenceExpressions = PsiTreeUtil.findChildrenOfType(root, PsiReferenceExpression::class.java)

        // Some logic

        return descriptors.toTypedArray()
    }
}

My problem is that for Kotlin files the buildFoldRegions() is not called at all.

2
Did you try to specify 'language="KOTLIN"'?Argb32
I tried. It doesn't work.vovahost

2 Answers

1
votes

Of course it will not work for kotlin ,as your

if (root !is PsiJavaFile) { return FoldingDescriptor.EMPTY }

For kotlin files, the file is org.jetbrains.kotlin.psi.KtFile instance, rather than PsiJavaFile


Update:

  1. You need to add kotlin plugin as the dependency of your plugin in plugin.xml
  2. The psi api of Kotlin is not same as Java (They are different languages). You need to write a different class (but some can be same, I just copy your origin code and edit so there is some duplicate in my kt implementation.

You can see my commit here https://github.com/aristotll/nstack-translation-folding/commit/45286e6ec10d3b50defe25d55f8fbd8f122a148b.

0
votes

In my case, adding kotlin-compiler library to the project resolved the issue with missing classes as KtFile and other related to Kotlin Psi.