(the post below was drafted with a great deal of help from ClaudeAI - thanks in advance)
The JTE template project had an IntelliJ plugin enabling near-perfect Kotlin code editing - autocomplete, error highlighting, etc. It relied on some hacks with the opaque MultiHostInjector API, but they no longer work with changes to that API for the K2 compiler, which is now the default while K1 is deprecated ( Add support for new Kotlin K2 mode. · Issue #49 · casid/jte-intellij · GitHub ). I (no prior experience with any of the Injector APIs) am attempting to migrate to LanguageInjectionContributor/LanguageInjectionPerformer to restore the Kotlin developer experience we previously enjoyed, on the K2 compiler. The migration itself was smooth but we’ve hit a KaModule association problem that appears regardless of which injection API is used.
What we’ve tried and where each approach breaks:
MODULE_ROOT_TYPE_KEY(K1 approach): inert in K2, no effect.resolveExtensionFileModuleon theVirtualFile:getKaModule()returns the correct module, but IDE features (semantic highlighter, intentions) that analyze PSI elements from the injected file throwKaBaseIllegalPsiException: The element cannot be analyzed in the context of the current session— a session mismatch between where the PSI was created and where the analysis session was opened.ktFile.contextModule = kaModule(@KaExperimentalApi): throwsIllegalArgumentException: 'contextModule' cannot be set for code fragments— because for a non-Kotlin host file, the Kotlin injection machinery always creates aKtCodeFragmentrather than aKtFile, regardless of the"kt"extension hint passed tostartInjecting.KtCodeFragment.context: constructor-onlyval, cannot be set post-construction, so we can’t provide a context element after the platform has already created the fragment.
The core question: For a non-Kotlin host file, the platform appears to always produce a KtCodeFragment for injected Kotlin. Is there a supported K2 mechanism for associating that fragment with the correct KaModule so that IDE features can analyze its PSI elements? Or is there a way to make the platform produce a KtFile instead of a KtCodeFragment for this case?
We have a YouTrack reference KTIJ-32613 which appears related. Happy to file a new ticket if this is a known gap.