Skip to content

Instantly share code, notes, and snippets.

@dkandalov
Created October 14, 2022 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkandalov/49f17eb3f6a2e87fdb1f2dc3d1eba609 to your computer and use it in GitHub Desktop.
Save dkandalov/49f17eb3f6a2e87fdb1f2dc3d1eba609 to your computer and use it in GitHub Desktop.
Example of ReferencerContributor added via LivePlugin (https://github.com/dkandalov/live-plugin/issues/146)
import com.intellij.openapi.extensions.DefaultPluginDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.paths.WebReference
import com.intellij.openapi.util.TextRange
import com.intellij.patterns.PlatformPatterns
import com.intellij.psi.*
import com.intellij.psi.impl.source.resolve.reference.PsiReferenceContributorEP
import com.intellij.util.ProcessingContext
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
// depends-on-plugin org.jetbrains.kotlin
val s = "github" // <- this string literal navigates to https://github.com
// Based on org.jetbrains.kotlin.idea.references.KotlinWebReferenceContributor
class ExampleContributor : PsiReferenceContributor() {
override fun registerReferenceProviders(registrar: PsiReferenceRegistrar) {
val pattern = PlatformPatterns.psiElement(KtStringTemplateExpression::class.java)
val provider = object : PsiReferenceProvider() {
override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<PsiReference> {
val expression = element as? KtStringTemplateExpression
return if (expression != null && expression.text.contains("github")) {
arrayOf(WebReference(expression, TextRange(0, expression.text.length), "https://github.com"))
} else {
PsiReference.EMPTY_ARRAY
}
}
override fun acceptsTarget(target: PsiElement) = false
}
registrar.registerReferenceProvider(pattern, provider)
}
}
val contributorEP = PsiReferenceContributorEP().also {
it.language = "kotlin"
it.implementationClass = ExampleContributor::class.java.name
it.pluginDescriptor = DefaultPluginDescriptor(PluginId.getId("LivePlugin"), ExampleContributor::class.java.classLoader)
}
PsiReferenceContributor.EP_NAME.point.registerExtension(contributorEP, pluginDisposable)
@ramon18
Copy link

ramon18 commented Apr 7, 2024

Hello,

This is giving me issues (in Rider):

error: type mismatch: inferred type is Class<KtStringTemplateExpression> but IElementType! was expected
        val pattern = PlatformPatterns.psiElement(KtStringTemplateExpression::class.java)

Sorry but I'm not involved in kotlin/java development, so this is all new to me...
Any help?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment