Skip to content

Commit

Permalink
refactor: split chat code completion action
Browse files Browse the repository at this point in the history
  • Loading branch information
phodal committed Dec 20, 2023
1 parent b0307da commit efe9462
Showing 1 changed file with 39 additions and 24 deletions.
Original file line number Diff line number Diff line change
@@ -1,31 +1,46 @@
package cc.unitmesh.devti.actions.chat

import cc.unitmesh.devti.actions.chat.base.ChatBaseAction
import cc.unitmesh.devti.AutoDevBundle
import cc.unitmesh.devti.gui.chat.ChatActionType
import com.intellij.openapi.actionSystem.ActionUpdateThread
import cc.unitmesh.devti.gui.chat.ChatContext
import cc.unitmesh.devti.gui.sendToChatPanel
import cc.unitmesh.devti.provider.ContextPrompter
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.command.WriteCommandAction

class CodeCompleteChatAction : ChatBaseAction() {
override fun getActionType(): ChatActionType = ChatActionType.CODE_COMPLETE

override fun getReplaceableAction(event: AnActionEvent): (response: String) -> Unit {
val editor = event.getRequiredData(CommonDataKeys.EDITOR)
val project = event.getRequiredData(CommonDataKeys.PROJECT)
val document = editor.document

val primaryCaret = editor.caretModel.primaryCaret;
val start = primaryCaret.selectionStart
val end = primaryCaret.selectionEnd

return { response ->
WriteCommandAction.runWriteCommandAction(project) {
document.insertString(start, response)
primaryCaret.removeSelection()
primaryCaret.moveToOffset(end + response.length)
}
import com.intellij.openapi.application.runReadAction
import com.intellij.temporary.getElementToAction

class CodeCompleteChatAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val document = e.getData(CommonDataKeys.EDITOR)?.document
val caretModel = e.getData(CommonDataKeys.EDITOR)?.caretModel

var prefixText = caretModel?.currentCaret?.selectedText ?: ""

val file = e.getData(CommonDataKeys.PSI_FILE)

val lineEndOffset = document?.getLineEndOffset(document.getLineNumber(caretModel?.offset ?: 0)) ?: 0
if (prefixText.isEmpty()) {
prefixText = document?.text?.substring(0, lineEndOffset) ?: ""
}
}
}
val suffixText = document?.text?.substring(lineEndOffset) ?: ""

val editor = e.getData(CommonDataKeys.EDITOR) ?: return

val prompter = ContextPrompter.prompter(file?.language?.displayName ?: "")

val element = runReadAction { getElementToAction(project, editor) }
prompter.initContext(ChatActionType.CODE_COMPLETE, prefixText, file, project, caretModel?.offset ?: 0, element)

sendToChatPanel(project) { panel, service ->
val chatContext = ChatContext(
null,
prefixText,
suffixText
)
service.handlePromptAndResponse(panel, prompter, chatContext)
}
}
}

0 comments on commit efe9462

Please sign in to comment.