Skip to content

Instantly share code, notes, and snippets.

@rahul-lohra
Last active July 19, 2020 03:41
Show Gist options
  • Save rahul-lohra/5b680026de04b95926b4e8e1d913ac06 to your computer and use it in GitHub Desktop.
Save rahul-lohra/5b680026de04b95926b4e8e1d913ac06 to your computer and use it in GitHub Desktop.
Logic for reading value from variable defined in kt file
class EditorLogic {
val nodeCreator = NodeCreator()
var expressionElement: PsiElement? = null
fun selectCurrentFile(variableName: String, project: Project, textArea: JTextArea) {
reset()
val fileEditorManager = FileEditorManager.getInstance(project)
val virtualFile = fileEditorManager.openFiles
if (!virtualFile.isNullOrEmpty()) {
val vf = fileEditorManager.selectedEditor?.file
vf?.let { file ->
val psiFile = PsiManager.getInstance(project).findFile(file)
if (psiFile != null) {
psiFile.accept(javaVisitor(textArea))
kotlinVisitor(variableName, textArea, psiFile)
}
}
}
}
fun kotlinVisitor(variableName: String, textArea: JTextArea, psiFile: PsiFile) {
psiFile.accept(object : KtTreeVisitorVoid() {
override fun visitProperty(property: KtProperty) {
super.visitProperty(property) //yes
val localVariableName = property.name
if (property.type().toString() == "String" && localVariableName == variableName) {
val expressionElement = property.lastChild
this@EditorLogic.expressionElement = expressionElement
textArea.text = findTextInVariable(expressionElement)
}
}
})
}
fun findTextInVariable(psiElement: PsiElement): String {
when (psiElement) {
is KtStringTemplateExpression -> {
val text = getTextFromKtStringTemplateExpression(psiElement)
val node = nodeCreator.createNode(text.replace("\\n", ""))
return nodeCreator.prettyPrint2(node)
}
is KtBinaryExpression -> {
val array = psiElement.text.split("+")
val sb = StringBuilder()
for (item in array) {
sb.append(
item.replaceFirst("\"", "")
.replace("\\t", "")
.replace("\\n", "")
.replace("\\", "")
.trimEnd()
.removeSuffix("\"")
)
}
val node = nodeCreator.createNode(sb.toString().replace("\\n", ""))
return nodeCreator.prettyPrint2(node)
}
is KtDotQualifiedExpression -> {
if (psiElement.firstChild is KtStringTemplateExpression) {
return findTextInVariable(psiElement.firstChild)
}
}
}
//todo Rahul throw exception - not supported
return "Type not supported"
}
fun reset() {
expressionElement = null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment