Inject language reference question

I don’t suppose there’s a way to annotate a string parameter as wanting a default language injection?

I know I can comment a string before the literal, but I think it would be useful to be able to declare a string parameter as having a default language.

Example:

fun html(
  @Language("html")
  str: String
) {
  ...
}

fun main() {
  html("""<p>Hello</p>""") // No need for //language=html
}

Looking at Language injections | IntelliJ IDEA it seems like there might be a way with Kotlin JVM, but not Kotlin JS, is that true?

You can annotate parameters and then use those annotations in libraries that rely on reflection or in IDEA inspections. There are no principal problems with that. You just need to write those libraries and inspections.

2 Likes

Just create an annotation with appropriate signature and use it, IDEA does not care from which exact artifact it came from:

package org.intellij.lang.annotations

@Retention(AnnotationRetention.BINARY)
annotation class Language(
    val value: String,
    val prefix: String = "",
    val suffix: String = ""
)

It’s not the annotation or reflection that I care about in this case, it’s the syntax highlighting that you’d get from adding //language=html before the literal.

Your example will work with manually declared @Language annotation on every platform, including Kotlin JS

2 Likes

Oh beautiful. That worked like a charm, thanks.

One thing to note for posterity is that the package is important :slight_smile:

Is there a way to create a shorthand for:

@Language("CSS", prefix = "{ --prop: ", suffix = "; }")

Ideally I’d like to have an annotation CssProp that has those defaults.

However, it doesn’t seem like you can extend an annotation in kotlin like you can in java

I guess it’s not possible this way, but you can define specific injections in IntelliJ:

  1. Define your custom annotation:
package some.package
annotation class CssProp
  1. Go to Settings > Editor > Language Injections and add new injection of type Generic Kotlin.
  2. Configure your language, prefix, suffix
  3. In Places Patterns put
+ kotlinParameter().withAnnotation("some.package.CssProp")
  1. Enjoy injected language in annotated parameters :wink:
  2. Additionally you can change scope from IDE to Project with one of the buttons in right toolbar. If you do, .idea/IntelliLang.xml file will be created in your project, so that you can share it with others, e.g. by putting it in repository

And one more clarification for earlier mentioned user defined @Language annotation.
In fact you can use annotation with custom name, placed in custom package - you just need to set it in Settings > Editor > Language Injections > Advanced > Language annotation class, where org.intellij.lang.annotations.Language happens to be default value.

1 Like