fix: migrate to built-in inline completion API from 2024.1 (#6947)
This commit is contained in:
parent
9c688f5281
commit
e31f2f4246
30 changed files with 367 additions and 1608 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -158,6 +158,7 @@ extensions/intellij/.idea/**
|
|||
**/.idea/shelf/
|
||||
**/.idea/inspectionProfiles/Project_Default.xml
|
||||
**/.idea/php.xml
|
||||
**/.idea/kotlinc.xml
|
||||
|
||||
|
||||
extensions/intellij/bin
|
||||
|
|
|
|||
6
.idea/kotlinc.xml
generated
6
.idea/kotlinc.xml
generated
|
|
@ -1,6 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="KotlinJpsPluginSettings">
|
||||
<option name="version" value="1.8.0" />
|
||||
</component>
|
||||
</project>
|
||||
1
extensions/intellij/.gitignore
vendored
1
extensions/intellij/.gitignore
vendored
|
|
@ -4,5 +4,6 @@ src/main/resources/bin
|
|||
src/main/resources/config_schema.json
|
||||
src/main/resources/continue_rc_schema.json
|
||||
video
|
||||
.intellijPlatform
|
||||
src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/*
|
||||
!src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/config.json
|
||||
|
|
@ -4,14 +4,13 @@
|
|||
<option name="env">
|
||||
<map>
|
||||
<entry key="GUI_URL" value="http://localhost:5173/jetbrains_index.html"/>
|
||||
<entry key="ORG_GRADLE_PROJECT_platformVersion" value="2024.1"/>
|
||||
<entry key="USE_TCP" value="true"/>
|
||||
</map>
|
||||
</option>
|
||||
<option name="executionName"/>
|
||||
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij"/>
|
||||
<option name="externalSystemIdString" value="GRADLE"/>
|
||||
<option name="scriptParameters" value=""/>
|
||||
<option name="scriptParameters" value="" />
|
||||
<option name="taskDescriptions">
|
||||
<list/>
|
||||
</option>
|
||||
|
|
|
|||
|
|
@ -5,17 +5,14 @@ import org.jetbrains.intellij.platform.gradle.tasks.PrepareSandboxTask
|
|||
fun environment(key: String) = providers.environmentVariable(key)
|
||||
|
||||
val remoteRobotVersion = "0.11.23"
|
||||
val platformType: String by project
|
||||
val platformVersion: String by project
|
||||
val pluginGroup: String by project
|
||||
val pluginVersion: String by project
|
||||
val pluginSinceBuild: String by project
|
||||
val pluginRepositoryUrl: String by project
|
||||
val isEap get() = environment("RELEASE_CHANNEL").orNull == "eap"
|
||||
|
||||
plugins {
|
||||
kotlin("jvm") version "1.8.0"
|
||||
id("org.jetbrains.intellij.platform") version "2.6.0"
|
||||
kotlin("jvm") version "1.9.22"
|
||||
id("org.jetbrains.intellij.platform") version "2.7.2"
|
||||
id("org.jetbrains.changelog") version "2.1.2"
|
||||
id("org.jetbrains.qodana") version "0.1.13"
|
||||
id("org.jetbrains.kotlinx.kover") version "0.7.3"
|
||||
|
|
@ -34,42 +31,46 @@ repositories {
|
|||
|
||||
dependencies {
|
||||
intellijPlatform {
|
||||
create(platformType, platformVersion)
|
||||
plugins(listOf("org.jetbrains.plugins.terminal:223.8214.6"))
|
||||
create("IC", platformVersion)
|
||||
plugins(listOf("org.jetbrains.plugins.terminal:241.14494.150"))
|
||||
testFramework(TestFrameworkType.Platform)
|
||||
}
|
||||
implementation("com.posthog.java:posthog:1.2.0")
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
testImplementation("com.intellij.remoterobot:remote-robot:$remoteRobotVersion")
|
||||
testImplementation("com.intellij.remoterobot:remote-fixtures:$remoteRobotVersion")
|
||||
testImplementation("io.mockk:mockk:1.14.2")
|
||||
testImplementation("io.mockk:mockk:1.14.2") {
|
||||
// this transitive dependency (1.6.4) conflicts with built-in version (1.7.3)
|
||||
// otherwise e2e tests (runIdeForUiTests) will have linkage errors
|
||||
exclude(group = "org.jetbrains.kotlinx", module = "kotlinx-coroutines-core")
|
||||
}
|
||||
testImplementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
|
||||
testImplementation("com.automation-remarks:video-recorder-junit5:2.0")
|
||||
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")
|
||||
testRuntimeOnly("org.junit.vintage:junit-vintage-engine:5.10.0") // required to run both JUnit 5 and JUnit 3
|
||||
}
|
||||
|
||||
kotlin { jvmToolchain(17) }
|
||||
kotlin {
|
||||
jvmToolchain(17)
|
||||
}
|
||||
|
||||
intellijPlatform {
|
||||
pluginConfiguration {
|
||||
ideaVersion {
|
||||
sinceBuild = pluginSinceBuild
|
||||
sinceBuild = "241"
|
||||
}
|
||||
}
|
||||
pluginVerification {
|
||||
ides {
|
||||
ide("IC", "2025.1.4")
|
||||
ide("IC", "2022.3.3")
|
||||
ide("IC", "2025.2")
|
||||
ide("IC", "2025.1")
|
||||
ide("IC", "2024.3")
|
||||
ide("IC", "2024.2")
|
||||
ide("IC", "2024.1")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
changelog {
|
||||
groups.empty()
|
||||
repositoryUrl = pluginRepositoryUrl
|
||||
}
|
||||
|
||||
qodana {
|
||||
cachePath = provider { file(".qodana").canonicalPath }
|
||||
reportPath = provider { file("build/reports/inspections").canonicalPath }
|
||||
|
|
@ -77,7 +78,11 @@ qodana {
|
|||
showReport = environment("QODANA_SHOW_REPORT").map { it.toBoolean() }.getOrElse(false)
|
||||
}
|
||||
|
||||
koverReport { defaults { xml { onCheck = true } } }
|
||||
koverReport {
|
||||
defaults {
|
||||
xml { onCheck = true }
|
||||
}
|
||||
}
|
||||
|
||||
intellijPlatformTesting {
|
||||
runIde {
|
||||
|
|
|
|||
|
|
@ -1,9 +1,6 @@
|
|||
pluginGroup=com.github.continuedev.continueintellijextension
|
||||
pluginRepositoryUrl=https://github.com/continuedev/continue
|
||||
pluginVersion=1.0.38
|
||||
pluginSinceBuild=223
|
||||
platformType=IC
|
||||
platformVersion=2022.3.3
|
||||
platformVersion=2024.1
|
||||
kotlin.stdlib.default.dependency=false
|
||||
org.gradle.configuration-cache=true
|
||||
org.gradle.caching=true
|
||||
|
|
|
|||
|
|
@ -1,32 +1,14 @@
|
|||
package com.github.continuedev.continueintellijextension.actions
|
||||
|
||||
import com.github.continuedev.continueintellijextension.autocomplete.AcceptAutocompleteAction
|
||||
import com.github.continuedev.continueintellijextension.nextEdit.AcceptNextEditAction
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
|
||||
import com.intellij.openapi.actionSystem.ActionPromoter
|
||||
import com.intellij.openapi.actionSystem.AnAction
|
||||
import com.intellij.openapi.actionSystem.DataContext
|
||||
import com.intellij.openapi.components.service
|
||||
import org.jetbrains.annotations.NotNull
|
||||
|
||||
class ContinueActionPromote : ActionPromoter {
|
||||
|
||||
override fun promote(@NotNull actions: List<AnAction>, @NotNull context: DataContext): List<AnAction>? {
|
||||
// For autocomplete actions
|
||||
if (actions.any { it is AcceptAutocompleteAction }) {
|
||||
val settings = service<ContinueExtensionSettings>()
|
||||
if (settings.continueState.showIDECompletionSideBySide) {
|
||||
return actions.filterIsInstance<AcceptAutocompleteAction>()
|
||||
}
|
||||
}
|
||||
|
||||
if (actions.any { it is AcceptNextEditAction }) {
|
||||
val settings = service<ContinueExtensionSettings>()
|
||||
if (settings.continueState.showIDECompletionSideBySide) {
|
||||
return actions.filterIsInstance<AcceptNextEditAction>()
|
||||
}
|
||||
}
|
||||
|
||||
val rejectDiffActions = actions.filterIsInstance<RejectDiffAction>()
|
||||
if (rejectDiffActions.isNotEmpty()) {
|
||||
return rejectDiffActions
|
||||
|
|
|
|||
|
|
@ -1,25 +0,0 @@
|
|||
package com.github.continuedev.continueintellijextension.autocomplete
|
||||
|
||||
import com.intellij.openapi.actionSystem.DataContext
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.editor.Caret
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.actionSystem.EditorAction
|
||||
import com.intellij.openapi.editor.actionSystem.EditorActionHandler
|
||||
|
||||
class AcceptAutocompleteAction : EditorAction(object : EditorActionHandler() {
|
||||
override fun doExecute(editor: Editor, caret: Caret?, dataContext: DataContext?) {
|
||||
ApplicationManager.getApplication().runWriteAction {
|
||||
editor.project?.service<AutocompleteService>()?.accept()
|
||||
}
|
||||
}
|
||||
|
||||
override fun isEnabledForCaret(editor: Editor, caret: Caret, dataContext: DataContext?): Boolean {
|
||||
val autocompleteService = editor.project?.service<AutocompleteService>();
|
||||
val enabled = editor == autocompleteService?.pendingCompletion?.editor
|
||||
// && caret.offset == autocompleteService.pendingCompletion?.offset
|
||||
&& autocompleteService.pendingCompletion?.text != null
|
||||
return enabled
|
||||
}
|
||||
})
|
||||
|
|
@ -1,151 +0,0 @@
|
|||
package com.github.continuedev.continueintellijextension.autocomplete
|
||||
|
||||
import com.github.continuedev.continueintellijextension.nextEdit.NextEditService
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
|
||||
import com.intellij.openapi.application.invokeLater
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.EditorKind
|
||||
import com.intellij.openapi.editor.event.*
|
||||
import com.intellij.openapi.fileEditor.FileEditorManager
|
||||
import com.intellij.openapi.fileEditor.FileEditorManagerEvent
|
||||
import com.intellij.openapi.fileEditor.FileEditorManagerListener
|
||||
import com.intellij.openapi.util.TextRange
|
||||
|
||||
class AutocompleteCaretListener : CaretListener {
|
||||
override fun caretPositionChanged(event: CaretEvent) {
|
||||
if(event.editor.editorKind != EditorKind.MAIN_EDITOR) {
|
||||
return
|
||||
}
|
||||
|
||||
val caret = event.caret ?: return
|
||||
val offset = caret.offset
|
||||
val editor = caret.editor
|
||||
val autocompleteService = editor.project?.service<AutocompleteService>() ?: return
|
||||
|
||||
if (autocompleteService.lastChangeWasPartialAccept) {
|
||||
autocompleteService.lastChangeWasPartialAccept = false
|
||||
return
|
||||
}
|
||||
|
||||
val pending = autocompleteService.pendingCompletion;
|
||||
if (pending != null && pending.editor == editor && pending.offset == offset) {
|
||||
return
|
||||
}
|
||||
autocompleteService.clearCompletions(editor)
|
||||
}
|
||||
}
|
||||
|
||||
class AutocompleteDocumentListener(private val editorManager: FileEditorManager, private val editor: Editor) :
|
||||
DocumentListener {
|
||||
override fun documentChanged(event: DocumentEvent) {
|
||||
// Ignore empty changes or changes where content didn't actually change.
|
||||
if (event.newFragment.isEmpty() && event.oldFragment.isEmpty()) {
|
||||
return
|
||||
}
|
||||
|
||||
// Make sure this is an actual text modification event.
|
||||
if (!event.isWholeTextReplaced && event.offset == 0 && event.oldLength == 0 && event.newLength == 0) {
|
||||
return
|
||||
}
|
||||
|
||||
if (editor != editorManager.selectedTextEditor) {
|
||||
return
|
||||
}
|
||||
|
||||
val service = editor.project?.service<AutocompleteService>() ?: return
|
||||
if (service.lastChangeWasPartialAccept) {
|
||||
return
|
||||
}
|
||||
|
||||
val nextEditService = editor.project?.service<NextEditService>() ?: return
|
||||
|
||||
// Check if we're in a test environment based on some property or condition
|
||||
val isAutocompleteTestEnvironment = System.getProperty("continue.autocomplete.test.environment") == "true"
|
||||
val isNextEditTestEnvironment = System.getProperty("continue.nextEdit.test.environment") == "true"
|
||||
|
||||
if (isAutocompleteTestEnvironment) {
|
||||
invokeLater {
|
||||
service.triggerCompletion(editor)
|
||||
}
|
||||
return
|
||||
} else if (isNextEditTestEnvironment) {
|
||||
invokeLater {
|
||||
nextEditService.triggerNextEdit(editor)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Check settings to see if next edit is enabled, and then trigger either autocomplete or next exit.
|
||||
val continuePluginService = editor.project?.service<ContinuePluginService>()
|
||||
if (continuePluginService == null) {
|
||||
return
|
||||
}
|
||||
|
||||
continuePluginService.coreMessenger?.request(
|
||||
"config/getSerializedProfileInfo",
|
||||
null,
|
||||
null,
|
||||
({ response ->
|
||||
val optInNextEditFeature = response.castNestedOrNull<Boolean>(
|
||||
"content",
|
||||
"result",
|
||||
"config",
|
||||
"experimental",
|
||||
"optInNextEditFeature"
|
||||
) ?: false
|
||||
|
||||
invokeLater {
|
||||
if (optInNextEditFeature) {
|
||||
nextEditService.triggerNextEdit(editor)
|
||||
} else {
|
||||
// Invoke later is important, otherwise the completion will be triggered before the document is updated
|
||||
// causing the old caret offset to be used
|
||||
// TODO: concurrency
|
||||
service.triggerCompletion(editor)
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
class AutocompleteEditorListener : EditorFactoryListener {
|
||||
private val disposables = mutableMapOf<Editor, () -> Unit>()
|
||||
override fun editorCreated(event: EditorFactoryEvent) {
|
||||
val editor = event.editor
|
||||
val project = editor.project ?: return
|
||||
val editorManager = project.let { FileEditorManager.getInstance(it) } ?: return
|
||||
val completionProvider = project.service<AutocompleteService>()
|
||||
|
||||
// Listen to changes to mouse position
|
||||
val caretListener = AutocompleteCaretListener()
|
||||
editor.caretModel.addCaretListener(caretListener)
|
||||
|
||||
// Listen to changes to selection
|
||||
val connection = editor.project?.messageBus?.connect()
|
||||
connection?.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, object : FileEditorManagerListener {
|
||||
override fun selectionChanged(event: FileEditorManagerEvent) {
|
||||
completionProvider.clearCompletions(editor)
|
||||
}
|
||||
})
|
||||
|
||||
// Listen to changes to content
|
||||
val documentListener = AutocompleteDocumentListener(editorManager, editor)
|
||||
editor.document.addDocumentListener(documentListener)
|
||||
|
||||
disposables[editor] = {
|
||||
editor.caretModel.removeCaretListener(caretListener)
|
||||
connection?.disconnect()
|
||||
editor.document.removeDocumentListener(documentListener)
|
||||
}
|
||||
}
|
||||
|
||||
override fun editorReleased(event: EditorFactoryEvent) {
|
||||
val editor = event.editor
|
||||
val disposable = disposables[editor]
|
||||
disposable?.invoke()
|
||||
disposables.remove(editor)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,48 +0,0 @@
|
|||
package com.github.continuedev.continueintellijextension.autocomplete
|
||||
|
||||
import com.intellij.codeInsight.lookup.impl.LookupImpl
|
||||
import com.intellij.codeInsight.lookup.Lookup
|
||||
import com.intellij.codeInsight.lookup.LookupEvent
|
||||
import com.intellij.codeInsight.lookup.LookupListener
|
||||
import com.intellij.codeInsight.lookup.LookupManagerListener
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.components.Service
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.project.Project
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
@Service(Service.Level.PROJECT)
|
||||
class AutocompleteLookupListener(project: Project) : LookupManagerListener {
|
||||
private val isLookupShown = AtomicBoolean(true)
|
||||
|
||||
fun isLookupEmpty(): Boolean {
|
||||
return isLookupShown.get()
|
||||
}
|
||||
|
||||
init {
|
||||
project.messageBus.connect().subscribe(LookupManagerListener.TOPIC, this)
|
||||
}
|
||||
|
||||
override fun activeLookupChanged(oldLookup: Lookup?, newLookup: Lookup?) {
|
||||
val newEditor = newLookup?.editor ?: return
|
||||
if (newLookup is LookupImpl) {
|
||||
newLookup.addLookupListener(
|
||||
object : LookupListener {
|
||||
override fun lookupShown(event: LookupEvent) {
|
||||
isLookupShown.set(false)
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
event.lookup.editor.project?.service<AutocompleteService>()?.hideCompletions(newEditor)
|
||||
}
|
||||
}
|
||||
|
||||
override fun lookupCanceled(event: LookupEvent) {
|
||||
isLookupShown.set(true)
|
||||
}
|
||||
|
||||
override fun itemSelected(event: LookupEvent) {
|
||||
isLookupShown.set(true)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,323 +0,0 @@
|
|||
package com.github.continuedev.continueintellijextension.autocomplete
|
||||
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.github.continuedev.continueintellijextension.utils.toUriOrNull
|
||||
import com.github.continuedev.continueintellijextension.utils.uuid
|
||||
import com.intellij.injected.editor.VirtualFileWindow
|
||||
import com.intellij.openapi.application.*
|
||||
import com.intellij.openapi.components.Service
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.InlayProperties
|
||||
import com.intellij.openapi.editor.impl.EditorImpl
|
||||
import com.intellij.openapi.fileEditor.FileDocumentManager
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.util.TextRange
|
||||
import com.intellij.openapi.wm.WindowManager
|
||||
import com.intellij.psi.PsiDocumentManager
|
||||
import com.intellij.psi.PsiElement
|
||||
|
||||
data class PendingCompletion(
|
||||
val editor: Editor,
|
||||
var offset: Int,
|
||||
val completionId: String,
|
||||
var text: String?
|
||||
)
|
||||
|
||||
|
||||
fun PsiElement.isInjectedText(): Boolean {
|
||||
val virtualFile = this.containingFile.virtualFile ?: return false
|
||||
if (virtualFile is VirtualFileWindow) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
fun Editor.addInlayElement(
|
||||
lines: List<String>,
|
||||
offset: Int,
|
||||
properties: InlayProperties
|
||||
) {
|
||||
if (this is EditorImpl) {
|
||||
if (lines[0].isNotEmpty()) {
|
||||
inlayModel.addInlineElement(offset, properties, ContinueInlayRenderer(listOf(lines[0])))
|
||||
}
|
||||
if (lines.size > 1) {
|
||||
inlayModel.addBlockElement(offset, properties, ContinueInlayRenderer(lines.drop(1)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Service(Service.Level.PROJECT)
|
||||
class AutocompleteService(private val project: Project) {
|
||||
var pendingCompletion: PendingCompletion? = null
|
||||
private val autocompleteLookupListener = project.service<AutocompleteLookupListener>()
|
||||
private val widget: AutocompleteSpinnerWidget? by lazy {
|
||||
WindowManager.getInstance().getStatusBar(project)
|
||||
?.getWidget(AutocompleteSpinnerWidget.ID) as? AutocompleteSpinnerWidget
|
||||
}
|
||||
|
||||
// To avoid triggering another completion on partial acceptance,
|
||||
// we need to keep track of whether the last change was a partial accept
|
||||
var lastChangeWasPartialAccept = false
|
||||
|
||||
fun triggerCompletion(editor: Editor) {
|
||||
val settings = service<ContinueExtensionSettings>()
|
||||
if (!settings.continueState.enableTabAutocomplete) {
|
||||
return
|
||||
}
|
||||
|
||||
if (pendingCompletion != null) {
|
||||
clearCompletions(pendingCompletion!!.editor)
|
||||
}
|
||||
|
||||
// Set pending completion
|
||||
val completionId = uuid()
|
||||
val offset = editor.caretModel.primaryCaret.offset
|
||||
pendingCompletion = PendingCompletion(editor, offset, completionId, null)
|
||||
|
||||
// Request a completion from the core
|
||||
val virtualFile = FileDocumentManager.getInstance().getFile(editor.document)
|
||||
|
||||
val uri = virtualFile?.toUriOrNull() ?: return
|
||||
|
||||
widget?.setLoading(true)
|
||||
|
||||
val line = editor.caretModel.primaryCaret.logicalPosition.line
|
||||
val column = editor.caretModel.primaryCaret.logicalPosition.column
|
||||
val input = mapOf(
|
||||
"completionId" to completionId,
|
||||
"filepath" to uri,
|
||||
"pos" to mapOf(
|
||||
"line" to line,
|
||||
"character" to column
|
||||
),
|
||||
"clipboardText" to "",
|
||||
"recentlyEditedRanges" to emptyList<Any>(),
|
||||
"recentlyVisitedRanges" to emptyList<Any>(),
|
||||
)
|
||||
|
||||
project.service<ContinuePluginService>().coreMessenger?.request(
|
||||
"autocomplete/complete",
|
||||
input,
|
||||
null,
|
||||
({ response ->
|
||||
if (pendingCompletion == null || pendingCompletion?.completionId == completionId) {
|
||||
widget?.setLoading(false)
|
||||
}
|
||||
|
||||
val responseObject = response as Map<*, *>
|
||||
val completions = responseObject["content"] as List<*>
|
||||
|
||||
if (completions.isNotEmpty()) {
|
||||
val completion = completions[0].toString()
|
||||
val finalTextToInsert = deduplicateCompletion(editor, offset, completion)
|
||||
|
||||
if (shouldRenderCompletion(finalTextToInsert, offset, line, editor)) {
|
||||
renderCompletion(editor, offset, finalTextToInsert)
|
||||
pendingCompletion = PendingCompletion(editor, offset, completionId, finalTextToInsert)
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
private fun shouldRenderCompletion(completion: String, offset: Int, line: Int, editor: Editor): Boolean {
|
||||
if (completion.isEmpty() || runReadAction { offset != editor.caretModel.offset }) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (completion.lines().size == 1) {
|
||||
return true
|
||||
}
|
||||
|
||||
val endOffset = editor.document.getLineEndOffset(line)
|
||||
|
||||
// Do not render if completion is multi-line and caret is in middle of line
|
||||
return offset <= endOffset && editor.document.getText(TextRange(offset, endOffset)).isBlank()
|
||||
}
|
||||
|
||||
private fun deduplicateCompletion(editor: Editor, offset: Int, completion: String): String {
|
||||
// Check if completion matches the first 10 characters after the cursor
|
||||
return ApplicationManager.getApplication().runReadAction<String> {
|
||||
val document = editor.document
|
||||
val caretOffset = editor.caretModel.offset
|
||||
|
||||
// Don't care about it if it's at the end of the document
|
||||
if (caretOffset == document.textLength) return@runReadAction completion
|
||||
|
||||
val N = 10
|
||||
var textAfterCursor = if (caretOffset + N <= document.textLength) {
|
||||
document.getText(TextRange(caretOffset, caretOffset + N))
|
||||
} else {
|
||||
document.getText(TextRange(caretOffset, document.textLength))
|
||||
}
|
||||
|
||||
// Avoid truncating the completion text when the text after the cursor is blank
|
||||
if (textAfterCursor.isBlank()) return@runReadAction completion
|
||||
|
||||
// Determine the index of a newline character within the text following the cursor.
|
||||
val newlineIndex = textAfterCursor.indexOf("\r\n").takeIf { it >= 0 } ?: textAfterCursor.indexOf('\n')
|
||||
// If a newline character is found and the current line is not empty, truncate the text at that point.
|
||||
if (newlineIndex > 0) {
|
||||
textAfterCursor = textAfterCursor.substring(0, newlineIndex)
|
||||
}
|
||||
|
||||
val indexOfTextAfterCursorInCompletion = completion.indexOf(textAfterCursor)
|
||||
if (indexOfTextAfterCursorInCompletion > 0) {
|
||||
return@runReadAction completion.slice(0..indexOfTextAfterCursorInCompletion - 1)
|
||||
} else if (indexOfTextAfterCursorInCompletion == 0) {
|
||||
return@runReadAction ""
|
||||
}
|
||||
|
||||
return@runReadAction completion
|
||||
}
|
||||
}
|
||||
|
||||
private fun renderCompletion(editor: Editor, offset: Int, completion: String) {
|
||||
if (completion.isEmpty()) {
|
||||
return
|
||||
}
|
||||
if (isInjectedFile(editor)) return
|
||||
// Skip rendering completions if the code completion dropdown is already visible and the IDE completion side-by-side setting is disabled
|
||||
if (shouldSkipRender()) {
|
||||
return
|
||||
}
|
||||
|
||||
invokeLater {
|
||||
// Clear existing completions
|
||||
hideCompletions(editor)
|
||||
|
||||
val properties = InlayProperties()
|
||||
properties.relatesToPrecedingText(true)
|
||||
properties.disableSoftWrapping(true)
|
||||
|
||||
val lines = completion.lines()
|
||||
pendingCompletion = pendingCompletion?.copy(text = lines.joinToString("\n"))
|
||||
editor.addInlayElement(lines, offset, properties)
|
||||
|
||||
// val attributes = TextAttributes().apply {
|
||||
// backgroundColor = JBColor.GREEN
|
||||
// }
|
||||
// val key = TextAttributesKey.createTextAttributesKey("CONTINUE_AUTOCOMPLETE")
|
||||
// key.let { editor.colorsScheme.setAttributes(it, attributes) }
|
||||
// editor.markupModel.addLineHighlighter(key, editor.caretModel.logicalPosition.line, HighlighterLayer.LAST)
|
||||
}
|
||||
}
|
||||
|
||||
fun accept() {
|
||||
val completion = pendingCompletion ?: return
|
||||
val text = completion.text ?: return
|
||||
val editor = completion.editor
|
||||
val offset = completion.offset
|
||||
editor.document.insertString(offset, text)
|
||||
|
||||
editor.caretModel.moveToOffset(offset + text.length)
|
||||
|
||||
project.service<ContinuePluginService>().coreMessenger?.request(
|
||||
"autocomplete/accept",
|
||||
hashMapOf("completionId" to completion.completionId),
|
||||
null,
|
||||
({})
|
||||
)
|
||||
invokeLater {
|
||||
clearCompletions(editor, completion)
|
||||
}
|
||||
}
|
||||
|
||||
private fun shouldSkipRender(): Boolean {
|
||||
val settings = service<ContinueExtensionSettings>()
|
||||
return !settings.continueState.showIDECompletionSideBySide && !autocompleteLookupListener.isLookupEmpty()
|
||||
}
|
||||
|
||||
private fun splitKeepingDelimiters(input: String, delimiterPattern: String = "\\s+"): List<String> {
|
||||
val initialSplit = input.split("(?<=$delimiterPattern)|(?=$delimiterPattern)".toRegex())
|
||||
.filter { it.isNotEmpty() }
|
||||
|
||||
val result = mutableListOf<String>()
|
||||
var currentDelimiter = ""
|
||||
|
||||
for (part in initialSplit) {
|
||||
if (part.matches(delimiterPattern.toRegex())) {
|
||||
currentDelimiter += part
|
||||
} else {
|
||||
if (currentDelimiter.isNotEmpty()) {
|
||||
result.add(currentDelimiter)
|
||||
currentDelimiter = ""
|
||||
}
|
||||
result.add(part)
|
||||
}
|
||||
}
|
||||
|
||||
if (currentDelimiter.isNotEmpty()) {
|
||||
result.add(currentDelimiter)
|
||||
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
fun partialAccept() {
|
||||
val completion = pendingCompletion ?: return
|
||||
val text = completion.text ?: return
|
||||
val editor = completion.editor
|
||||
val offset = completion.offset
|
||||
|
||||
lastChangeWasPartialAccept = true
|
||||
|
||||
// Split the text into words, keeping delimiters
|
||||
val words = splitKeepingDelimiters(text)
|
||||
println(words)
|
||||
val word = words[0]
|
||||
editor.document.insertString(offset, word)
|
||||
editor.caretModel.moveToOffset(offset + word.length)
|
||||
|
||||
// Remove the completion and re-display it
|
||||
hideCompletions(editor)
|
||||
completion.text = text.substring(word.length)
|
||||
completion.offset += word.length
|
||||
renderCompletion(editor, completion.offset, completion.text!!)
|
||||
}
|
||||
|
||||
private fun cancelCompletion(completion: PendingCompletion) {
|
||||
// Send cancellation message to core
|
||||
widget?.setLoading(false)
|
||||
project.service<ContinuePluginService>().coreMessenger?.request("autocomplete/cancel", null, null, ({}))
|
||||
}
|
||||
|
||||
fun clearCompletions(editor: Editor, completion: PendingCompletion? = pendingCompletion) {
|
||||
if (isInjectedFile(editor)) return
|
||||
|
||||
if (completion != null) {
|
||||
cancelCompletion(completion)
|
||||
if (completion.completionId == pendingCompletion?.completionId) pendingCompletion = null
|
||||
}
|
||||
disposeInlayRenderer(editor)
|
||||
}
|
||||
|
||||
private fun isInjectedFile(editor: Editor): Boolean {
|
||||
return runReadAction {
|
||||
PsiDocumentManager.getInstance(project).getPsiFile(editor.document)?.isInjectedText() ?: false
|
||||
}
|
||||
}
|
||||
|
||||
fun hideCompletions(editor: Editor) {
|
||||
if (isInjectedFile(editor)) return
|
||||
|
||||
disposeInlayRenderer(editor)
|
||||
}
|
||||
|
||||
private fun disposeInlayRenderer(editor: Editor) {
|
||||
editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength).forEach {
|
||||
if (it.renderer is ContinueInlayRenderer) {
|
||||
it.dispose()
|
||||
}
|
||||
}
|
||||
editor.inlayModel.getBlockElementsInRange(0, editor.document.textLength).forEach {
|
||||
if (it.renderer is ContinueInlayRenderer) {
|
||||
it.dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,109 +0,0 @@
|
|||
package com.github.continuedev.continueintellijextension.autocomplete
|
||||
|
||||
import com.github.continuedev.continueintellijextension.Icons
|
||||
import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
import com.intellij.openapi.Disposable
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.util.Disposer
|
||||
import com.intellij.openapi.wm.StatusBar
|
||||
import com.intellij.openapi.wm.StatusBarWidget
|
||||
import com.intellij.openapi.util.IconLoader
|
||||
import com.intellij.openapi.wm.StatusBarWidgetFactory
|
||||
import com.intellij.openapi.wm.WindowManager
|
||||
import com.intellij.openapi.wm.impl.status.EditorBasedWidget
|
||||
import com.intellij.ui.AnimatedIcon
|
||||
import com.intellij.util.Consumer
|
||||
import java.awt.event.MouseEvent
|
||||
import javax.swing.Icon
|
||||
import javax.swing.JLabel
|
||||
|
||||
class AutocompleteSpinnerWidget(project: Project) : EditorBasedWidget(project), StatusBarWidget.IconPresentation,
|
||||
Disposable {
|
||||
private val iconLabel = JLabel()
|
||||
private var isLoading = false
|
||||
|
||||
private val animatedIcon = AnimatedIcon.Default()
|
||||
|
||||
init {
|
||||
Disposer.register(project.service<ContinuePluginDisposable>(), this)
|
||||
updateIcon()
|
||||
}
|
||||
|
||||
fun show() {
|
||||
println("Showing autocomplete spinner widget")
|
||||
}
|
||||
|
||||
override fun dispose() {}
|
||||
|
||||
override fun ID(): String {
|
||||
return ID
|
||||
}
|
||||
|
||||
override fun getTooltipText(): String {
|
||||
val enabled = service<ContinueExtensionSettings>().state.enableTabAutocomplete
|
||||
return if (enabled) "Continue autocomplete enabled" else "Continue autocomplete disabled"
|
||||
}
|
||||
|
||||
override fun getClickConsumer(): Consumer<MouseEvent>? {
|
||||
return null
|
||||
}
|
||||
|
||||
override fun getIcon(): Icon = if (isLoading) animatedIcon else
|
||||
Icons.Continue
|
||||
|
||||
fun setLoading(loading: Boolean) {
|
||||
isLoading = loading
|
||||
updateIcon()
|
||||
}
|
||||
|
||||
private fun updateIcon() {
|
||||
iconLabel.icon = getIcon()
|
||||
|
||||
|
||||
// Update the widget
|
||||
val statusBar = WindowManager.getInstance().getStatusBar(project)
|
||||
statusBar?.updateWidget(ID())
|
||||
}
|
||||
|
||||
override fun install(statusBar: StatusBar) {
|
||||
updateIcon()
|
||||
}
|
||||
|
||||
override fun getPresentation(): StatusBarWidget.WidgetPresentation {
|
||||
return this
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val ID = "AutocompleteSpinnerWidget"
|
||||
}
|
||||
}
|
||||
|
||||
class AutocompleteSpinnerWidgetFactory : StatusBarWidgetFactory {
|
||||
fun create(project: Project): AutocompleteSpinnerWidget {
|
||||
return AutocompleteSpinnerWidget(project)
|
||||
}
|
||||
|
||||
override fun getId(): String {
|
||||
return AutocompleteSpinnerWidget.ID
|
||||
}
|
||||
|
||||
override fun getDisplayName(): String {
|
||||
return "Continue Autocomplete"
|
||||
}
|
||||
|
||||
override fun isAvailable(p0: Project): Boolean {
|
||||
return true
|
||||
}
|
||||
|
||||
override fun createWidget(project: Project): StatusBarWidget {
|
||||
return create(project)
|
||||
}
|
||||
|
||||
override fun disposeWidget(p0: StatusBarWidget) {
|
||||
Disposer.dispose(p0)
|
||||
}
|
||||
|
||||
override fun canBeEnabledOn(p0: StatusBar): Boolean = true
|
||||
}
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
package com.github.continuedev.continueintellijextension.autocomplete
|
||||
|
||||
import com.intellij.openapi.actionSystem.ActionUpdateThread
|
||||
import com.intellij.openapi.actionSystem.AnAction
|
||||
import com.intellij.openapi.actionSystem.AnActionEvent
|
||||
import com.intellij.openapi.actionSystem.CommonDataKeys
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.project.Project
|
||||
|
||||
class CancelAutocompleteAction : AnAction() {
|
||||
override fun actionPerformed(e: AnActionEvent) {
|
||||
if (isInvokedInEditor(e)) {
|
||||
val editor = e.getRequiredData(CommonDataKeys.EDITOR)
|
||||
ApplicationManager.getApplication().runWriteAction {
|
||||
editor.project?.service<AutocompleteService>()?.clearCompletions(editor)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun update(e: AnActionEvent) {
|
||||
e.presentation.isEnabledAndVisible = isInvokedInEditor(e)
|
||||
}
|
||||
|
||||
private fun isInvokedInEditor(e: AnActionEvent): Boolean {
|
||||
val project: Project? = e.project
|
||||
val editor: Editor? = e.getData(CommonDataKeys.EDITOR)
|
||||
return project != null && editor != null && editor.contentComponent.hasFocus()
|
||||
}
|
||||
|
||||
override fun getActionUpdateThread(): ActionUpdateThread {
|
||||
return ActionUpdateThread.BGT
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
package com.github.continuedev.continueintellijextension.autocomplete
|
||||
|
||||
|
||||
interface CompletionService {
|
||||
|
||||
suspend fun getAutocomplete(uuid: String, url: String, line: Int, column: Int): String?
|
||||
|
||||
fun acceptAutocomplete(uuid: String?)
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
package com.github.continuedev.continueintellijextension.autocomplete
|
||||
|
||||
import com.github.continuedev.continueintellijextension.`continue`.ProfileInfoService
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
|
||||
import com.intellij.openapi.components.Service
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.project.Project
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
|
||||
@Service(Service.Level.PROJECT)
|
||||
class ContinueCompletionService(private val project: Project) : CompletionService {
|
||||
|
||||
override suspend fun getAutocomplete(uuid: String, url: String, line: Int, column: Int): String? {
|
||||
val requestInput = getCompletionInput(uuid, url, line, column)
|
||||
val modelTimeout = project.service<ProfileInfoService>().fetchModelTimeoutOrNull() ?: 1000.0
|
||||
return withTimeoutOrNull(modelTimeout.milliseconds) {
|
||||
suspendCancellableCoroutine { continuation ->
|
||||
project.service<ContinuePluginService>().coreMessenger?.request(
|
||||
"autocomplete/complete",
|
||||
requestInput,
|
||||
null
|
||||
) {
|
||||
val content = it.castNestedOrNull<List<String>>("content")?.firstOrNull() ?: ""
|
||||
continuation.resumeWith(Result.success(content))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun acceptAutocomplete(uuid: String?) {
|
||||
project.service<ContinuePluginService>().coreMessenger?.request(
|
||||
"autocomplete/accept",
|
||||
mapOf("completionId" to uuid),
|
||||
null
|
||||
) {}
|
||||
}
|
||||
|
||||
private fun getCompletionInput(uuid: String, filepath: String, line: Int, character: Int): Map<String, *> = mapOf(
|
||||
"completionId" to uuid,
|
||||
"filepath" to filepath,
|
||||
"pos" to mapOf(
|
||||
"line" to line,
|
||||
"character" to character
|
||||
),
|
||||
"clipboardText" to "",
|
||||
"recentlyEditedRanges" to emptyList<Any>(),
|
||||
"recentlyVisitedRanges" to emptyList<Any>(),
|
||||
)
|
||||
|
||||
}
|
||||
|
|
@ -1,58 +0,0 @@
|
|||
package com.github.continuedev.continueintellijextension.autocomplete
|
||||
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.EditorCustomElementRenderer
|
||||
import com.intellij.openapi.editor.Inlay
|
||||
import com.intellij.openapi.editor.colors.EditorFontType
|
||||
import com.intellij.openapi.editor.impl.EditorImpl
|
||||
import com.intellij.openapi.editor.markup.TextAttributes
|
||||
import com.intellij.ui.JBColor
|
||||
import com.intellij.util.ui.UIUtil
|
||||
import java.awt.Font
|
||||
import java.awt.Graphics
|
||||
import java.awt.Rectangle
|
||||
|
||||
/**
|
||||
* The `ContinueInlayRenderer` class is responsible for rendering custom inlay elements within an editor.
|
||||
* It implements the [EditorCustomElementRenderer] interface to provide custom rendering logic for inlays.
|
||||
*
|
||||
* This renderer is designed to display a list of text lines (`lines`) within the editor, calculating the
|
||||
* necessary width and height based on the content and rendering each line with appropriate font and color.
|
||||
*
|
||||
* @author lk
|
||||
*/
|
||||
class ContinueInlayRenderer(val lines: List<String>) : EditorCustomElementRenderer {
|
||||
override fun calcWidthInPixels(inlay: Inlay<*>): Int {
|
||||
var maxLen = 0;
|
||||
for (line in lines) {
|
||||
val len = (inlay.editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth(line)
|
||||
if (len > maxLen) {
|
||||
maxLen = len
|
||||
}
|
||||
}
|
||||
return maxLen
|
||||
}
|
||||
|
||||
override fun calcHeightInPixels(inlay: Inlay<*>): Int {
|
||||
return (inlay.editor as EditorImpl).lineHeight * lines.size
|
||||
}
|
||||
|
||||
private fun font(editor: Editor): Font {
|
||||
val editorFont = editor.colorsScheme.getFont(EditorFontType.PLAIN)
|
||||
return UIUtil.getFontWithFallbackIfNeeded(editorFont, lines.joinToString("\n"))
|
||||
.deriveFont(editor.colorsScheme.editorFontSize)
|
||||
}
|
||||
|
||||
override fun paint(inlay: Inlay<*>, g: Graphics, targetRegion: Rectangle, textAttributes: TextAttributes) {
|
||||
val editor = inlay.editor
|
||||
g.color = JBColor.GRAY
|
||||
g.font = font(editor)
|
||||
var additionalYOffset = 0
|
||||
val ascent = editor.ascent
|
||||
val lineHeight = editor.lineHeight
|
||||
for (line in lines) {
|
||||
g.drawString(line, targetRegion.x, targetRegion.y + ascent + additionalYOffset)
|
||||
additionalYOffset += lineHeight
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
package com.github.continuedev.continueintellijextension.autocomplete
|
||||
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
import com.github.continuedev.continueintellijextension.utils.uuid
|
||||
import com.intellij.codeInsight.inline.completion.*
|
||||
import com.intellij.codeInsight.inline.completion.elements.InlineCompletionElement
|
||||
import com.intellij.codeInsight.inline.completion.elements.InlineCompletionGrayTextElement
|
||||
import com.intellij.codeInsight.inline.completion.suggestion.InlineCompletionSingleSuggestion
|
||||
import com.intellij.codeInsight.inline.completion.suggestion.InlineCompletionSuggestion
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.project.Project
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
|
||||
class ContinueInlineCompletionProvider : InlineCompletionProvider {
|
||||
override val id get() = InlineCompletionProviderID("Continue")
|
||||
override val insertHandler: InlineCompletionInsertHandler = NotifyingHandler()
|
||||
private var lastUuid: String? = null
|
||||
private var lastProject: Project? = null
|
||||
|
||||
override fun isEnabled(event: InlineCompletionEvent): Boolean {
|
||||
val isSettingEnabled = ContinueExtensionSettings.instance.continueState.enableTabAutocomplete
|
||||
val isEventOk = event is InlineCompletionEvent.DirectCall
|
||||
|| event is InlineCompletionEvent.DocumentChange
|
||||
|| event is InlineCompletionEvent.LookupChange
|
||||
return isSettingEnabled && isEventOk
|
||||
}
|
||||
|
||||
override suspend fun getSuggestion(request: InlineCompletionRequest): InlineCompletionSuggestion {
|
||||
val editor = request.editor
|
||||
val project = request.file.project
|
||||
lastUuid = uuid()
|
||||
lastProject = project
|
||||
val variant = project.service<CompletionService>().getAutocomplete(
|
||||
lastUuid!!,
|
||||
editor.virtualFile.url,
|
||||
editor.caretModel.primaryCaret.logicalPosition.line,
|
||||
editor.caretModel.primaryCaret.logicalPosition.column
|
||||
)
|
||||
if (variant == null)
|
||||
return InlineCompletionSuggestion.Empty
|
||||
return InlineCompletionSingleSuggestion.build(elements = flowOf(InlineCompletionGrayTextElement(variant)))
|
||||
}
|
||||
|
||||
private inner class NotifyingHandler : DefaultInlineCompletionInsertHandler() {
|
||||
|
||||
override fun afterInsertion(
|
||||
environment: InlineCompletionInsertEnvironment,
|
||||
elements: List<InlineCompletionElement>
|
||||
) {
|
||||
super.afterInsertion(environment, elements)
|
||||
lastProject?.service<CompletionService>()?.acceptAutocomplete(lastUuid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
package com.github.continuedev.continueintellijextension.autocomplete
|
||||
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
import com.intellij.openapi.actionSystem.AnAction
|
||||
import com.intellij.openapi.actionSystem.AnActionEvent
|
||||
import com.intellij.openapi.components.service
|
||||
class DisableTabAutocompleteAction : AnAction() {
|
||||
override fun actionPerformed(e: AnActionEvent) {
|
||||
val continueSettingsService = service<ContinueExtensionSettings>()
|
||||
continueSettingsService.continueState.enableTabAutocomplete = true
|
||||
}
|
||||
}
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
package com.github.continuedev.continueintellijextension.autocomplete
|
||||
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
import com.intellij.openapi.actionSystem.AnAction
|
||||
import com.intellij.openapi.actionSystem.AnActionEvent
|
||||
import com.intellij.openapi.components.service
|
||||
class EnableTabAutocompleteAction : AnAction() {
|
||||
override fun actionPerformed(e: AnActionEvent) {
|
||||
val continueSettingsService = service<ContinueExtensionSettings>()
|
||||
continueSettingsService.continueState.enableTabAutocomplete = true
|
||||
}
|
||||
}
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
package com.github.continuedev.continueintellijextension.autocomplete
|
||||
|
||||
import com.intellij.openapi.actionSystem.DataContext
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.editor.Caret
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.actionSystem.EditorAction
|
||||
import com.intellij.openapi.editor.actionSystem.EditorActionHandler
|
||||
|
||||
class PartialAcceptAutocompleteAction : EditorAction(object : EditorActionHandler() {
|
||||
override fun doExecute(editor: Editor, caret: Caret?, dataContext: DataContext?) {
|
||||
ApplicationManager.getApplication().runWriteAction {
|
||||
editor.project?.service<AutocompleteService>()?.partialAccept()
|
||||
}
|
||||
}
|
||||
|
||||
override fun isEnabledForCaret(editor: Editor, caret: Caret, dataContext: DataContext?): Boolean {
|
||||
val autocompleteService = editor.project?.service<AutocompleteService>();
|
||||
val enabled = editor == autocompleteService?.pendingCompletion?.editor
|
||||
&& caret.offset == autocompleteService.pendingCompletion?.offset
|
||||
&& autocompleteService.pendingCompletion?.text != null
|
||||
return enabled
|
||||
}
|
||||
}) {}
|
||||
|
|
@ -9,13 +9,9 @@ import com.github.continuedev.continueintellijextension.editor.DiffStreamService
|
|||
import com.github.continuedev.continueintellijextension.editor.EditorUtils
|
||||
import com.github.continuedev.continueintellijextension.protocol.ApplyToFileParams
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.project.Project
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.coroutines.resumeWithException
|
||||
|
||||
/**
|
||||
* Handles applying text to a file with streaming diff preview
|
||||
|
|
@ -122,33 +118,9 @@ class ApplyToFileHandler(
|
|||
}
|
||||
|
||||
private suspend fun fetchApplyLLMConfig(): Any? {
|
||||
return try {
|
||||
suspendCancellableCoroutine { continuation ->
|
||||
continuePluginService.coreMessenger?.request(
|
||||
"config/getSerializedProfileInfo", null, null
|
||||
) { response ->
|
||||
try {
|
||||
val selectedModels = response.castNestedOrNull<Map<String, Any>>(
|
||||
"content", "result", "config", "selectedModelByRole"
|
||||
)
|
||||
|
||||
// If "apply" role model is not found, try "chat" role
|
||||
val applyCodeBlockModel = selectedModels?.get("apply") ?: selectedModels?.get("chat")
|
||||
|
||||
if (applyCodeBlockModel != null) {
|
||||
continuation.resume(applyCodeBlockModel)
|
||||
} else {
|
||||
// If neither "apply" nor "chat" models are available, return with exception
|
||||
continuation.resumeWithException(IllegalStateException("No 'apply' or 'chat' model found in configuration."))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
continuation.resumeWithException(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
val selectedModelByRole = project.service<ProfileInfoService>().fetchSelectedModelByRoleOrNull()
|
||||
return selectedModelByRole?.get("apply")
|
||||
?: selectedModelByRole?.get("chat")
|
||||
}
|
||||
|
||||
private fun setupAndStreamDiffs(editorUtils: EditorUtils, llm: Any) {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,63 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`
|
||||
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
|
||||
import com.intellij.openapi.components.Service
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.diagnostic.Logger
|
||||
import com.intellij.openapi.project.Project
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
@Service(Service.Level.PROJECT)
|
||||
class ProfileInfoService(private val project: Project) {
|
||||
private val log = Logger.getInstance(ProfileInfoService::class.java)
|
||||
private var fallbackInfo: Any? = null // todo: add type + deserialize
|
||||
|
||||
suspend fun fetchModelTimeoutOrNull() =
|
||||
fetchOrNull().castNestedOrNull<Double?>(
|
||||
"content",
|
||||
"result",
|
||||
"config",
|
||||
"tabAutocompleteOptions",
|
||||
"modelTimeout"
|
||||
)
|
||||
|
||||
suspend fun fetchSelectedModelByRoleOrNull(): Map<String, Any>? =
|
||||
fetchOrNull().castNestedOrNull<Map<String, Any>>(
|
||||
"content",
|
||||
"result",
|
||||
"config",
|
||||
"selectedModelByRole"
|
||||
)
|
||||
|
||||
suspend fun fetchModelsByRoleOrNull() =
|
||||
fetchOrNull().castNestedOrNull<Map<String, Any>>(
|
||||
"content",
|
||||
"result",
|
||||
"config",
|
||||
"modelsByRole"
|
||||
)
|
||||
|
||||
private suspend fun fetchOrNull(): Any? {
|
||||
val actual = withTimeoutOrNull(1.seconds) {
|
||||
suspendCancellableCoroutine { continuation ->
|
||||
project.service<ContinuePluginService>().coreMessenger?.request(
|
||||
"config/getSerializedProfileInfo",
|
||||
null,
|
||||
null
|
||||
) { response ->
|
||||
continuation.resumeWith(Result.success(response))
|
||||
}
|
||||
}
|
||||
}
|
||||
if (actual == null) {
|
||||
log.warn("Fall back to previous settings due to timeout")
|
||||
return fallbackInfo
|
||||
}
|
||||
fallbackInfo = actual
|
||||
return actual
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -2,8 +2,8 @@ package com.github.continuedev.continueintellijextension.editor
|
|||
|
||||
import com.github.continuedev.continueintellijextension.Icons
|
||||
import com.github.continuedev.continueintellijextension.`continue`.GetTheme
|
||||
import com.github.continuedev.continueintellijextension.`continue`.ProfileInfoService
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
|
||||
import com.github.continuedev.continueintellijextension.utils.getMetaKeyLabel
|
||||
import com.github.continuedev.continueintellijextension.utils.getShiftKeyLabel
|
||||
|
|
@ -14,12 +14,13 @@ import com.intellij.openapi.editor.colors.EditorColorsManager
|
|||
import com.intellij.openapi.editor.colors.EditorFontType
|
||||
import com.intellij.openapi.editor.impl.EditorImpl
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.util.IconLoader
|
||||
import com.intellij.openapi.util.Ref
|
||||
import com.intellij.openapi.util.TextRange
|
||||
import com.intellij.ui.JBColor
|
||||
import com.intellij.util.ui.JBUI
|
||||
import com.intellij.util.ui.UIUtil
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import java.awt.*
|
||||
import java.awt.event.*
|
||||
import java.awt.geom.AffineTransform
|
||||
|
|
@ -34,6 +35,7 @@ import kotlin.math.max
|
|||
import net.miginfocom.swing.MigLayout
|
||||
import org.jdesktop.swingx.JXPanel
|
||||
import org.jdesktop.swingx.JXTextArea
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
|
||||
const val MAIN_FONT_SIZE = 13
|
||||
const val DOWN_ARROW = " ▾"
|
||||
|
|
@ -43,37 +45,21 @@ const val MAX_MODEL_WAIT_TIME = 1500
|
|||
* Fetches and combines available model titles from both "edit" and "chat" roles.
|
||||
* Edit models are prioritized and appear first in the returned list.
|
||||
* Handles duplicate models by only including them once (prioritizing edit role).
|
||||
*
|
||||
* @param continuePluginService The service used to fetch config information
|
||||
* @return List of model titles with edit models first, duplicates removed
|
||||
* @throws No exceptions, but will return empty list if request fails or times out after 1.5 seconds
|
||||
*/
|
||||
fun getModelTitles(continuePluginService: ContinuePluginService): List<String> {
|
||||
val modelTitles = mutableListOf<String>()
|
||||
|
||||
continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
|
||||
val modelsByRole =
|
||||
response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "modelsByRole") ?: return@request
|
||||
|
||||
// Get edit models first
|
||||
val editModels = modelsByRole.castNestedOrNull<List<*>>("edit")
|
||||
?.mapNotNull { it.castNestedOrNull<String>("title") } ?: emptyList()
|
||||
|
||||
// Then get chat models
|
||||
val chatModels = modelsByRole.castNestedOrNull<List<*>>("chat")
|
||||
?.mapNotNull { it.castNestedOrNull<String>("title") } ?: emptyList()
|
||||
|
||||
// Add edit models first, then chat models (avoiding duplicates)
|
||||
modelTitles.addAll(editModels)
|
||||
modelTitles.addAll(chatModels.filter { it !in editModels })
|
||||
fun getModelTitles(project: Project): List<String> {
|
||||
// fixme: blocking code on EDT (however this is not a regression compared to the latest changes)
|
||||
return runBlocking {
|
||||
withTimeoutOrNull(MAX_MODEL_WAIT_TIME.milliseconds) {
|
||||
val modelsByRole = project.service<ProfileInfoService>().fetchModelsByRoleOrNull()
|
||||
val editModels = modelsByRole.castNestedOrNull<List<*>>("edit")
|
||||
?.mapNotNull { it.castNestedOrNull<String>("title") }
|
||||
?: emptyList()
|
||||
val chatModels = modelsByRole.castNestedOrNull<List<*>>("chat")
|
||||
?.mapNotNull { it.castNestedOrNull<String>("title") }
|
||||
?: emptyList()
|
||||
(editModels + chatModels).distinct()
|
||||
} ?: emptyList()
|
||||
}
|
||||
|
||||
val startTime = System.currentTimeMillis()
|
||||
while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < MAX_MODEL_WAIT_TIME) {
|
||||
Thread.sleep(20)
|
||||
}
|
||||
|
||||
return modelTitles
|
||||
}
|
||||
|
||||
fun makeTextArea(): JTextArea {
|
||||
|
|
@ -161,8 +147,7 @@ fun openInlineEdit(project: Project?, editor: Editor) {
|
|||
|
||||
val manager = EditorComponentInlaysManager.from(editor, true)
|
||||
|
||||
val continuePluginService = project.service<ContinuePluginService>()
|
||||
val modelTitles = getModelTitles(continuePluginService)
|
||||
val modelTitles = getModelTitles(project)
|
||||
|
||||
val highlightedRIF = editorUtils.getHighlightedRIF() ?: return
|
||||
val (startLineNumber, endLineNumber) = highlightedRIF.lines
|
||||
|
|
|
|||
|
|
@ -1,25 +0,0 @@
|
|||
package com.github.continuedev.continueintellijextension.nextEdit
|
||||
|
||||
import com.intellij.openapi.actionSystem.DataContext
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.editor.Caret
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.actionSystem.EditorAction
|
||||
import com.intellij.openapi.editor.actionSystem.EditorActionHandler
|
||||
|
||||
class AcceptNextEditAction : EditorAction(object : EditorActionHandler() {
|
||||
override fun doExecute(editor: Editor, caret: Caret?, dataContext: DataContext?) {
|
||||
ApplicationManager.getApplication().runWriteAction {
|
||||
editor.project?.service<NextEditService>()?.accept()
|
||||
}
|
||||
}
|
||||
|
||||
override fun isEnabledForCaret(editor: Editor, caret: Caret, dataContext: DataContext?): Boolean {
|
||||
val nextEditService = editor.project?.service<NextEditService>();
|
||||
val enabled = editor == nextEditService?.pendingCompletion?.editor
|
||||
// && caret.offset == autocompleteService.pendingCompletion?.offset
|
||||
&& nextEditService.pendingCompletion?.text != null
|
||||
return enabled
|
||||
}
|
||||
})
|
||||
|
|
@ -1,321 +0,0 @@
|
|||
package com.github.continuedev.continueintellijextension.nextEdit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.FimResult
|
||||
import com.github.continuedev.continueintellijextension.autocomplete.AutocompleteLookupListener
|
||||
import com.github.continuedev.continueintellijextension.autocomplete.AutocompleteSpinnerWidget
|
||||
import com.github.continuedev.continueintellijextension.autocomplete.ContinueInlayRenderer
|
||||
import com.github.continuedev.continueintellijextension.autocomplete.PendingCompletion
|
||||
import com.github.continuedev.continueintellijextension.autocomplete.addInlayElement
|
||||
import com.github.continuedev.continueintellijextension.autocomplete.isInjectedText
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.github.continuedev.continueintellijextension.utils.checkFim
|
||||
import com.github.continuedev.continueintellijextension.utils.toUriOrNull
|
||||
import com.github.continuedev.continueintellijextension.utils.uuid
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.application.WriteAction
|
||||
import com.intellij.openapi.application.invokeLater
|
||||
import com.intellij.openapi.application.runReadAction
|
||||
import com.intellij.openapi.components.Service
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.InlayProperties
|
||||
import com.intellij.openapi.fileEditor.FileDocumentManager
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.util.TextRange
|
||||
import com.intellij.openapi.wm.WindowManager
|
||||
import com.intellij.psi.PsiDocumentManager
|
||||
|
||||
@Service(Service.Level.PROJECT)
|
||||
class NextEditService(private val project: Project) {
|
||||
var pendingCompletion: PendingCompletion? = null
|
||||
private val autocompleteLookupListener = project.service<AutocompleteLookupListener>()
|
||||
private val widget: AutocompleteSpinnerWidget? by lazy {
|
||||
WindowManager.getInstance().getStatusBar(project)
|
||||
?.getWidget(AutocompleteSpinnerWidget.ID) as? AutocompleteSpinnerWidget
|
||||
}
|
||||
|
||||
// To avoid triggering another completion on partial acceptance,
|
||||
// we need to keep track of whether the last change was a partial accept.
|
||||
var lastChangeWasPartialAccept = false
|
||||
|
||||
fun triggerNextEdit(editor: Editor) {
|
||||
val settings = service<ContinueExtensionSettings>()
|
||||
if (!settings.continueState.enableTabAutocomplete) {
|
||||
return
|
||||
}
|
||||
|
||||
if (pendingCompletion != null) {
|
||||
clearCompletions(pendingCompletion!!.editor)
|
||||
}
|
||||
|
||||
// Set pending completion.
|
||||
val completionId = uuid()
|
||||
val offset = editor.caretModel.primaryCaret.offset
|
||||
pendingCompletion = PendingCompletion(editor, offset, completionId, null)
|
||||
|
||||
// Request a completion from the core.
|
||||
val virtualFile = FileDocumentManager.getInstance().getFile(editor.document)
|
||||
|
||||
val uri = virtualFile?.toUriOrNull() ?: return
|
||||
|
||||
widget?.setLoading(true)
|
||||
|
||||
val line = editor.caretModel.primaryCaret.logicalPosition.line
|
||||
val column = editor.caretModel.primaryCaret.logicalPosition.column
|
||||
val input = mapOf(
|
||||
"completionId" to completionId,
|
||||
"filepath" to uri,
|
||||
"pos" to mapOf(
|
||||
"line" to line,
|
||||
"character" to column
|
||||
),
|
||||
"clipboardText" to "",
|
||||
"recentlyEditedRanges" to emptyList<Any>(),
|
||||
"recentlyVisitedRanges" to emptyList<Any>(),
|
||||
)
|
||||
|
||||
// TODO: Add message support for nextEdit/predict.
|
||||
project.service<ContinuePluginService>().coreMessenger?.request(
|
||||
"nextEdit/predict",
|
||||
input,
|
||||
null,
|
||||
({ response ->
|
||||
if (pendingCompletion == null || pendingCompletion?.completionId == completionId) {
|
||||
widget?.setLoading(false)
|
||||
}
|
||||
|
||||
val responseObject = response as Map<*, *>
|
||||
val predictions = responseObject["content"] as List<*>
|
||||
|
||||
if (predictions.isNotEmpty()) {
|
||||
val prediction = predictions[0].toString()
|
||||
val oldEditRange = predictions[1].toString()
|
||||
// Check if the prediction is purely additive.
|
||||
val result = checkFim(
|
||||
oldEditRange,
|
||||
prediction,
|
||||
Pair(line, column)
|
||||
)
|
||||
when (result) {
|
||||
is FimResult.FimEdit -> {
|
||||
// If so, render ghost text.
|
||||
val finalTextToInsert = deduplicateCompletion(editor, offset, result.fimText)
|
||||
if (shouldRenderCompletion(finalTextToInsert, offset, line, editor)) {
|
||||
renderCompletion(editor, offset, finalTextToInsert)
|
||||
pendingCompletion = PendingCompletion(editor, offset, completionId, finalTextToInsert)
|
||||
}
|
||||
}
|
||||
is FimResult.NotFimEdit -> {
|
||||
// Else, render a window.
|
||||
if (shouldRenderCompletion(prediction, offset, line, editor)) {
|
||||
val nextEditWindowService = NextEditWindowService.getInstance(project)
|
||||
nextEditWindowService.showCodePreview(prediction, editor, completionId)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
private fun shouldRenderCompletion(completion: String, offset: Int, line: Int, editor: Editor): Boolean {
|
||||
if (completion.isEmpty() || runReadAction { offset != editor.caretModel.offset }) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (completion.lines().size == 1) {
|
||||
return true
|
||||
}
|
||||
|
||||
val endOffset = editor.document.getLineEndOffset(line)
|
||||
|
||||
// Do not render if completion is multi-line and caret is in middle of line
|
||||
return offset <= endOffset && editor.document.getText(TextRange(offset, endOffset)).isBlank()
|
||||
}
|
||||
|
||||
private fun deduplicateCompletion(editor: Editor, offset: Int, completion: String): String {
|
||||
// Check if completion matches the first 10 characters after the cursor
|
||||
return ApplicationManager.getApplication().runReadAction<String> {
|
||||
val document = editor.document
|
||||
val caretOffset = editor.caretModel.offset
|
||||
|
||||
// Don't care about it if it's at the end of the document
|
||||
if (caretOffset == document.textLength) return@runReadAction completion
|
||||
|
||||
val N = 10
|
||||
var textAfterCursor = if (caretOffset + N <= document.textLength) {
|
||||
document.getText(TextRange(caretOffset, caretOffset + N))
|
||||
} else {
|
||||
document.getText(TextRange(caretOffset, document.textLength))
|
||||
}
|
||||
|
||||
// Avoid truncating the completion text when the text after the cursor is blank
|
||||
if (textAfterCursor.isBlank()) return@runReadAction completion
|
||||
|
||||
// Determine the index of a newline character within the text following the cursor.
|
||||
val newlineIndex = textAfterCursor.indexOf("\r\n").takeIf { it >= 0 } ?: textAfterCursor.indexOf('\n')
|
||||
// If a newline character is found and the current line is not empty, truncate the text at that point.
|
||||
if (newlineIndex > 0) {
|
||||
textAfterCursor = textAfterCursor.substring(0, newlineIndex)
|
||||
}
|
||||
|
||||
val indexOfTextAfterCursorInCompletion = completion.indexOf(textAfterCursor)
|
||||
if (indexOfTextAfterCursorInCompletion > 0) {
|
||||
return@runReadAction completion.slice(0..indexOfTextAfterCursorInCompletion - 1)
|
||||
} else if (indexOfTextAfterCursorInCompletion == 0) {
|
||||
return@runReadAction ""
|
||||
}
|
||||
|
||||
return@runReadAction completion
|
||||
}
|
||||
}
|
||||
|
||||
private fun renderCompletion(editor: Editor, offset: Int, completion: String) {
|
||||
if (completion.isEmpty()) {
|
||||
return
|
||||
}
|
||||
if (isInjectedFile(editor)) return
|
||||
// Skip rendering completions if the code completion dropdown is already visible and the IDE completion side-by-side setting is disabled
|
||||
if (shouldSkipRender()) {
|
||||
return
|
||||
}
|
||||
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
WriteAction.run<Throwable> {
|
||||
// Clear existing completions
|
||||
hideCompletions(editor)
|
||||
|
||||
val properties = InlayProperties()
|
||||
properties.relatesToPrecedingText(true)
|
||||
properties.disableSoftWrapping(true)
|
||||
|
||||
val lines = completion.lines()
|
||||
pendingCompletion = pendingCompletion?.copy(text = lines.joinToString("\n"))
|
||||
editor.addInlayElement(lines, offset, properties)
|
||||
|
||||
// val attributes = TextAttributes().apply {
|
||||
// backgroundColor = JBColor.GREEN
|
||||
// }
|
||||
// val key = TextAttributesKey.createTextAttributesKey("CONTINUE_AUTOCOMPLETE")
|
||||
// key.let { editor.colorsScheme.setAttributes(it, attributes) }
|
||||
// editor.markupModel.addLineHighlighter(key, editor.caretModel.logicalPosition.line, HighlighterLayer.LAST)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun accept() {
|
||||
val completion = pendingCompletion ?: return
|
||||
val text = completion.text ?: return
|
||||
val editor = completion.editor
|
||||
val offset = completion.offset
|
||||
editor.document.insertString(offset, text)
|
||||
|
||||
editor.caretModel.moveToOffset(offset + text.length)
|
||||
|
||||
project.service<ContinuePluginService>().coreMessenger?.request(
|
||||
"nextEdit/accept",
|
||||
hashMapOf("completionId" to completion.completionId),
|
||||
null,
|
||||
({})
|
||||
)
|
||||
invokeLater {
|
||||
clearCompletions(editor, completion)
|
||||
}
|
||||
}
|
||||
|
||||
private fun shouldSkipRender(): Boolean {
|
||||
val settings = service<ContinueExtensionSettings>()
|
||||
return !settings.continueState.showIDECompletionSideBySide && !autocompleteLookupListener.isLookupEmpty()
|
||||
}
|
||||
|
||||
private fun splitKeepingDelimiters(input: String, delimiterPattern: String = "\\s+"): List<String> {
|
||||
val initialSplit = input.split("(?<=$delimiterPattern)|(?=$delimiterPattern)".toRegex())
|
||||
.filter { it.isNotEmpty() }
|
||||
|
||||
val result = mutableListOf<String>()
|
||||
var currentDelimiter = ""
|
||||
|
||||
for (part in initialSplit) {
|
||||
if (part.matches(delimiterPattern.toRegex())) {
|
||||
currentDelimiter += part
|
||||
} else {
|
||||
if (currentDelimiter.isNotEmpty()) {
|
||||
result.add(currentDelimiter)
|
||||
currentDelimiter = ""
|
||||
}
|
||||
result.add(part)
|
||||
}
|
||||
}
|
||||
|
||||
if (currentDelimiter.isNotEmpty()) {
|
||||
result.add(currentDelimiter)
|
||||
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
fun partialAccept() {
|
||||
val completion = pendingCompletion ?: return
|
||||
val text = completion.text ?: return
|
||||
val editor = completion.editor
|
||||
val offset = completion.offset
|
||||
|
||||
lastChangeWasPartialAccept = true
|
||||
|
||||
// Split the text into words, keeping delimiters
|
||||
val words = splitKeepingDelimiters(text)
|
||||
println(words)
|
||||
val word = words[0]
|
||||
editor.document.insertString(offset, word)
|
||||
editor.caretModel.moveToOffset(offset + word.length)
|
||||
|
||||
// Remove the completion and re-display it
|
||||
hideCompletions(editor)
|
||||
completion.text = text.substring(word.length)
|
||||
completion.offset += word.length
|
||||
renderCompletion(editor, completion.offset, completion.text!!)
|
||||
}
|
||||
|
||||
private fun rejectCompletion(completion: PendingCompletion) {
|
||||
// Send rejection message to core
|
||||
widget?.setLoading(false)
|
||||
project.service<ContinuePluginService>().coreMessenger?.request("nextEdit/reject", null, null, ({}))
|
||||
}
|
||||
|
||||
fun clearCompletions(editor: Editor, completion: PendingCompletion? = pendingCompletion) {
|
||||
if (isInjectedFile(editor)) return
|
||||
|
||||
if (completion != null) {
|
||||
// cancelCompletion(completion)
|
||||
if (completion.completionId == pendingCompletion?.completionId) pendingCompletion = null
|
||||
}
|
||||
disposeInlayRenderer(editor)
|
||||
}
|
||||
|
||||
private fun isInjectedFile(editor: Editor): Boolean {
|
||||
return runReadAction {
|
||||
PsiDocumentManager.getInstance(project).getPsiFile(editor.document)?.isInjectedText() ?: false
|
||||
}
|
||||
}
|
||||
|
||||
fun hideCompletions(editor: Editor) {
|
||||
if (isInjectedFile(editor)) return
|
||||
|
||||
disposeInlayRenderer(editor)
|
||||
}
|
||||
|
||||
private fun disposeInlayRenderer(editor: Editor) {
|
||||
editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength).forEach {
|
||||
if (it.renderer is ContinueInlayRenderer) {
|
||||
it.dispose()
|
||||
}
|
||||
}
|
||||
editor.inlayModel.getBlockElementsInRange(0, editor.document.textLength).forEach {
|
||||
if (it.renderer is ContinueInlayRenderer) {
|
||||
it.dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,304 +0,0 @@
|
|||
package com.github.continuedev.continueintellijextension.nextEdit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.intellij.openapi.actionSystem.AnAction
|
||||
import com.intellij.openapi.actionSystem.AnActionEvent
|
||||
import com.intellij.openapi.actionSystem.CustomShortcutSet
|
||||
import com.intellij.openapi.command.WriteCommandAction
|
||||
import com.intellij.openapi.components.Service
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.editor.Document
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.EditorSettings
|
||||
import com.intellij.openapi.editor.colors.EditorColorsManager
|
||||
import com.intellij.openapi.editor.ex.EditorEx
|
||||
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
|
||||
import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory
|
||||
import com.intellij.openapi.fileEditor.FileDocumentManager
|
||||
import com.intellij.openapi.fileTypes.FileTypeManager
|
||||
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.ui.popup.JBPopupFactory
|
||||
import com.intellij.openapi.ui.popup.JBPopupListener
|
||||
import com.intellij.openapi.ui.popup.LightweightWindowEvent
|
||||
import com.intellij.psi.PsiDocumentManager
|
||||
import com.intellij.ui.EditorTextField
|
||||
import com.intellij.ui.components.JBScrollPane
|
||||
import java.awt.BorderLayout
|
||||
import java.awt.Color
|
||||
import java.awt.Dimension
|
||||
import java.awt.FlowLayout
|
||||
import java.awt.Point
|
||||
import java.awt.event.ActionEvent
|
||||
import java.awt.event.KeyAdapter
|
||||
import java.awt.event.KeyEvent
|
||||
import javax.swing.AbstractAction
|
||||
import javax.swing.JButton
|
||||
import javax.swing.JComponent
|
||||
import javax.swing.JPanel
|
||||
import javax.swing.JScrollPane
|
||||
import javax.swing.KeyStroke
|
||||
|
||||
@Service(Service.Level.PROJECT)
|
||||
class NextEditWindowService(private val project: Project) {
|
||||
/**
|
||||
* Creates a Swing component that displays syntax-highlighted code.
|
||||
*
|
||||
* @param code The code to display
|
||||
* @param language The language/file extension of the code (e.g. "java", "kotlin", "py")
|
||||
* @param isEditable Whether the code should be editable (default: false)
|
||||
* @return A JComponent that can be added to the UI
|
||||
*/
|
||||
fun createCodeViewer(code: String, language: String, document: Document, isEditable: Boolean = false): JComponent {
|
||||
// Get file type based on extension.
|
||||
// NOTE: This is actually IDE and tier-dependent. For example, TypeScript won't work on IntelliJ CE.
|
||||
val fileType = FileTypeManager.getInstance().getFileTypeByExtension(language)
|
||||
|
||||
// Create an EditorTextField with the specified code and file type.
|
||||
val editorTextField = object : EditorTextField(code, project, fileType) {
|
||||
override fun createEditor(): EditorEx {
|
||||
val editor = super.createEditor()
|
||||
|
||||
// Configure editor settings.
|
||||
val settings: EditorSettings = editor.settings
|
||||
settings.isLineNumbersShown = true
|
||||
settings.isLineMarkerAreaShown = true
|
||||
settings.isIndentGuidesShown = true
|
||||
settings.isVirtualSpace = false
|
||||
settings.isRightMarginShown = false
|
||||
settings.additionalLinesCount = 0
|
||||
settings.isShowingSpecialChars = false
|
||||
settings.isCaretRowShown = true
|
||||
|
||||
// Set read-only if not editable.
|
||||
editor.isViewer = !isEditable
|
||||
|
||||
// Syntax highlighter.
|
||||
// Get current editor color scheme.
|
||||
val currentScheme = EditorColorsManager.getInstance().globalScheme
|
||||
|
||||
// Apply syntax highlighting with current theme.
|
||||
val virtualFile = FileDocumentManager.getInstance().getFile(document)
|
||||
var syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(fileType, project, virtualFile)
|
||||
|
||||
// If we couldn't get a syntax highlighter from the file, try to get one just from the file type.
|
||||
if (syntaxHighlighter == null) {
|
||||
syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(fileType, project, null)
|
||||
}
|
||||
|
||||
// If we have a highlighter, apply it.
|
||||
if (syntaxHighlighter != null) {
|
||||
editor.highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(
|
||||
syntaxHighlighter,
|
||||
currentScheme
|
||||
)
|
||||
} else {
|
||||
// Fallback to plain text highlighting if all attempts fail.
|
||||
val plainTextFileType = FileTypeManager.getInstance().getFileTypeByExtension("txt")
|
||||
editor.highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(
|
||||
project,
|
||||
plainTextFileType
|
||||
)
|
||||
}
|
||||
|
||||
// Apply the theme's background color.
|
||||
editor.backgroundColor = currentScheme.defaultBackground
|
||||
|
||||
return editor
|
||||
}
|
||||
|
||||
// Override to ensure multi-line support.
|
||||
override fun getPreferredSize(): Dimension {
|
||||
val lineCount = code.lines().size
|
||||
// Adjust height based on line count (with some minimum).
|
||||
val preferredSize = super.getPreferredSize()
|
||||
val lineHeight = preferredSize.height / (if (lineCount > 0) lineCount else 1)
|
||||
val newHeight = lineHeight * (if (lineCount > 0) lineCount else 1) + 10 // Add padding
|
||||
return Dimension(preferredSize.width, newHeight)
|
||||
}
|
||||
}
|
||||
|
||||
// Enable multi-line mode.
|
||||
editorTextField.setOneLineMode(false)
|
||||
|
||||
// Wrap in a scroll pane for larger code blocks.
|
||||
val panel = JPanel(BorderLayout())
|
||||
panel.add(JBScrollPane(editorTextField), BorderLayout.CENTER)
|
||||
|
||||
return panel
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a popup dialog with the code preview.
|
||||
*/
|
||||
fun showCodePreview(code: String, parentEditor: Editor, completionId: String) {
|
||||
// Use invokeAndWait or invokeLater to ensure we're on the EDT.
|
||||
com.intellij.openapi.application.ApplicationManager.getApplication().invokeLater {
|
||||
val codeViewer = createCodeViewer(code, getFileLanguage(parentEditor.document), parentEditor.document)
|
||||
|
||||
// Create a button panel.
|
||||
val buttonPanel = JPanel(FlowLayout(FlowLayout.RIGHT))
|
||||
val acceptButton = JButton("Accept (Tab)")
|
||||
val dismissButton = JButton("Dismiss (Esc)")
|
||||
buttonPanel.add(acceptButton)
|
||||
buttonPanel.add(dismissButton)
|
||||
|
||||
// Create a panel to hold the code viewer and buttons.
|
||||
val panel = JPanel(BorderLayout())
|
||||
panel.add(codeViewer, BorderLayout.CENTER)
|
||||
panel.add(buttonPanel, BorderLayout.SOUTH)
|
||||
|
||||
|
||||
// Create the popup.
|
||||
val popup = JBPopupFactory.getInstance()
|
||||
.createComponentPopupBuilder(panel, codeViewer)
|
||||
.setMovable(true)
|
||||
.setResizable(true)
|
||||
.setRequestFocus(true)
|
||||
.setCancelOnClickOutside(true)
|
||||
.setCancelOnOtherWindowOpen(true)
|
||||
.setFocusable(true)
|
||||
.addListener(object : JBPopupListener {
|
||||
override fun onClosed(event: LightweightWindowEvent) {
|
||||
if (!event.isOk) {
|
||||
// This only triggers when dismissed, not when accepted.
|
||||
println("Dismissing code preview popup")
|
||||
project.service<ContinuePluginService>().coreMessenger?.request(
|
||||
"nextEdit/reject",
|
||||
hashMapOf("completionId" to completionId),
|
||||
null, ({})
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
.createPopup()
|
||||
|
||||
// Helper function to accept the code and apply it to the editor.
|
||||
fun acceptCode() {
|
||||
val document = parentEditor.document
|
||||
val caretModel = parentEditor.caretModel
|
||||
val caretOffset = caretModel.offset
|
||||
val caretPosition = document.getLineNumber(caretOffset)
|
||||
|
||||
// Calculate start and end lines.
|
||||
val totalLines = document.lineCount
|
||||
val startLine = maxOf(0, caretPosition - 5)
|
||||
val endLine = minOf(totalLines - 1, caretPosition + 5)
|
||||
|
||||
// Get start and end offsets.
|
||||
val startOffset = document.getLineStartOffset(startLine)
|
||||
val endOffset = document.getLineEndOffset(endLine)
|
||||
|
||||
// Write command to replace the text.
|
||||
WriteCommandAction.runWriteCommandAction(project) {
|
||||
document.replaceString(startOffset, endOffset, code)
|
||||
}
|
||||
|
||||
project.service<ContinuePluginService>().coreMessenger?.request(
|
||||
"nextEdit/accept",
|
||||
hashMapOf("completionId" to completionId),
|
||||
null, ({})
|
||||
)
|
||||
}
|
||||
|
||||
// Use ActionManager to handle Tab key globally during popup display.
|
||||
val acceptAction = object : AnAction() {
|
||||
override fun actionPerformed(e: AnActionEvent) {
|
||||
acceptCode()
|
||||
popup.closeOk(null)
|
||||
}
|
||||
}
|
||||
|
||||
// Create a custom shortcut set for the Tab key.
|
||||
val customShortcutSet = CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0))
|
||||
|
||||
|
||||
// Register action with shortcut.
|
||||
acceptAction.registerCustomShortcutSet(customShortcutSet, panel)
|
||||
|
||||
// Add button actions.
|
||||
acceptButton.addActionListener {
|
||||
acceptCode()
|
||||
popup.closeOk(null)
|
||||
}
|
||||
|
||||
dismissButton.addActionListener {
|
||||
popup.cancel()
|
||||
}
|
||||
|
||||
// Get the exact position of the cursor.
|
||||
val visualPosition = parentEditor.caretModel.visualPosition
|
||||
val cursorPoint = parentEditor.visualPositionToXY(visualPosition)
|
||||
|
||||
// Convert to screen coordinates.
|
||||
val editorComponent = parentEditor.component
|
||||
val locationOnScreen = editorComponent.locationOnScreen
|
||||
val screenPoint = Point(
|
||||
locationOnScreen.x + cursorPoint.x,
|
||||
locationOnScreen.y + cursorPoint.y
|
||||
)
|
||||
|
||||
// Show the popup at the cursor position.
|
||||
popup.showInScreenCoordinates(editorComponent, screenPoint)
|
||||
|
||||
// Ensure proper focus for keyboard shortcuts.
|
||||
codeViewer.requestFocusInWindow()
|
||||
}
|
||||
}
|
||||
|
||||
// Move editorConfig to a proper instance property that gets actual editor settings.
|
||||
private val editorConfig: EditorConfig by lazy {
|
||||
val settings = EditorSettingsExternalizable.getInstance()
|
||||
val editorFontSize = EditorColorsManager.getInstance().globalScheme.editorFontSize
|
||||
val editorFontFamily = EditorColorsManager.getInstance().globalScheme.editorFontName
|
||||
|
||||
EditorConfig(
|
||||
fontSize = editorFontSize.toDouble(),
|
||||
fontFamily = editorFontFamily
|
||||
)
|
||||
}
|
||||
|
||||
// Data class to hold editor configuration.
|
||||
private data class EditorConfig(
|
||||
val fontSize: Double = 14.0,
|
||||
val fontFamily: String = "JetBrains Mono"
|
||||
)
|
||||
|
||||
/**
|
||||
* Convenience method to map common programming languages to their file extensions.
|
||||
*/
|
||||
fun mapLanguageToExtension(language: String): String {
|
||||
return when (language.lowercase()) {
|
||||
"javascript" -> "js"
|
||||
"typescript" -> "ts"
|
||||
"python" -> "py"
|
||||
"java" -> "java"
|
||||
"kotlin" -> "kt"
|
||||
"c++" -> "cpp"
|
||||
"c#" -> "cs"
|
||||
"go" -> "go"
|
||||
"rust" -> "rs"
|
||||
"ruby" -> "rb"
|
||||
"php" -> "php"
|
||||
"swift" -> "swift"
|
||||
"shell", "bash" -> "sh"
|
||||
"html" -> "html"
|
||||
"css" -> "css"
|
||||
"json" -> "json"
|
||||
"xml" -> "xml"
|
||||
"yaml", "yml" -> "yaml"
|
||||
"markdown", "md" -> "md"
|
||||
// Add more mappings as needed
|
||||
else -> language
|
||||
}
|
||||
}
|
||||
|
||||
private fun getFileLanguage(document: Document): String {
|
||||
val virtualFile = FileDocumentManager.getInstance().getFile(document)
|
||||
return virtualFile?.extension?.lowercase() ?: "text"
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun getInstance(project: Project): NextEditWindowService = project.service()
|
||||
}
|
||||
}
|
||||
|
|
@ -15,8 +15,6 @@
|
|||
</depends>
|
||||
|
||||
<extensions defaultExtensionNs="com.intellij">
|
||||
<editorFactoryListener
|
||||
implementation="com.github.continuedev.continueintellijextension.autocomplete.AutocompleteEditorListener"/>
|
||||
<toolWindow id="Continue" anchor="right" icon="com.github.continuedev.continueintellijextension.Icons.Continue"
|
||||
factoryClass="com.github.continuedev.continueintellijextension.toolWindow.ContinuePluginToolWindowFactory"/>
|
||||
<projectService id="ContinuePluginService"
|
||||
|
|
@ -24,12 +22,11 @@
|
|||
<projectService
|
||||
id="DiffStreamService"
|
||||
serviceImplementation="com.github.continuedev.continueintellijextension.editor.DiffStreamService"/>
|
||||
<projectService
|
||||
id="AutocompleteLookupListener"
|
||||
serviceImplementation="com.github.continuedev.continueintellijextension.autocomplete.AutocompleteLookupListener"/>
|
||||
<statusBarWidgetFactory
|
||||
implementation="com.github.continuedev.continueintellijextension.autocomplete.AutocompleteSpinnerWidgetFactory"
|
||||
id="AutocompleteSpinnerWidget"/>
|
||||
|
||||
<projectService serviceInterface="com.github.continuedev.continueintellijextension.autocomplete.CompletionService"
|
||||
serviceImplementation="com.github.continuedev.continueintellijextension.autocomplete.ContinueCompletionService"/>
|
||||
<inline.completion.provider id="Continue" implementation="com.github.continuedev.continueintellijextension.autocomplete.ContinueInlineCompletionProvider"/>
|
||||
|
||||
<notificationGroup id="Continue"
|
||||
displayType="BALLOON"/>
|
||||
<actionPromoter order="last"
|
||||
|
|
@ -174,33 +171,5 @@
|
|||
<add-to-group group-id="EditorPopupMenu"/>
|
||||
<override-text place="GoToAction" text="Continue: Add Highlighted Code to Context and Clear Chat"/>
|
||||
</action>
|
||||
|
||||
<action id="com.github.continuedev.continueintellijextension.autocomplete.AcceptAutocompleteAction"
|
||||
class="com.github.continuedev.continueintellijextension.autocomplete.AcceptAutocompleteAction"
|
||||
text="Accept Autocomplete Suggestion" description="Accept Autocomplete Suggestion">
|
||||
<keyboard-shortcut keymap="$default" first-keystroke="TAB"/>
|
||||
<keyboard-shortcut keymap="Mac OS X" first-keystroke="TAB"/>
|
||||
</action>
|
||||
|
||||
<action id="com.github.continuedev.continueintellijextension.nextEdit.AcceptNextEditAction"
|
||||
class="com.github.continuedev.continueintellijextension.nextEdit.AcceptNextEditAction"
|
||||
text="Accept Autocomplete Suggestion" description="Accept Next Edit Prediction">
|
||||
<keyboard-shortcut keymap="$default" first-keystroke="TAB"/>
|
||||
<keyboard-shortcut keymap="Mac OS X" first-keystroke="TAB"/>
|
||||
</action>
|
||||
|
||||
<action id="com.github.continuedev.continueintellijextension.autocomplete.CancelAutocompleteAction"
|
||||
class="com.github.continuedev.continueintellijextension.autocomplete.CancelAutocompleteAction"
|
||||
text="Cancel Autocomplete Suggestion" description="Cancel Autocomplete Suggestion">
|
||||
<keyboard-shortcut keymap="$default" first-keystroke="ESCAPE"/>
|
||||
</action>
|
||||
|
||||
<action id="com.github.continuedev.continueintellijextension.autocomplete.PartialAcceptAutocompleteAction"
|
||||
class="com.github.continuedev.continueintellijextension.autocomplete.PartialAcceptAutocompleteAction"
|
||||
text="Partial Accept Autocomplete Suggestion"
|
||||
description="Partial Accept Autocomplete Suggestion">
|
||||
<keyboard-shortcut first-keystroke="control alt RIGHT" keymap="$default"/>
|
||||
<keyboard-shortcut first-keystroke="alt meta RIGHT" keymap="Mac OS X"/>
|
||||
</action>
|
||||
</actions>
|
||||
</idea-plugin>
|
||||
|
|
|
|||
|
|
@ -28,13 +28,11 @@ class Autocomplete {
|
|||
|
||||
@BeforeEach
|
||||
fun waitForIde(remoteRobot: RemoteRobot) {
|
||||
System.setProperty("continue.autocomplete.test.environment", "true")
|
||||
waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") }
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
fun closeProject(remoteRobot: RemoteRobot) {
|
||||
System.clearProperty("continue.autocomplete.test.environment")
|
||||
CommonSteps(remoteRobot).closeProject()
|
||||
}
|
||||
|
||||
|
|
@ -54,7 +52,7 @@ class Autocomplete {
|
|||
// Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus.
|
||||
waitFor(ofSeconds(20)) {
|
||||
findAll<ComponentFixture>(
|
||||
byXpath("//div[@accessiblename='Main.java' and @class='SingleHeightLabel']")
|
||||
byXpath("//div[@visible_text='Main.java']")
|
||||
).isNotEmpty()
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
package com.github.continuedev.continueintellijextension.unit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.ApplyState
|
||||
import com.github.continuedev.continueintellijextension.ApplyStateStatus
|
||||
import com.github.continuedev.continueintellijextension.IDE
|
||||
import com.github.continuedev.continueintellijextension.ApplyState
|
||||
import com.github.continuedev.continueintellijextension.`continue`.ApplyToFileHandler
|
||||
import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger
|
||||
import com.github.continuedev.continueintellijextension.editor.DiffStreamService
|
||||
|
|
@ -11,12 +11,12 @@ import com.github.continuedev.continueintellijextension.protocol.ApplyToFilePara
|
|||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.project.Project
|
||||
import io.mockk.*
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import io.mockk.verify
|
||||
import junit.framework.TestCase
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.coroutines.runBlocking
|
||||
|
||||
@ExperimentalCoroutinesApi
|
||||
class ApplyToFileHandlerTest : TestCase() {
|
||||
// Mock all dependencies
|
||||
private val mockProject = mockk<Project>(relaxed = true)
|
||||
|
|
@ -54,12 +54,14 @@ class ApplyToFileHandlerTest : TestCase() {
|
|||
)
|
||||
}
|
||||
|
||||
fun `test should insert text directly when document is empty`() = runTest {
|
||||
fun `test should insert text directly when document is empty`() {
|
||||
// Given
|
||||
every { mockEditorUtils.isDocumentEmpty() } returns true
|
||||
|
||||
// When
|
||||
handler.handleApplyToFile()
|
||||
runBlocking {
|
||||
handler.handleApplyToFile()
|
||||
}
|
||||
|
||||
// Then
|
||||
verify { mockEditorUtils.insertTextIntoEmptyDocument(testParams.text) }
|
||||
|
|
|
|||
|
|
@ -0,0 +1,122 @@
|
|||
package com.github.continuedev.continueintellijextension.unit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.autocomplete.ContinueInlineCompletionProvider
|
||||
import com.github.continuedev.continueintellijextension.autocomplete.CompletionService
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
import com.intellij.codeInsight.inline.completion.InlineCompletionHandler
|
||||
import com.intellij.codeInsight.inline.completion.testInlineCompletion
|
||||
import com.intellij.openapi.fileTypes.PlainTextFileType
|
||||
import com.intellij.testFramework.fixtures.BasePlatformTestCase
|
||||
import com.intellij.testFramework.replaceService
|
||||
import org.junit.jupiter.api.Assertions.assertDoesNotThrow
|
||||
import java.util.UUID
|
||||
|
||||
@Suppress("UnstableApiUsage")
|
||||
class ContinueInlineCompletionProviderTest : BasePlatformTestCase() {
|
||||
|
||||
override fun runInDispatchThread() =
|
||||
false
|
||||
|
||||
override fun setUp() {
|
||||
super.setUp()
|
||||
InlineCompletionHandler.registerTestHandler(ContinueInlineCompletionProvider(), testRootDisposable)
|
||||
}
|
||||
|
||||
fun `test don't show when settings are disabled`() = myFixture.testInlineCompletion {
|
||||
registerSuggestion("b")
|
||||
init(PlainTextFileType.INSTANCE, "a<caret>")
|
||||
ContinueExtensionSettings.instance.continueState.enableTabAutocomplete = false
|
||||
callInlineCompletion()
|
||||
delay()
|
||||
assertNoLookup()
|
||||
}
|
||||
|
||||
|
||||
fun `test show completion on Ctrl + Space, then insert with Tab`() = myFixture.testInlineCompletion {
|
||||
registerSuggestion("subtract(a: Int, b: Int) = a - b")
|
||||
init(
|
||||
PlainTextFileType.INSTANCE,
|
||||
"""
|
||||
class Calculator {
|
||||
fun add(a: Int, b: Int) = a + b
|
||||
fun <caret>
|
||||
}
|
||||
""".trimIndent()
|
||||
)
|
||||
callInlineCompletion()
|
||||
delay()
|
||||
insertWithTab()
|
||||
assertFileContent(
|
||||
"""
|
||||
class Calculator {
|
||||
fun add(a: Int, b: Int) = a + b
|
||||
fun subtract(a: Int, b: Int) = a - b<caret>
|
||||
}
|
||||
""".trimIndent()
|
||||
)
|
||||
}
|
||||
|
||||
fun `test inline completion that updates as the user types`() = myFixture.testInlineCompletion {
|
||||
registerSuggestion("4567890'")
|
||||
init(PlainTextFileType.INSTANCE, "digits = '123<caret>")
|
||||
callInlineCompletion()
|
||||
delay()
|
||||
typeChar('4')
|
||||
typeChar('5')
|
||||
assertInlineRender("67890'")
|
||||
typeChar('6')
|
||||
insertWithTab()
|
||||
assertFileContent("digits = '1234567890'<caret>")
|
||||
}
|
||||
|
||||
fun `test multiline`() = myFixture.testInlineCompletion {
|
||||
registerSuggestion(": i32) -> i32 {\n a + b\n}")
|
||||
init(PlainTextFileType.INSTANCE, "fn add(a: i32, b<caret>")
|
||||
callInlineCompletion()
|
||||
delay()
|
||||
insertWithTab()
|
||||
assertFileContent(
|
||||
"""
|
||||
fn add(a: i32, b: i32) -> i32 {
|
||||
a + b
|
||||
}<caret>
|
||||
""".trimIndent()
|
||||
)
|
||||
}
|
||||
|
||||
fun `test accepting completion notifies the service with valid UUID`() = myFixture.testInlineCompletion {
|
||||
var uuid: String? = null
|
||||
registerSuggestion("test") { uuid = it }
|
||||
init(PlainTextFileType.INSTANCE, "test <caret>")
|
||||
callInlineCompletion()
|
||||
delay()
|
||||
insertWithTab()
|
||||
assertFileContent("test test<caret>")
|
||||
assertDoesNotThrow {
|
||||
UUID.fromString(uuid)
|
||||
}
|
||||
}
|
||||
|
||||
fun `test not accepting completions is not notifying service with UUID`() = myFixture.testInlineCompletion {
|
||||
var uuid: String? = null
|
||||
registerSuggestion("test") { uuid = it }
|
||||
init(PlainTextFileType.INSTANCE, "test <caret>")
|
||||
callInlineCompletion()
|
||||
delay()
|
||||
assertInlineRender("test")
|
||||
assertNull(uuid)
|
||||
}
|
||||
|
||||
private fun registerSuggestion(variant: String?, accept: (String?) -> Unit = {}) =
|
||||
myFixture.project.replaceService(
|
||||
CompletionService::class.java,
|
||||
object : CompletionService {
|
||||
override suspend fun getAutocomplete(uuid: String, url: String, line: Int, column: Int): String? =
|
||||
variant
|
||||
|
||||
override fun acceptAutocomplete(uuid: String?) =
|
||||
accept(uuid)
|
||||
},
|
||||
testRootDisposable
|
||||
)
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue