generated from JetBrains/intellij-platform-plugin-template
-
Notifications
You must be signed in to change notification settings - Fork 287
/
RenameLookupManagerListener.kt
81 lines (64 loc) · 2.63 KB
/
RenameLookupManagerListener.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package cc.unitmesh.devti.practise
import cc.unitmesh.devti.AutoDevIcons
import cc.unitmesh.devti.llms.LlmFactory
import cc.unitmesh.devti.settings.coder.coderSetting
import com.intellij.codeInsight.completion.PrefixMatcher
import com.intellij.codeInsight.lookup.*
import com.intellij.codeInsight.lookup.impl.LookupImpl
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.impl.source.tree.LeafPsiElement
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking
class RenameLookupManagerListener(val project: Project) : LookupManagerListener {
private val llm = LlmFactory.instance.create(project)
override fun activeLookupChanged(oldLookup: Lookup?, newLookup: Lookup?) {
val lookupImpl = newLookup as? LookupImpl ?: return
if (!project.coderSetting.state.enableRenameSuggestion) return
val lookupOriginalStart = lookupImpl.lookupOriginalStart
val startOffset = if (lookupOriginalStart > -1) lookupOriginalStart else 0
val psiElement = lookupImpl.psiFile?.findElementAt(startOffset)
val element = psiElement ?: lookupImpl.psiElement ?: return
val parentClass = if (element is LeafPsiElement || element is PsiWhiteSpace) {
element.parent?.javaClass
} else {
element.javaClass
}
val name = parentClass?.name ?: element.text
val prompt = runBlocking {
val stringFlow: Flow<String> = llm.stream(
"""$name is a badname. Please provide 5 better options name for follow code:
```${element.language.displayName}
${element.text}
```
1.
""".trimIndent(),
"",
false
)
val sb = StringBuilder()
stringFlow.collect {
sb.append(it)
}
sb.toString()
}
// the prompt will be list format, split with \n and remove start number with regex
val suggestionNames = prompt.split("\n").map {
it.replace(Regex("^\\d+\\."), "")
.trim()
.removeSurrounding("`")
}
suggestionNames.map {
lookupImpl.addItem(RenameLookupElement(it), PrefixMatcher.ALWAYS_TRUE)
}
}
}
class RenameLookupElement(val name: String) : LookupElement() {
override fun getLookupString(): String = name
override fun renderElement(presentation: LookupElementPresentation) {
presentation.icon = AutoDevIcons.Idea
super.renderElement(presentation)
}
}
class RenameLookupListener : LookupListener {
}