Skip to content

Instantly share code, notes, and snippets.

@bentonmize
Created August 16, 2024 14:36
Show Gist options
  • Save bentonmize/1f8065fc54a1b46120ff6f335f4ed015 to your computer and use it in GitHub Desktop.
Save bentonmize/1f8065fc54a1b46120ff6f335f4ed015 to your computer and use it in GitHub Desktop.
LivePlugin basic hello replacement
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.util.elementType
import liveplugin.registerInspection
import liveplugin.show
// depends-on-plugin com.intellij.java
registerInspection(HelloWorldInspection())
if (!isIdeStartup) {
show("Loaded hello world inspection!<br/>It replaces \"hello\" string literal in Python code with \"Howdy do!\"")
}
class HelloWorldInspection: LocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object: PsiElementVisitor() {
override fun visitElement(element: PsiElement) {
super.visitElement(element)
if(element.text.contains("hello")) {
if(element.containingFile.toString().contains("PyFile")) {
if(element.elementType.toString().contains("STRING_LITERAL_EXPRESSION")) {
// show(element.elementType)
// for( c in element.children) {
// show(c.elementType)
// }
holder.registerProblem(element, "Found hello!", HelloWorldQuickFix())
}
}
}
}
}
override fun getDisplayName() = "Replace \"hello\" with \"Howdy do!\" in Python"
override fun getShortName() = "HelloWorldInspection"
override fun getGroupDisplayName() = "Live plugin"
override fun isEnabledByDefault() = true
}
class HelloWorldQuickFix: LocalQuickFix {
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val factory = JavaPsiFacade.getInstance(project).elementFactory
val stringLiteral = factory.createExpressionFromText("\"Howdy do!\"", null)
descriptor.psiElement.replace(stringLiteral)
}
override fun getName() = "Replace with \"Howdy do!\""
override fun getFamilyName() = name
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment