Merge pull request #7131 (Next Edit for JetBrains) from continuedev/jacob/con-3353
This commit is contained in:
commit
3fbb98f237
18 changed files with 2907 additions and 83 deletions
|
|
@ -1,5 +1,11 @@
|
|||
package com.github.continuedev.continueintellijextension.autocomplete
|
||||
|
||||
import com.github.continuedev.continueintellijextension.FimResult
|
||||
import com.github.continuedev.continueintellijextension.Position
|
||||
import com.github.continuedev.continueintellijextension.nextEdit.NextEditJumpManager
|
||||
import com.github.continuedev.continueintellijextension.nextEdit.NextEditService
|
||||
import com.github.continuedev.continueintellijextension.nextEdit.NextEditUtils
|
||||
import com.github.continuedev.continueintellijextension.nextEdit.NextEditWindowManager
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
import com.github.continuedev.continueintellijextension.utils.uuid
|
||||
import com.intellij.codeInsight.inline.completion.*
|
||||
|
|
@ -7,8 +13,10 @@ import com.intellij.codeInsight.inline.completion.elements.InlineCompletionEleme
|
|||
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.codeInsight.inline.completion.suggestion.InlineCompletionVariant
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.project.Project
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
|
||||
class ContinueInlineCompletionProvider : InlineCompletionProvider {
|
||||
|
|
@ -16,6 +24,7 @@ class ContinueInlineCompletionProvider : InlineCompletionProvider {
|
|||
override val insertHandler: InlineCompletionInsertHandler = NotifyingHandler()
|
||||
private var lastUuid: String? = null
|
||||
private var lastProject: Project? = null
|
||||
private var isUsingNextEdit = false
|
||||
|
||||
override fun isEnabled(event: InlineCompletionEvent): Boolean {
|
||||
val isSettingEnabled = ContinueExtensionSettings.instance.continueState.enableTabAutocomplete
|
||||
|
|
@ -27,18 +36,100 @@ class ContinueInlineCompletionProvider : InlineCompletionProvider {
|
|||
|
||||
override suspend fun getSuggestion(request: InlineCompletionRequest): InlineCompletionSuggestion {
|
||||
val editor = request.editor
|
||||
val project = request.file.project
|
||||
val project = editor.project
|
||||
?: return InlineCompletionSuggestion.Empty
|
||||
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)))
|
||||
|
||||
// Check if Next Edit is supported
|
||||
val isNextEditSupported = NextEditUtils.isNextEditSupported(project)
|
||||
|
||||
if (isNextEditSupported) {
|
||||
isUsingNextEdit = true
|
||||
val nextEditService = project.service<NextEditService>()
|
||||
val nextEditJumpManager = project.service<NextEditJumpManager>()
|
||||
|
||||
val currCursorPos = Pair(
|
||||
editor.caretModel.primaryCaret.logicalPosition.line,
|
||||
editor.caretModel.primaryCaret.logicalPosition.column
|
||||
)
|
||||
|
||||
val isJumping = nextEditJumpManager.isJumpInProgress()
|
||||
val chainExists = nextEditService.chainExists()
|
||||
val nextEditOutcome = when {
|
||||
isJumping && chainExists -> nextEditService.handleCase2() // Case 2: Jumping (chain exists, jump was taken).
|
||||
chainExists -> nextEditService.handleCase3(
|
||||
editor,
|
||||
currCursorPos
|
||||
) // Case 3: Accepting next edit outcome (chain exists, jump is not taken).
|
||||
else -> nextEditService.handleCase1(
|
||||
request,
|
||||
editor,
|
||||
currCursorPos,
|
||||
lastUuid
|
||||
) // Case 1: Typing (chain does not exist).
|
||||
}
|
||||
|
||||
if (nextEditOutcome == null) {
|
||||
return InlineCompletionSuggestion.Empty
|
||||
}
|
||||
|
||||
val editableRegionStartLine = nextEditOutcome.editableRegionStartLine
|
||||
val editableRegionEndLine = nextEditOutcome.editableRegionEndLine
|
||||
val oldEditRangeSlice = editor.document.text
|
||||
.split("\n")
|
||||
.drop(editableRegionStartLine)
|
||||
.take(editableRegionEndLine - editableRegionStartLine + 1)
|
||||
.joinToString("\n")
|
||||
|
||||
// Check if it's a FIM (Fill-In-Middle) operation
|
||||
val fimResult = NextEditUtils.checkFim(
|
||||
oldEditRangeSlice, // Use the extracted slice instead of nextEditOutcome.oldCode
|
||||
nextEditOutcome.completion,
|
||||
currCursorPos
|
||||
)
|
||||
|
||||
when (fimResult) {
|
||||
is FimResult.FimEdit -> {
|
||||
// Render as gray text inline completion
|
||||
return object : InlineCompletionSuggestion {
|
||||
override suspend fun getVariants(): List<InlineCompletionVariant> {
|
||||
val completion = InlineCompletionVariant.build(
|
||||
request.file.virtualFile,
|
||||
flow { emit(InlineCompletionGrayTextElement(fimResult.fimText)) }
|
||||
)
|
||||
return listOf(completion)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is FimResult.NotFimEdit -> {
|
||||
// For non-FIM operations, show custom UI and return empty
|
||||
val nextEditWindowManager = project.service<NextEditWindowManager>()
|
||||
nextEditWindowManager.showNextEditWindow(
|
||||
editor,
|
||||
Position(currCursorPos.first, currCursorPos.second),
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
oldEditRangeSlice,
|
||||
nextEditOutcome.completion,
|
||||
nextEditOutcome.diffLines,
|
||||
)
|
||||
return InlineCompletionSuggestion.Empty
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Use traditional autocomplete
|
||||
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() {
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ class DiffStreamService {
|
|||
handlers[editor]?.rejectAll()
|
||||
}
|
||||
handlers[editor] = handler
|
||||
println("Registered handler for editor")
|
||||
//println("Registered handler for editor")
|
||||
}
|
||||
|
||||
fun reject(editor: Editor) {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,175 @@
|
|||
package com.github.continuedev.continueintellijextension.listeners
|
||||
|
||||
import com.github.continuedev.continueintellijextension.nextEdit.NextEditService
|
||||
import com.intellij.openapi.components.Service
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.LogicalPosition
|
||||
import com.intellij.openapi.editor.event.CaretEvent
|
||||
import com.intellij.openapi.editor.event.CaretListener
|
||||
import com.intellij.openapi.editor.event.SelectionEvent
|
||||
import com.intellij.openapi.editor.event.SelectionListener
|
||||
import com.intellij.openapi.project.DumbAware
|
||||
import com.intellij.openapi.project.Project
|
||||
import kotlinx.coroutines.*
|
||||
|
||||
/**
|
||||
* Interface for services that need to handle cursor movement events.
|
||||
*/
|
||||
interface CursorMovementHandler {
|
||||
val handlerId: String
|
||||
|
||||
/**
|
||||
* Called when cursor moves while this handler is active.
|
||||
* @return true if the cursor movement was expected/handled, false otherwise
|
||||
*/
|
||||
suspend fun onCursorMoved(editor: Editor, oldPosition: LogicalPosition?, newPosition: LogicalPosition): Boolean
|
||||
|
||||
/**
|
||||
* Called when this handler becomes active.
|
||||
*/
|
||||
fun onActivated() {}
|
||||
|
||||
/**
|
||||
* Called when this handler is about to be deactivated.
|
||||
*/
|
||||
fun onDeactivated() {}
|
||||
|
||||
/**
|
||||
* Called when the handler should clean up its resources.
|
||||
*/
|
||||
fun dispose() {
|
||||
onDeactivated()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Manages active cursor movement handlers to distinguish between intentional
|
||||
* cursor movements and side effects from various IDE operations.
|
||||
*
|
||||
* When a service is performing an operation that might move the cursor (like
|
||||
* accepting a completion, jumping, typing), it should register an active handler.
|
||||
* If no handler is active when the cursor moves, it's considered an intentional
|
||||
* movement and the next edit chain is deleted.
|
||||
*/
|
||||
@Service(Service.Level.PROJECT)
|
||||
class ActiveHandlerManager(private val project: Project) : SelectionListener, CaretListener, DumbAware {
|
||||
|
||||
private val coroutineScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
|
||||
private var activeHandler: CursorMovementHandler? = null
|
||||
private var isHandlingEvent = false
|
||||
|
||||
// Track last known cursor position to detect movements
|
||||
private var lastKnownPosition: LogicalPosition? = null
|
||||
private var lastKnownEditor: Editor? = null
|
||||
|
||||
/**
|
||||
* Set an active handler for cursor movement events.
|
||||
* This should be called when a service is about to perform an operation
|
||||
* that might cause cursor movement.
|
||||
*/
|
||||
fun setActiveHandler(handler: CursorMovementHandler) {
|
||||
clearActiveHandler()
|
||||
|
||||
activeHandler = handler
|
||||
handler.onActivated()
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the currently active handler.
|
||||
* This should be called when the operation is complete.
|
||||
*/
|
||||
fun clearActiveHandler() {
|
||||
activeHandler?.let { handler ->
|
||||
handler.onDeactivated()
|
||||
handler.dispose()
|
||||
}
|
||||
activeHandler = null
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the currently active handler.
|
||||
*/
|
||||
fun getActiveHandler(): CursorMovementHandler? = activeHandler
|
||||
|
||||
/**
|
||||
* Check if a specific handler is currently active.
|
||||
*/
|
||||
fun isHandlerActive(handlerId: String): Boolean {
|
||||
return activeHandler?.handlerId == handlerId
|
||||
}
|
||||
|
||||
// SelectionListener implementation
|
||||
override fun selectionChanged(event: SelectionEvent) {
|
||||
if (isHandlingEvent || event.editor.isDisposed) return
|
||||
|
||||
coroutineScope.launch {
|
||||
handleCursorMovement(event.editor, event.newRange.startOffset)
|
||||
}
|
||||
}
|
||||
|
||||
// CaretListener implementation
|
||||
override fun caretPositionChanged(event: CaretEvent) {
|
||||
if (isHandlingEvent || event.editor.isDisposed) return
|
||||
|
||||
coroutineScope.launch {
|
||||
handleCursorMovement(event.editor, event.caret?.offset ?: return@launch)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun handleCursorMovement(editor: Editor, offset: Int) {
|
||||
if (isHandlingEvent) return
|
||||
|
||||
isHandlingEvent = true
|
||||
try {
|
||||
val currentPosition = editor.offsetToLogicalPosition(offset)
|
||||
val oldPosition = if (editor == lastKnownEditor) lastKnownPosition else null
|
||||
|
||||
// Update tracking
|
||||
lastKnownPosition = currentPosition
|
||||
lastKnownEditor = editor
|
||||
|
||||
// Skip if position hasn't actually changed
|
||||
if (oldPosition != null && oldPosition == currentPosition) {
|
||||
return
|
||||
}
|
||||
|
||||
val handler = activeHandler
|
||||
if (handler != null) {
|
||||
// A handler is active - let it decide if this movement was expected
|
||||
try {
|
||||
val wasHandled = handler.onCursorMoved(editor, oldPosition, currentPosition)
|
||||
if (!wasHandled) {
|
||||
handleDeliberateCursorMovement()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
println("ActiveHandlerManager: Error in handler '${handler.handlerId}': ${e.message}")
|
||||
// Treat as deliberate movement if handler fails
|
||||
handleDeliberateCursorMovement()
|
||||
}
|
||||
} else {
|
||||
// No active handler - this is a deliberate cursor movement
|
||||
handleDeliberateCursorMovement()
|
||||
}
|
||||
} finally {
|
||||
isHandlingEvent = false
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun handleDeliberateCursorMovement() {
|
||||
try {
|
||||
// Clear any active handler since the user moved the cursor deliberately
|
||||
clearActiveHandler()
|
||||
|
||||
// Delete the next edit chain
|
||||
val nextEditService = project.getService(NextEditService::class.java)
|
||||
nextEditService.deleteChain()
|
||||
} catch (e: Exception) {
|
||||
println("ActiveHandlerManager: Error handling deliberate cursor movement: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
fun dispose() {
|
||||
clearActiveHandler()
|
||||
coroutineScope.cancel()
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
package com.github.continuedev.continueintellijextension.listeners
|
||||
|
||||
import com.intellij.openapi.components.Service
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.editor.event.DocumentEvent
|
||||
import com.intellij.openapi.editor.event.DocumentListener
|
||||
import com.intellij.openapi.project.Project
|
||||
import kotlinx.coroutines.*
|
||||
|
||||
/**
|
||||
* Tracks document changes to detect typing sessions and manage active handlers.
|
||||
*/
|
||||
@Service(Service.Level.PROJECT)
|
||||
class DocumentChangeTracker(private val project: Project) : DocumentListener {
|
||||
|
||||
private val coroutineScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
|
||||
private var typingHandler: TypingSessionHandler? = null
|
||||
private var typingSessionTimer: Job? = null
|
||||
|
||||
private val TYPING_SESSION_TIMEOUT = 2000L // ms
|
||||
|
||||
override fun documentChanged(event: DocumentEvent) {
|
||||
if (event.document.isWritable) {
|
||||
handleDocumentChange()
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleDocumentChange() {
|
||||
val activeHandlerManager = project.service<ActiveHandlerManager>()
|
||||
|
||||
// Cancel existing typing session timer
|
||||
typingSessionTimer?.cancel()
|
||||
|
||||
// If no active handler or it's not already a typing session, create one
|
||||
val currentHandler = activeHandlerManager.getActiveHandler()
|
||||
if (currentHandler !is TypingSessionHandler) {
|
||||
typingHandler = TypingSessionHandler(project)
|
||||
activeHandlerManager.setActiveHandler(typingHandler!!)
|
||||
} else {
|
||||
// Update existing typing handler
|
||||
(currentHandler as TypingSessionHandler).updateTypingTime()
|
||||
}
|
||||
|
||||
// Set up timer to clear typing session after inactivity
|
||||
typingSessionTimer = coroutineScope.launch {
|
||||
delay(TYPING_SESSION_TIMEOUT)
|
||||
|
||||
// Clear typing handler if it's still active
|
||||
if (activeHandlerManager.isHandlerActive("typingSession")) {
|
||||
activeHandlerManager.clearActiveHandler()
|
||||
typingHandler?.dispose()
|
||||
typingHandler = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun dispose() {
|
||||
typingSessionTimer?.cancel()
|
||||
typingHandler?.dispose()
|
||||
coroutineScope.cancel()
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,283 @@
|
|||
package com.github.continuedev.continueintellijextension.listeners
|
||||
|
||||
import com.github.continuedev.continueintellijextension.nextEdit.NextEditService
|
||||
import com.github.continuedev.continueintellijextension.nextEdit.NextEditJumpManager
|
||||
import com.github.continuedev.continueintellijextension.nextEdit.NextEditWindowManager
|
||||
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.LogicalPosition
|
||||
import com.intellij.openapi.editor.event.SelectionEvent
|
||||
import com.intellij.openapi.editor.event.SelectionListener
|
||||
import com.intellij.openapi.project.DumbAware
|
||||
import com.intellij.openapi.project.Project
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import java.util.concurrent.ConcurrentLinkedQueue
|
||||
|
||||
enum class HandlerPriority(val value: Int) {
|
||||
CRITICAL(5),
|
||||
HIGH(4),
|
||||
NORMAL(3),
|
||||
LOW(2),
|
||||
FALLBACK(1)
|
||||
}
|
||||
|
||||
data class StateSnapshot(
|
||||
val nextEditWindowAccepted: Boolean,
|
||||
val jumpInProgress: Boolean,
|
||||
val jumpJustAccepted: Boolean,
|
||||
val lastDocumentChangeTime: Long,
|
||||
val isTypingSession: Boolean,
|
||||
val document: Document?,
|
||||
val cursorPosition: LogicalPosition?
|
||||
)
|
||||
|
||||
typealias SelectionChangeHandler = suspend (SelectionEvent, StateSnapshot) -> Boolean
|
||||
|
||||
data class HandlerRegistration(
|
||||
val id: String,
|
||||
val priority: Int,
|
||||
val handler: SelectionChangeHandler
|
||||
)
|
||||
|
||||
@Service(Service.Level.PROJECT)
|
||||
class SelectionChangeManager(private val project: Project) : SelectionListener, DumbAware {
|
||||
private val coroutineScope = CoroutineScope(Dispatchers.Main)
|
||||
private val listeners = mutableListOf<HandlerRegistration>()
|
||||
|
||||
// Event processing
|
||||
private val eventQueue = ConcurrentLinkedQueue<SelectionEvent>()
|
||||
private var lastEventTime = 0L
|
||||
private var isProcessingEvent = false
|
||||
private val processingMutex = Mutex()
|
||||
private var processingJob: Job? = null
|
||||
|
||||
// Debounce settings
|
||||
private val DEBOUNCE_DELAY = 50L
|
||||
private val PROCESSING_TIMEOUT = 500L
|
||||
|
||||
// Track typing session state
|
||||
private var isTypingSession = false
|
||||
private var typingTimer: Job? = null
|
||||
private var lastDocumentChangeTime = 0L
|
||||
private val TYPING_SESSION_TIMEOUT = 2000L
|
||||
|
||||
init {
|
||||
// Register the default fallback handler
|
||||
registerListener(
|
||||
"defaultFallbackHandler",
|
||||
::defaultFallbackHandler,
|
||||
HandlerPriority.FALLBACK
|
||||
)
|
||||
}
|
||||
|
||||
fun documentChanged() {
|
||||
isTypingSession = true
|
||||
lastDocumentChangeTime = System.currentTimeMillis()
|
||||
resetTypingSession()
|
||||
}
|
||||
|
||||
private fun resetTypingSession() {
|
||||
typingTimer?.cancel()
|
||||
typingTimer = coroutineScope.launch {
|
||||
delay(TYPING_SESSION_TIMEOUT)
|
||||
isTypingSession = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a listener for the selection change event.
|
||||
* @param id Unique id for this handler.
|
||||
* @param handler Function to handle the event.
|
||||
* @param priority Higher priority runs first.
|
||||
* @return Function to unregister this listener.
|
||||
*/
|
||||
fun registerListener(
|
||||
id: String,
|
||||
handler: SelectionChangeHandler,
|
||||
priority: HandlerPriority = HandlerPriority.NORMAL
|
||||
): () -> Unit {
|
||||
// Remove any existing handler with the same id
|
||||
listeners.removeAll { it.id == id }
|
||||
|
||||
// Add the new handler
|
||||
listeners.add(HandlerRegistration(id, priority.value, handler))
|
||||
|
||||
// Sort by descending priority
|
||||
listeners.sortByDescending { it.priority }
|
||||
|
||||
// Return the unregister function
|
||||
return {
|
||||
listeners.removeAll { it.id == id }
|
||||
}
|
||||
}
|
||||
|
||||
override fun selectionChanged(event: SelectionEvent) {
|
||||
if (event.editor.isDisposed || event.editor.project?.isDisposed == true) {
|
||||
return
|
||||
}
|
||||
|
||||
coroutineScope.launch {
|
||||
handleSelectionChange(event)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a given selection change event.
|
||||
* @param e The selection change event.
|
||||
*/
|
||||
private suspend fun handleSelectionChange(e: SelectionEvent) {
|
||||
val now = System.currentTimeMillis()
|
||||
|
||||
// Simple debouncing logic
|
||||
// Ignore events that come too quickly after the previous one
|
||||
if (now - lastEventTime < DEBOUNCE_DELAY) {
|
||||
// Replace the queued event with the most recent one
|
||||
if (eventQueue.isNotEmpty()) {
|
||||
eventQueue.clear()
|
||||
}
|
||||
eventQueue.offer(e)
|
||||
return
|
||||
}
|
||||
|
||||
lastEventTime = now
|
||||
|
||||
// Queue this event for later if the manager is already processing an event
|
||||
if (isProcessingEvent) {
|
||||
eventQueue.offer(e)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
// Process this event first
|
||||
processEventWithTimeout(e)
|
||||
|
||||
// Process remaining queued events sequentially
|
||||
while (eventQueue.isNotEmpty()) {
|
||||
val nextEvent = eventQueue.poll()
|
||||
if (nextEvent != null) {
|
||||
processEventWithTimeout(nextEvent)
|
||||
}
|
||||
}
|
||||
} catch (err: Exception) {
|
||||
println("Error processing selection change event: ${err.message}")
|
||||
err.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a given event with a timeout.
|
||||
* This is in attempt to prevent deadlocks between events.
|
||||
* @param e The selection change event.
|
||||
*/
|
||||
private suspend fun processEventWithTimeout(e: SelectionEvent) {
|
||||
processingMutex.withLock {
|
||||
isProcessingEvent = true
|
||||
|
||||
try {
|
||||
// Cancel any existing processing job
|
||||
processingJob?.cancel()
|
||||
|
||||
// Set up a timeout to prevent deadlocks
|
||||
processingJob = coroutineScope.launch {
|
||||
try {
|
||||
processEvent(e)
|
||||
} catch (ex: Exception) {
|
||||
println("Error in processEvent: ${ex.message}")
|
||||
ex.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for completion with timeout
|
||||
val timeoutJob = coroutineScope.launch {
|
||||
delay(PROCESSING_TIMEOUT)
|
||||
processingJob?.cancel()
|
||||
throw Exception("Selection change event processing timed out")
|
||||
}
|
||||
|
||||
try {
|
||||
processingJob?.join()
|
||||
timeoutJob.cancel()
|
||||
} catch (ex: Exception) {
|
||||
println("Processing timeout or error: ${ex.message}")
|
||||
}
|
||||
|
||||
} finally {
|
||||
isProcessingEvent = false
|
||||
processingJob = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Core event processing logic.
|
||||
* @param e The selection change event.
|
||||
*/
|
||||
private suspend fun processEvent(e: SelectionEvent) {
|
||||
val snapshot = captureState(e)
|
||||
|
||||
for (registration in listeners) {
|
||||
try {
|
||||
if (registration.handler(e, snapshot)) {
|
||||
return
|
||||
}
|
||||
} catch (err: Exception) {
|
||||
println("Error in selection change handler '${registration.id}': ${err.message}")
|
||||
err.printStackTrace()
|
||||
// Don't break - continue to next handler
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun captureState(e: SelectionEvent): StateSnapshot {
|
||||
val nextEditWindowManager = runCatching {
|
||||
project.getService(NextEditWindowManager::class.java)
|
||||
}.getOrNull()
|
||||
|
||||
val jumpManager = runCatching {
|
||||
project.getService(NextEditJumpManager::class.java)
|
||||
}.getOrNull()
|
||||
|
||||
val cursorPosition = try {
|
||||
e.editor.caretModel.primaryCaret.logicalPosition
|
||||
} catch (ex: Exception) {
|
||||
null
|
||||
}
|
||||
|
||||
return StateSnapshot(
|
||||
nextEditWindowAccepted = nextEditWindowManager?.hasAccepted() ?: false,
|
||||
jumpInProgress = jumpManager?.isJumpInProgress() ?: false,
|
||||
jumpJustAccepted = jumpManager?.wasJumpJustAccepted() ?: false,
|
||||
lastDocumentChangeTime = lastDocumentChangeTime,
|
||||
isTypingSession = isTypingSession,
|
||||
document = e.editor.document,
|
||||
cursorPosition = cursorPosition
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun defaultFallbackHandler(
|
||||
e: SelectionEvent,
|
||||
state: StateSnapshot
|
||||
): Boolean {
|
||||
println("defaultFallbackHandler: deleteChain called from selectionChanged")
|
||||
|
||||
try {
|
||||
val nextEditService = project.getService(NextEditService::class.java)
|
||||
nextEditService.deleteChain()
|
||||
} catch (ex: Exception) {
|
||||
println("Error deleting chain in defaultFallbackHandler: ${ex.message}")
|
||||
}
|
||||
|
||||
// TODO: Add prefetch logic similar to VS Code if needed
|
||||
// This would involve getting next editable regions and enqueuing them
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
package com.github.continuedev.continueintellijextension.listeners
|
||||
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.LogicalPosition
|
||||
import com.intellij.openapi.project.Project
|
||||
|
||||
/**
|
||||
* Handler for cursor movements during typing sessions.
|
||||
* Preserves the chain when user is actively typing.
|
||||
*/
|
||||
class TypingSessionHandler(
|
||||
private val project: Project
|
||||
) : CursorMovementHandler {
|
||||
|
||||
override val handlerId = "typingSession"
|
||||
|
||||
private var lastDocumentChangeTime = 0L
|
||||
private val TYPING_DELAY = 1000L // ms - consider movements within this time as typing
|
||||
|
||||
fun updateTypingTime() {
|
||||
lastDocumentChangeTime = System.currentTimeMillis()
|
||||
}
|
||||
|
||||
override suspend fun onCursorMoved(
|
||||
editor: Editor,
|
||||
oldPosition: LogicalPosition?,
|
||||
newPosition: LogicalPosition
|
||||
): Boolean {
|
||||
val now = System.currentTimeMillis()
|
||||
val timeSinceLastEdit = now - lastDocumentChangeTime
|
||||
|
||||
// If recent document change and cursor moved forward/down, likely typing
|
||||
if (timeSinceLastEdit < TYPING_DELAY) {
|
||||
val isTypingMovement = oldPosition?.let { old ->
|
||||
// Same line, moving forward
|
||||
(newPosition.line == old.line && newPosition.column > old.column) ||
|
||||
// Next line, typical of pressing Enter
|
||||
(newPosition.line == old.line + 1 && newPosition.column <= old.column)
|
||||
} ?: false
|
||||
|
||||
if (isTypingMovement) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
override fun onDeactivated() {
|
||||
//println("TypingSessionHandler: Deactivated")
|
||||
}
|
||||
|
||||
override fun dispose() {
|
||||
onDeactivated()
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
package com.github.continuedev.continueintellijextension.nextEdit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.listeners.CursorMovementHandler
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.LogicalPosition
|
||||
import com.intellij.openapi.project.Project
|
||||
|
||||
/**
|
||||
* Handler for cursor movements during jump operations.
|
||||
*/
|
||||
class NextEditJumpHandler(
|
||||
private val project: Project,
|
||||
private val jumpManager: NextEditJumpManager
|
||||
) : CursorMovementHandler {
|
||||
|
||||
override val handlerId = "nextEditJump"
|
||||
|
||||
override suspend fun onCursorMoved(
|
||||
editor: Editor,
|
||||
oldPosition: LogicalPosition?,
|
||||
newPosition: LogicalPosition
|
||||
): Boolean {
|
||||
// Check if we're still in a jump operation
|
||||
if (!jumpManager.isJumpInProgress()) {
|
||||
// Jump is no longer in progress, cursor movement is deliberate
|
||||
return false
|
||||
}
|
||||
|
||||
val jumpPosition = jumpManager.getJumpPosition()
|
||||
val originalPosition = jumpManager.getOriginalPosition()
|
||||
|
||||
return when {
|
||||
// Cursor moved to the expected jump position - this is expected
|
||||
jumpPosition != null && newPosition == jumpPosition -> {
|
||||
true
|
||||
}
|
||||
|
||||
// Cursor is still at the original position - no movement yet
|
||||
originalPosition != null && newPosition == originalPosition -> {
|
||||
true
|
||||
}
|
||||
|
||||
// Cursor moved somewhere else - user moved manually, abort jump
|
||||
else -> {
|
||||
jumpManager.abortJump()
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDeactivated() {
|
||||
println("NextEditJumpHandler: Deactivated")
|
||||
}
|
||||
|
||||
override fun dispose() {
|
||||
onDeactivated()
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,475 @@
|
|||
package com.github.continuedev.continueintellijextension.nextEdit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.listeners.ActiveHandlerManager
|
||||
import com.github.continuedev.continueintellijextension.utils.InlineCompletionUtils
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.application.EDT
|
||||
import com.intellij.openapi.components.Service
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.LogicalPosition
|
||||
import com.intellij.openapi.editor.ScrollType
|
||||
import com.intellij.openapi.editor.markup.HighlighterLayer
|
||||
import com.intellij.openapi.editor.markup.HighlighterTargetArea
|
||||
import com.intellij.openapi.editor.markup.RangeHighlighter
|
||||
import com.intellij.openapi.editor.markup.TextAttributes
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.ui.popup.JBPopup
|
||||
import com.intellij.openapi.ui.popup.JBPopupFactory
|
||||
import com.intellij.openapi.util.TextRange
|
||||
import com.intellij.ui.JBColor
|
||||
import com.intellij.ui.components.JBLabel
|
||||
import com.intellij.ui.components.JBPanel
|
||||
import com.intellij.util.ui.JBFont
|
||||
import com.intellij.util.ui.JBUI
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.launch
|
||||
import java.awt.*
|
||||
import java.awt.event.ActionEvent
|
||||
import java.awt.event.KeyEvent
|
||||
import java.awt.geom.RoundRectangle2D
|
||||
import javax.swing.AbstractAction
|
||||
import javax.swing.JComponent
|
||||
import javax.swing.KeyStroke
|
||||
import javax.swing.SwingUtilities
|
||||
import javax.swing.border.AbstractBorder
|
||||
|
||||
data class CompletionDataForAfterJump(
|
||||
val completionId: String,
|
||||
val outcome: NextEditOutcome,
|
||||
val position: LogicalPosition
|
||||
)
|
||||
|
||||
@Service(Service.Level.PROJECT)
|
||||
class NextEditJumpManager(private val project: Project) {
|
||||
|
||||
private val coroutineScope = CoroutineScope(Dispatchers.Default + SupervisorJob())
|
||||
|
||||
// State management
|
||||
private var jumpState = JumpState()
|
||||
|
||||
// Handler management
|
||||
private var jumpHandler: NextEditJumpHandler? = null
|
||||
|
||||
// UI components
|
||||
private var jumpPopup: JBPopup? = null
|
||||
private var editorHighlighter: RangeHighlighter? = null
|
||||
private var keyboardShortcutsPanel: JComponent? = null
|
||||
|
||||
// Callbacks
|
||||
private var triggerInlineSuggestCallback: (() -> Unit)? = null
|
||||
private var deleteChainCallback: (() -> Unit)? = null
|
||||
|
||||
private data class JumpState(
|
||||
val inProgress: Boolean = false,
|
||||
val justAccepted: Boolean = false,
|
||||
val jumpPosition: LogicalPosition? = null,
|
||||
val editor: Editor? = null,
|
||||
val oldCursorPosition: LogicalPosition? = null,
|
||||
val completionAfterJump: CompletionDataForAfterJump? = null
|
||||
)
|
||||
|
||||
init {
|
||||
// registerSelectionChangeHandler()
|
||||
}
|
||||
|
||||
// Public API
|
||||
fun isJumpInProgress(): Boolean = jumpState.inProgress
|
||||
|
||||
fun setJumpInProgress(jumpInProgress: Boolean) {
|
||||
jumpState = jumpState.copy(inProgress = jumpInProgress)
|
||||
}
|
||||
|
||||
fun wasJumpJustAccepted(): Boolean = jumpState.justAccepted
|
||||
|
||||
fun setTriggerInlineSuggestCallback(callback: () -> Unit) {
|
||||
triggerInlineSuggestCallback = callback
|
||||
}
|
||||
|
||||
fun setDeleteChainCallback(callback: () -> Unit) {
|
||||
deleteChainCallback = callback
|
||||
}
|
||||
|
||||
fun setCompletionAfterJump(completionData: CompletionDataForAfterJump) {
|
||||
jumpState = jumpState.copy(completionAfterJump = completionData)
|
||||
}
|
||||
|
||||
fun clearSavedCompletionAfterJump() {
|
||||
jumpState = jumpState.copy(completionAfterJump = null)
|
||||
}
|
||||
|
||||
fun getSavedCompletionAfterJump(): CompletionDataForAfterJump? = jumpState.completionAfterJump
|
||||
|
||||
fun getJumpPosition(): LogicalPosition? = jumpState.jumpPosition
|
||||
|
||||
fun getOriginalPosition(): LogicalPosition? = jumpState.oldCursorPosition
|
||||
|
||||
fun abortJump() {
|
||||
// Public method that delegates to the existing private rejectJump logic
|
||||
rejectJump()
|
||||
}
|
||||
|
||||
// Main entry point
|
||||
suspend fun suggestJump(
|
||||
editor: Editor,
|
||||
currentPosition: LogicalPosition,
|
||||
nextJumpLocation: LogicalPosition,
|
||||
completionContent: String? = null
|
||||
): Boolean {
|
||||
// Skip if content is identical at jump location
|
||||
if (completionContent != null &&
|
||||
isContentIdentical(editor, nextJumpLocation, completionContent)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Update state
|
||||
jumpState = jumpState.copy(
|
||||
inProgress = true,
|
||||
jumpPosition = nextJumpLocation,
|
||||
editor = editor,
|
||||
oldCursorPosition = currentPosition
|
||||
)
|
||||
|
||||
// Register active handler to track cursor movements during jump
|
||||
jumpHandler = NextEditJumpHandler(project, this)
|
||||
val activeHandlerManager = project.getService(ActiveHandlerManager::class.java)
|
||||
activeHandlerManager.setActiveHandler(jumpHandler!!)
|
||||
|
||||
// Show UI - ensure this runs on EDT
|
||||
return try {
|
||||
var result = false
|
||||
ApplicationManager.getApplication().invokeAndWait {
|
||||
try {
|
||||
showJumpDecoration(editor, nextJumpLocation)
|
||||
|
||||
// Scroll to show jump location
|
||||
editor.scrollingModel.scrollTo(nextJumpLocation, ScrollType.CENTER)
|
||||
|
||||
result = true
|
||||
} catch (e: Exception) {
|
||||
// Reset state on error
|
||||
jumpState = jumpState.copy(inProgress = false)
|
||||
result = false
|
||||
}
|
||||
}
|
||||
result
|
||||
} catch (e: Exception) {
|
||||
println("DEBUG: Error in suggestJump invokeAndWait: $e")
|
||||
// Reset state on error
|
||||
jumpState = jumpState.copy(inProgress = false)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
// Private implementation
|
||||
private fun showJumpDecoration(editor: Editor, position: LogicalPosition) {
|
||||
clearJumpDecoration()
|
||||
|
||||
// Add editor highlight
|
||||
val markupModel = editor.markupModel
|
||||
val lineStartOffset = editor.document.getLineStartOffset(position.line)
|
||||
val lineEndOffset = editor.document.getLineEndOffset(position.line)
|
||||
|
||||
editorHighlighter = markupModel.addRangeHighlighter(
|
||||
lineStartOffset,
|
||||
lineEndOffset,
|
||||
HighlighterLayer.SELECTION - 1,
|
||||
TextAttributes().apply {
|
||||
backgroundColor = JBColor.namedColor("InfoPopup.background", JBColor(0xE6F3FF, 0x2D3142))
|
||||
},
|
||||
HighlighterTargetArea.LINES_IN_RANGE
|
||||
)
|
||||
|
||||
// Show popup with keyboard shortcuts
|
||||
showJumpPopup(editor, position)
|
||||
}
|
||||
|
||||
private fun showJumpPopup(editor: Editor, position: LogicalPosition) {
|
||||
val popupComponent = createJumpPopupComponent(editor)
|
||||
|
||||
jumpPopup = JBPopupFactory.getInstance()
|
||||
.createComponentPopupBuilder(popupComponent, popupComponent)
|
||||
.setFocusable(true)
|
||||
.setRequestFocus(true)
|
||||
.setResizable(false)
|
||||
.setMovable(false)
|
||||
.setCancelOnClickOutside(false)
|
||||
.setCancelOnWindowDeactivation(false)
|
||||
.setCancelKeyEnabled(false)
|
||||
.setCancelCallback {
|
||||
if (jumpState.inProgress && !jumpState.justAccepted) {
|
||||
rejectJump()
|
||||
}
|
||||
true
|
||||
}
|
||||
.createPopup()
|
||||
|
||||
// Show popup and ensure focus
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
try {
|
||||
val lineEndOffset = editor.document.getLineEndOffset(position.line)
|
||||
val lineEndPoint = editor.offsetToXY(lineEndOffset)
|
||||
val editorComponent = editor.contentComponent
|
||||
|
||||
// Calculate the vertical center of the line
|
||||
val lineHeight = editor.lineHeight
|
||||
val lineCenterY = lineEndPoint.y + (lineHeight / 2)
|
||||
|
||||
// Get the popup's preferred size to calculate its center
|
||||
val popupSize = popupComponent.preferredSize
|
||||
val popupCenterY = popupSize.height / 2
|
||||
|
||||
// Position the popup so its center aligns with the line's center
|
||||
val adjustedY = lineCenterY - popupCenterY
|
||||
|
||||
val screenPoint = Point(lineEndPoint.x + 20, adjustedY)
|
||||
SwingUtilities.convertPointToScreen(screenPoint, editorComponent)
|
||||
|
||||
jumpPopup?.showInScreenCoordinates(editorComponent, screenPoint)
|
||||
|
||||
val content = jumpPopup?.content
|
||||
if (content is JComponent) {
|
||||
// Remove default border and add custom rounded border
|
||||
content.border = object : AbstractBorder() {
|
||||
override fun paintBorder(c: Component, g: Graphics, x: Int, y: Int, width: Int, height: Int) {
|
||||
val g2 = g.create() as Graphics2D
|
||||
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
|
||||
|
||||
val arc = 6f
|
||||
// g2.color = JBColor.border()
|
||||
g2.color = Color(0x999998)
|
||||
g2.stroke = BasicStroke(1f)
|
||||
g2.draw(
|
||||
RoundRectangle2D.Float(
|
||||
x.toFloat(),
|
||||
y.toFloat(),
|
||||
width.toFloat() - 1f,
|
||||
height.toFloat() - 1f,
|
||||
arc,
|
||||
arc
|
||||
)
|
||||
)
|
||||
g2.dispose()
|
||||
}
|
||||
|
||||
override fun getBorderInsets(c: Component): Insets = JBUI.insets(1)
|
||||
}
|
||||
}
|
||||
|
||||
// Force focus after popup is shown
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
popupComponent.requestFocusInWindow()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
jumpPopup?.showInBestPositionFor(editor)
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
popupComponent.requestFocusInWindow()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun createJumpPopupComponent(editor: Editor): JComponent {
|
||||
val panel = object : JBPanel<JBPanel<*>>() {
|
||||
private val arc = 6f
|
||||
|
||||
init {
|
||||
isOpaque = false
|
||||
background = JBColor.namedColor("InfoPopup.background", JBColor(0xE6F3FF, 0x2D3142))
|
||||
}
|
||||
|
||||
override fun paintComponent(g: Graphics) {
|
||||
val g2 = g.create() as Graphics2D
|
||||
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
|
||||
|
||||
val width = width.toFloat()
|
||||
val height = height.toFloat()
|
||||
|
||||
// Draw background with rounded corners
|
||||
g2.color = background
|
||||
g2.fill(RoundRectangle2D.Float(0f, 0f, width, height, arc, arc))
|
||||
|
||||
// Draw border with the SAME dimensions as the background
|
||||
g2.color = JBColor.border()
|
||||
g2.stroke = BasicStroke(1f)
|
||||
g2.draw(RoundRectangle2D.Float(0f, 0f, width, height, arc, arc))
|
||||
|
||||
g2.dispose()
|
||||
super.paintComponent(g)
|
||||
}
|
||||
}.apply {
|
||||
layout = BorderLayout()
|
||||
border = JBUI.Borders.empty(2, 4)
|
||||
}
|
||||
|
||||
// Create the message label
|
||||
val message = "📍 Press Tab to jump, Esc to cancel"
|
||||
val label = JBLabel(message).apply {
|
||||
foreground = JBColor.foreground()
|
||||
background = JBColor.namedColor("InfoPopup.background", JBColor(0xE6F3FF, 0x2D3142))
|
||||
isOpaque = true
|
||||
font = JBFont.small()
|
||||
}
|
||||
|
||||
panel.add(label, BorderLayout.CENTER)
|
||||
|
||||
// Add keyboard shortcuts to the panel
|
||||
addKeyboardShortcuts(panel, editor)
|
||||
|
||||
// Store reference for cleanup
|
||||
keyboardShortcutsPanel = panel
|
||||
|
||||
return panel
|
||||
}
|
||||
|
||||
private fun addKeyboardShortcuts(panel: JComponent, editor: Editor) {
|
||||
// CRITICAL: Disable focus traversal for Tab key
|
||||
panel.setFocusTraversalKeysEnabled(false)
|
||||
|
||||
val inputMap = panel.getInputMap(JComponent.WHEN_FOCUSED)
|
||||
val actionMap = panel.actionMap
|
||||
|
||||
// Add Tab key for accept
|
||||
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "acceptJump")
|
||||
actionMap.put("acceptJump", object : AbstractAction() {
|
||||
override fun actionPerformed(e: ActionEvent?) {
|
||||
acceptJump(editor)
|
||||
}
|
||||
})
|
||||
|
||||
// Add Esc key for reject
|
||||
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "rejectJump")
|
||||
actionMap.put("rejectJump", object : AbstractAction() {
|
||||
override fun actionPerformed(e: ActionEvent?) {
|
||||
rejectJump()
|
||||
}
|
||||
})
|
||||
|
||||
panel.isFocusable = true
|
||||
}
|
||||
|
||||
private fun acceptJump(editor: Editor) {
|
||||
val state = jumpState
|
||||
if (!state.inProgress || state.jumpPosition == null || state.editor == null) {
|
||||
return
|
||||
}
|
||||
|
||||
// Update state BEFORE clearing decorations to prevent cancel callback from triggering reject
|
||||
jumpState = jumpState.copy(justAccepted = true)
|
||||
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
// Move cursor to jump position
|
||||
state.editor.caretModel.moveToLogicalPosition(state.jumpPosition)
|
||||
|
||||
// Clear decorations (this will cancel popup, but won't trigger reject due to state check)
|
||||
clearJumpDecoration()
|
||||
|
||||
coroutineScope.launch(Dispatchers.EDT) {
|
||||
InlineCompletionUtils.triggerInlineCompletion(editor, project)
|
||||
}
|
||||
|
||||
// Reset accepted state after a brief moment
|
||||
coroutineScope.launch {
|
||||
kotlinx.coroutines.delay(100)
|
||||
jumpState = jumpState.copy(justAccepted = false)
|
||||
|
||||
// Clear the active handler after jump is complete
|
||||
clearActiveHandler()
|
||||
|
||||
// Trigger inline suggestion
|
||||
triggerInlineSuggestCallback?.invoke()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun rejectJump() {
|
||||
if (!jumpState.inProgress) {
|
||||
return
|
||||
}
|
||||
|
||||
// Delete the chain
|
||||
deleteChainCallback?.invoke()
|
||||
|
||||
// Clear state
|
||||
clearJumpState()
|
||||
|
||||
// Clear handler when rejecting
|
||||
clearActiveHandler()
|
||||
}
|
||||
|
||||
private fun clearJumpDecoration() {
|
||||
// Clear keyboard shortcuts first
|
||||
keyboardShortcutsPanel?.let { panel ->
|
||||
if (panel is JComponent) {
|
||||
panel.inputMap?.clear()
|
||||
panel.actionMap?.clear()
|
||||
}
|
||||
}
|
||||
keyboardShortcutsPanel = null
|
||||
|
||||
// Cancel popup
|
||||
jumpPopup?.cancel()
|
||||
jumpPopup = null
|
||||
|
||||
// Remove editor highlighter
|
||||
editorHighlighter?.let { highlighter ->
|
||||
jumpState.editor?.markupModel?.removeHighlighter(highlighter)
|
||||
editorHighlighter = null
|
||||
}
|
||||
}
|
||||
|
||||
private fun clearJumpState() {
|
||||
clearJumpDecoration()
|
||||
jumpState = JumpState()
|
||||
}
|
||||
|
||||
private fun isContentIdentical(
|
||||
editor: Editor,
|
||||
jumpLocation: LogicalPosition,
|
||||
completionContent: String
|
||||
): Boolean {
|
||||
return try {
|
||||
val completionLines = completionContent.split("\n")
|
||||
val document = editor.document
|
||||
val startLine = jumpLocation.line
|
||||
val endLine = minOf(startLine + completionLines.size - 1, document.lineCount - 1)
|
||||
|
||||
// Check if we have enough lines
|
||||
if (endLine - startLine + 1 < completionLines.size) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Compare line by line
|
||||
completionLines.indices.all { i ->
|
||||
val documentLine = startLine + i
|
||||
if (documentLine >= document.lineCount) return@all false
|
||||
|
||||
val lineStartOffset = document.getLineStartOffset(documentLine)
|
||||
val lineEndOffset = document.getLineEndOffset(documentLine)
|
||||
val lineText = document.getText(TextRange(lineStartOffset, lineEndOffset))
|
||||
|
||||
lineText == completionLines[i]
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
println("Error checking content at jump location: $error")
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fun cleanup() {
|
||||
clearJumpState()
|
||||
triggerInlineSuggestCallback = null
|
||||
deleteChainCallback = null
|
||||
}
|
||||
|
||||
private fun clearActiveHandler() {
|
||||
jumpHandler?.let { handler ->
|
||||
val activeHandlerManager = project.getService(ActiveHandlerManager::class.java)
|
||||
activeHandlerManager.clearActiveHandler()
|
||||
handler.dispose()
|
||||
}
|
||||
jumpHandler = null
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,373 @@
|
|||
package com.github.continuedev.continueintellijextension.nextEdit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.Position
|
||||
import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.intellij.codeInsight.inline.completion.InlineCompletionRequest
|
||||
import com.intellij.openapi.components.Service
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.LogicalPosition
|
||||
import com.intellij.openapi.project.Project
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
|
||||
interface NextEditService {
|
||||
suspend fun getNextEditSuggestion(
|
||||
completionId: String,
|
||||
filepath: String,
|
||||
line: Int,
|
||||
character: Int,
|
||||
withChain: Boolean = false,
|
||||
usingFullFileDiff: Boolean = true
|
||||
): NextEditOutcome?
|
||||
|
||||
suspend fun handleCase1(
|
||||
request: InlineCompletionRequest,
|
||||
editor: Editor,
|
||||
currCursorPos: Pair<Int, Int>,
|
||||
lastUuid: String?
|
||||
): NextEditOutcome?
|
||||
|
||||
suspend fun handleCase2(): NextEditOutcome?
|
||||
suspend fun handleCase3(editor: Editor, currentCursorPos: Pair<Int, Int>): NextEditOutcome?
|
||||
fun startChain()
|
||||
fun deleteChain()
|
||||
suspend fun chainExists(): Boolean
|
||||
suspend fun getNextInChain(): ProcessedItem?
|
||||
fun markDisplayed(completionId: String, outcome: NextEditOutcome)
|
||||
fun acceptEdit(completionId: String)
|
||||
fun rejectEdit(completionId: String)
|
||||
}
|
||||
|
||||
@Service(Service.Level.PROJECT)
|
||||
class ContinueNextEditService(private val project: Project) : NextEditService {
|
||||
private val displayedCompletions = mutableMapOf<String, NextEditOutcome>()
|
||||
|
||||
private val coreMessenger: CoreMessenger?
|
||||
get() = project.service<ContinuePluginService>().coreMessenger
|
||||
|
||||
// Case 1: Typing (chain does not exist).
|
||||
override suspend fun handleCase1(
|
||||
request: InlineCompletionRequest,
|
||||
editor: Editor,
|
||||
currCursorPos: Pair<Int, Int>,
|
||||
lastUuid: String?
|
||||
): NextEditOutcome? {
|
||||
// Start a new chain
|
||||
startChain()
|
||||
|
||||
val nextEditOutcome = this.getNextEditSuggestion(
|
||||
lastUuid!!,
|
||||
editor.virtualFile.url,
|
||||
currCursorPos.first,
|
||||
currCursorPos.second
|
||||
)
|
||||
|
||||
// TODO: Check once and if null, invoke inline completion trigger once more
|
||||
|
||||
return nextEditOutcome
|
||||
}
|
||||
|
||||
// Case 2: Jumping (chain exists, jump was taken).
|
||||
override suspend fun handleCase2(): NextEditOutcome? {
|
||||
val jumpManager = project.service<NextEditJumpManager>()
|
||||
|
||||
// Reset jump state
|
||||
jumpManager.setJumpInProgress(false)
|
||||
|
||||
// Use the saved completion from JumpManager instead of making new request
|
||||
val savedCompletion = jumpManager.getSavedCompletionAfterJump()
|
||||
if (savedCompletion != null) {
|
||||
val (_, outcome) = savedCompletion
|
||||
jumpManager.clearSavedCompletionAfterJump()
|
||||
return outcome
|
||||
} else {
|
||||
// This technically should not happen according to the TypeScript comment
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// Case 3: Accepting next edit outcome (chain exists, jump is not taken).
|
||||
override suspend fun handleCase3(editor: Editor, currentCursorPos: Pair<Int, Int>): NextEditOutcome? {
|
||||
val jumpManager = project.service<NextEditJumpManager>()
|
||||
|
||||
// Try suggesting jump for each location in the chain
|
||||
var isJumpSuggested = false
|
||||
|
||||
while (chainExists() && !isJumpSuggested) {
|
||||
val nextItemInChain = getNextInChain()
|
||||
if (nextItemInChain == null) {
|
||||
break
|
||||
}
|
||||
|
||||
val nextLocation = nextItemInChain.location
|
||||
val outcome = nextItemInChain.outcome
|
||||
|
||||
val currentPosition = LogicalPosition(currentCursorPos.first, currentCursorPos.second)
|
||||
val nextPosition = LogicalPosition(nextLocation.range.start.line, nextLocation.range.start.character)
|
||||
|
||||
isJumpSuggested = jumpManager.suggestJump(
|
||||
editor,
|
||||
currentPosition,
|
||||
nextPosition,
|
||||
outcome.completion
|
||||
)
|
||||
|
||||
if (isJumpSuggested) {
|
||||
// Store completion to be rendered after a jump
|
||||
jumpManager.setCompletionAfterJump(
|
||||
CompletionDataForAfterJump(
|
||||
completionId = outcome.completionId,
|
||||
outcome = outcome,
|
||||
position = nextPosition
|
||||
)
|
||||
)
|
||||
|
||||
// Don't display anything yet.
|
||||
// This will be handled in Case 2.
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
if (!isJumpSuggested) {
|
||||
deleteChain()
|
||||
return null
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
override suspend fun getNextEditSuggestion(
|
||||
completionId: String,
|
||||
filepath: String,
|
||||
line: Int,
|
||||
character: Int,
|
||||
withChain: Boolean,
|
||||
usingFullFileDiff: Boolean
|
||||
): NextEditOutcome? {
|
||||
val requestData = mapOf(
|
||||
"input" to mapOf(
|
||||
"completionId" to completionId,
|
||||
"filepath" to filepath,
|
||||
"pos" to mapOf("line" to line, "character" to character),
|
||||
"recentlyEditedRanges" to emptyList<Any>(),
|
||||
"recentlyVisitedRanges" to emptyList<Any>()
|
||||
),
|
||||
"options" to mapOf(
|
||||
"withChain" to withChain,
|
||||
"usingFullFileDiff" to usingFullFileDiff
|
||||
)
|
||||
)
|
||||
|
||||
return withTimeoutOrNull(5000.milliseconds) {
|
||||
suspendCancellableCoroutine { continuation ->
|
||||
coreMessenger?.request("nextEdit/predict", requestData, null) { response ->
|
||||
val outcome = parseNextEditOutcome(response)
|
||||
continuation.resume(outcome)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun startChain() {
|
||||
// Remove local chain creation
|
||||
coreMessenger?.request("nextEdit/startChain", emptyMap<String, Any>(), null) {}
|
||||
}
|
||||
|
||||
override fun deleteChain() {
|
||||
// Remove local chain deletion
|
||||
coreMessenger?.request("nextEdit/deleteChain", emptyMap<String, Any>(), null) {}
|
||||
}
|
||||
|
||||
override suspend fun chainExists(): Boolean {
|
||||
return suspendCancellableCoroutine { continuation ->
|
||||
coreMessenger?.request("nextEdit/isChainAlive", emptyMap<String, Any>(), null) { response ->
|
||||
val exists = parseChainExistsResponse(response)
|
||||
continuation.resume(exists)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getNextInChain(): ProcessedItem? {
|
||||
return suspendCancellableCoroutine { continuation ->
|
||||
coreMessenger?.request("nextEdit/queue/dequeueProcessed", emptyMap<String, Any>(), null) { response ->
|
||||
val processedItem = parseProcessedItem(response)
|
||||
// val nextEditItem = processedItem?.let { convertToNextEditItem(it) }
|
||||
continuation.resume(processedItem)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun markDisplayed(completionId: String, outcome: NextEditOutcome) {
|
||||
displayedCompletions[completionId] = outcome
|
||||
}
|
||||
|
||||
override fun acceptEdit(completionId: String) {
|
||||
coreMessenger?.request("nextEdit/accept", mapOf("completionId" to completionId), null) {}
|
||||
displayedCompletions.remove(completionId)
|
||||
}
|
||||
|
||||
override fun rejectEdit(completionId: String) {
|
||||
coreMessenger?.request("nextEdit/reject", mapOf("completionId" to completionId), null) {}
|
||||
displayedCompletions.remove(completionId)
|
||||
deleteChain()
|
||||
}
|
||||
|
||||
private fun parseNextEditOutcome(response: Any?): NextEditOutcome? {
|
||||
return try {
|
||||
val responseMap = response as? Map<String, Any> ?: return null
|
||||
val contentMap = responseMap["content"] as? Map<String, Any> ?: return null
|
||||
|
||||
parseNextEditOutcomeFromMap(contentMap)
|
||||
} catch (e: Exception) {
|
||||
println("Error parsing Next Edit outcome: ${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseNextEditOutcomeFromMap(contentMap: Map<String, Any>): NextEditOutcome? {
|
||||
return try {
|
||||
// Extract position data
|
||||
val cursorPos = contentMap["cursorPosition"] as? Map<String, Any>
|
||||
val cursorPosition = if (cursorPos != null) {
|
||||
Position(
|
||||
line = (cursorPos["line"] as? Number)?.toInt() ?: 0,
|
||||
character = (cursorPos["character"] as? Number)?.toInt() ?: 0
|
||||
)
|
||||
} else {
|
||||
Position(0, 0)
|
||||
}
|
||||
|
||||
val finalCursorPos = contentMap["finalCursorPosition"] as? Map<String, Any>
|
||||
val finalCursorPosition = if (finalCursorPos != null) {
|
||||
Position(
|
||||
line = (finalCursorPos["line"] as? Number)?.toInt() ?: 0,
|
||||
character = (finalCursorPos["character"] as? Number)?.toInt() ?: 0
|
||||
)
|
||||
} else {
|
||||
Position(0, 0)
|
||||
}
|
||||
|
||||
// Extract diffLines
|
||||
val diffLinesRaw = contentMap["diffLines"] as? List<Map<String, Any>> ?: emptyList()
|
||||
val diffLines = diffLinesRaw.map { diffLineMap ->
|
||||
DiffLine(
|
||||
type = diffLineMap["type"] as? String ?: "same",
|
||||
line = diffLineMap["line"] as? String ?: ""
|
||||
)
|
||||
}
|
||||
|
||||
// Construct NextEditOutcome from the map data
|
||||
NextEditOutcome(
|
||||
// TabAutocompleteOptions fields
|
||||
disable = contentMap["disable"] as? Boolean ?: false,
|
||||
maxPromptTokens = (contentMap["maxPromptTokens"] as? Number)?.toInt() ?: 2048,
|
||||
debounceDelay = (contentMap["debounceDelay"] as? Number)?.toInt() ?: 150,
|
||||
maxSuffixPercentage = (contentMap["maxSuffixPercentage"] as? Number)?.toInt() ?: 25,
|
||||
prefixPercentage = (contentMap["prefixPercentage"] as? Number)?.toInt() ?: 85,
|
||||
transform = contentMap["transform"] as? Boolean,
|
||||
template = contentMap["template"] as? String,
|
||||
multilineCompletions = contentMap["multilineCompletions"] as? String ?: "auto",
|
||||
slidingWindowPrefixPercentage = (contentMap["slidingWindowPrefixPercentage"] as? Number)?.toInt() ?: 75,
|
||||
slidingWindowSize = (contentMap["slidingWindowSize"] as? Number)?.toInt() ?: 500,
|
||||
useCache = contentMap["useCache"] as? Boolean ?: true,
|
||||
onlyMyCode = contentMap["onlyMyCode"] as? Boolean ?: true,
|
||||
useRecentlyEdited = contentMap["useRecentlyEdited"] as? Boolean ?: true,
|
||||
disableInFiles = contentMap["disableInFiles"] as? List<String>,
|
||||
useImports = contentMap["useImports"] as? Boolean,
|
||||
showWhateverWeHaveAtXMs = (contentMap["showWhateverWeHaveAtXMs"] as? Number)?.toInt(),
|
||||
|
||||
// Autocomplete fields
|
||||
elapsed = (contentMap["elapsed"] as? Number)?.toLong() ?: 0L,
|
||||
modelProvider = contentMap["modelProvider"] as? String ?: "",
|
||||
modelName = contentMap["modelName"] as? String ?: "",
|
||||
completionOptions = contentMap["completionOptions"] ?: emptyMap<String, Any>(),
|
||||
completionId = contentMap["completionId"] as? String ?: "",
|
||||
gitRepo = contentMap["gitRepo"] as? String,
|
||||
uniqueId = contentMap["uniqueId"] as? String ?: "",
|
||||
timestamp = (contentMap["timestamp"] as? Number)?.toLong() ?: System.currentTimeMillis(),
|
||||
|
||||
// Next Edit specific fields
|
||||
fileUri = contentMap["fileUri"] as? String ?: "",
|
||||
workspaceDirUri = contentMap["workspaceDirUri"] as? String ?: "",
|
||||
prompt = contentMap["prompt"] as? String ?: "",
|
||||
userEdits = contentMap["userEdits"] as? String ?: "",
|
||||
userExcerpts = contentMap["userExcerpts"] as? String ?: "",
|
||||
originalEditableRange = contentMap["originalEditableRange"] as? String ?: "",
|
||||
completion = contentMap["completion"] as? String ?: "",
|
||||
cursorPosition = cursorPosition,
|
||||
finalCursorPosition = finalCursorPosition,
|
||||
accepted = contentMap["accepted"] as? Boolean,
|
||||
editableRegionStartLine = (contentMap["editableRegionStartLine"] as? Number)?.toInt() ?: 0,
|
||||
editableRegionEndLine = (contentMap["editableRegionEndLine"] as? Number)?.toInt() ?: 0,
|
||||
diffLines = diffLines
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
println("Error parsing NextEditOutcome from map: ${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseProcessedItem(response: Any?): ProcessedItem? {
|
||||
return try {
|
||||
val responseMap = response as? Map<String, Any> ?: return null
|
||||
val content = responseMap["content"] as Map<String, Any> ?: return null
|
||||
|
||||
// Parse location (RangeInFile)
|
||||
val locationMap = content["location"] as? Map<String, Any> ?: return null
|
||||
val filepath = locationMap["filepath"] as? String ?: return null
|
||||
|
||||
val rangeMap = locationMap["range"] as? Map<String, Any> ?: return null
|
||||
val startMap = rangeMap["start"] as? Map<String, Any> ?: return null
|
||||
val endMap = rangeMap["end"] as? Map<String, Any> ?: return null
|
||||
|
||||
val startPosition = Position(
|
||||
line = (startMap["line"] as? Number)?.toInt() ?: 0,
|
||||
character = (startMap["character"] as? Number)?.toInt() ?: 0
|
||||
)
|
||||
|
||||
val endPosition = Position(
|
||||
line = (endMap["line"] as? Number)?.toInt() ?: 0,
|
||||
character = (endMap["character"] as? Number)?.toInt() ?: 0
|
||||
)
|
||||
|
||||
val range = com.github.continuedev.continueintellijextension.Range(startPosition, endPosition)
|
||||
val location = com.github.continuedev.continueintellijextension.RangeInFile(filepath, range)
|
||||
|
||||
// Parse outcome (NextEditOutcome) - reuse existing logic from parseNextEditOutcome
|
||||
val outcomeData = content["outcome"] as? Map<String, Any> ?: return null
|
||||
val outcome = parseNextEditOutcomeFromMap(outcomeData) ?: return null
|
||||
|
||||
ProcessedItem(location, outcome)
|
||||
} catch (e: Exception) {
|
||||
println("Error parsing ProcessedItem: ${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseChainExistsResponse(response: Any?): Boolean {
|
||||
return try {
|
||||
val responseMap = response as? Map<String, Any> ?: return false
|
||||
val content = responseMap["content"] ?: return false
|
||||
content as? Boolean ?: false
|
||||
} catch (e: Exception) {
|
||||
println("Error parsing chain exists response: ${e.message}")
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun convertToNextEditItem(processedItem: ProcessedItem): NextEditItem {
|
||||
// Convert ProcessedItem from core to NextEditItem for JetBrains
|
||||
// Implementation depends on ProcessedItem structure
|
||||
TODO("Implement conversion from ProcessedItem to NextEditItem")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
data class NextEditItem(
|
||||
val outcome: NextEditOutcome,
|
||||
val jumpLocation: LogicalPosition
|
||||
)
|
||||
|
|
@ -0,0 +1,148 @@
|
|||
package com.github.continuedev.continueintellijextension.nextEdit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.FimResult
|
||||
import com.github.continuedev.continueintellijextension.auth.ContinueAuthService
|
||||
import com.github.continuedev.continueintellijextension.`continue`.ProfileInfoService
|
||||
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.project.Project
|
||||
|
||||
sealed class NextEditModelMatcher {
|
||||
abstract fun matches(modelName: String?, title: String?): Boolean
|
||||
|
||||
data object MercuryCoder : NextEditModelMatcher() {
|
||||
override fun matches(modelName: String?, title: String?): Boolean =
|
||||
modelName?.lowercase()?.contains("mercury-coder") == true ||
|
||||
title?.lowercase()?.contains("mercury-coder") == true
|
||||
}
|
||||
|
||||
data object Instinct : NextEditModelMatcher() {
|
||||
override fun matches(modelName: String?, title: String?): Boolean =
|
||||
modelName?.lowercase()?.contains("instinct") == true ||
|
||||
title?.lowercase()?.contains("instinct") == true
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val allMatchers = listOf(MercuryCoder, Instinct)
|
||||
|
||||
fun isSupported(modelName: String?, title: String?): Boolean =
|
||||
allMatchers.any { it.matches(modelName, title) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
object NextEditUtils {
|
||||
suspend fun isNextEditSupported(project: Project): Boolean {
|
||||
return try {
|
||||
// NOTE: Quick filter for non-continue users.
|
||||
// Remove this once we have a FIM - Next Edit toggle UI.
|
||||
val authService = project.service<ContinueAuthService>()
|
||||
val sessionInfo = authService.loadControlPlaneSessionInfo()
|
||||
val userEmail = sessionInfo?.account?.id
|
||||
|
||||
if (userEmail == null || !userEmail.endsWith("@continue.dev")) {
|
||||
return false
|
||||
}
|
||||
|
||||
val profileInfoService = project.service<ProfileInfoService>()
|
||||
val selectedModelByRole = profileInfoService.fetchSelectedModelByRoleOrNull()
|
||||
|
||||
// Use the existing utility function
|
||||
val autocompleteModel = selectedModelByRole?.get("autocomplete").castNestedOrNull<Map<String, Any>>()
|
||||
|
||||
if (autocompleteModel != null) {
|
||||
val modelName = autocompleteModel["model"] as? String ?: ""
|
||||
val title = autocompleteModel["title"] as? String
|
||||
val capabilities = autocompleteModel["capabilities"].castNestedOrNull<Map<String, Any>>()
|
||||
|
||||
isNextEditModel(modelName, title, capabilities)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
println("Error checking Next Edit support: ${e.message}")
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun isNextEditModel(
|
||||
model: String,
|
||||
title: String?,
|
||||
capabilities: Map<String, Any>?
|
||||
): Boolean {
|
||||
// Check capabilities first - this takes precedence.
|
||||
val hasNextEditCapability = capabilities?.get("nextEdit") as? Boolean ?: false
|
||||
|
||||
// Check model name and title against known Next Edit models.
|
||||
return hasNextEditCapability || NextEditModelMatcher.isSupported(model, title)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the diff is indeed a FIM (Fill-In-Middle).
|
||||
* @param oldEditRange Original string content.
|
||||
* @param newEditRange New string content.
|
||||
* @param cursorPosition The position of the cursor in the old string.
|
||||
* @return A Pair where the first value is a boolean indicating if the change is purely additive (FIM)
|
||||
* and the second value is the FIM text content or null if not a FIM.
|
||||
*/
|
||||
fun checkFim(
|
||||
oldEditRange: String,
|
||||
newEditRange: String,
|
||||
cursorPosition: Pair<Int, Int> // line, character
|
||||
): FimResult {
|
||||
// Find the common prefix
|
||||
var prefixLength = 0
|
||||
while (prefixLength < oldEditRange.length &&
|
||||
prefixLength < newEditRange.length &&
|
||||
oldEditRange[prefixLength] == newEditRange[prefixLength]
|
||||
) {
|
||||
prefixLength++
|
||||
}
|
||||
|
||||
// Find the common suffix
|
||||
var oldSuffixPos = oldEditRange.length - 1
|
||||
var newSuffixPos = newEditRange.length - 1
|
||||
|
||||
while (oldSuffixPos >= prefixLength &&
|
||||
newSuffixPos >= prefixLength &&
|
||||
oldEditRange[oldSuffixPos] == newEditRange[newSuffixPos]
|
||||
) {
|
||||
oldSuffixPos--
|
||||
newSuffixPos--
|
||||
}
|
||||
|
||||
// The old text is purely preserved if:
|
||||
// 1. The prefix ends before or at the cursor.
|
||||
// 2. The suffix starts after or at the cursor.
|
||||
// 3. There's no gap between prefix and suffix in the old text.
|
||||
|
||||
val suffixStartInOld = oldSuffixPos + 1
|
||||
val suffixStartInNew = newSuffixPos + 1
|
||||
|
||||
// Convert cursor position to an offset in the string.
|
||||
// For simplicity, we need to calculate the cursor's position in the string.
|
||||
// This requires knowledge of line endings in the oldEditRange.
|
||||
val lines = oldEditRange.substring(0, prefixLength).split("\n")
|
||||
val cursorOffset = if (lines.size > 1) {
|
||||
lines.dropLast(1).sumOf { it.length + 1 } + cursorPosition.second
|
||||
} else {
|
||||
cursorPosition.second
|
||||
}
|
||||
|
||||
// Check if the cursor is positioned between the prefix and suffix.
|
||||
val cursorBetweenPrefixAndSuffix =
|
||||
prefixLength <= cursorOffset && cursorOffset <= suffixStartInOld
|
||||
|
||||
// Check if the old text is completely preserved (no deletion).
|
||||
val noTextDeleted = suffixStartInOld - prefixLength <= 0
|
||||
|
||||
val isFim = cursorBetweenPrefixAndSuffix && noTextDeleted
|
||||
|
||||
return if (isFim) {
|
||||
// Extract the content between prefix and suffix in the new string.
|
||||
FimResult.FimEdit(newEditRange.substring(prefixLength, suffixStartInNew))
|
||||
} else {
|
||||
FimResult.NotFimEdit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
package com.github.continuedev.continueintellijextension.nextEdit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.listeners.CursorMovementHandler
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.LogicalPosition
|
||||
import com.intellij.openapi.project.Project
|
||||
|
||||
/**
|
||||
* Handler for cursor movements during next edit window operations.
|
||||
*/
|
||||
class NextEditWindowHandler(
|
||||
private val project: Project,
|
||||
private val windowManager: NextEditWindowManager,
|
||||
private val expectedPosition: LogicalPosition
|
||||
) : CursorMovementHandler {
|
||||
|
||||
override val handlerId = "nextEditWindow"
|
||||
|
||||
override suspend fun onCursorMoved(
|
||||
editor: Editor,
|
||||
oldPosition: LogicalPosition?,
|
||||
newPosition: LogicalPosition
|
||||
): Boolean {
|
||||
// Check if window was just accepted
|
||||
if (windowManager.hasAccepted()) {
|
||||
return true
|
||||
}
|
||||
|
||||
// Check if cursor is still near the expected position (within the same line)
|
||||
if (newPosition.line == expectedPosition.line) {
|
||||
return true
|
||||
}
|
||||
|
||||
// User moved away from the suggestion area - close window and treat as deliberate
|
||||
windowManager.hideAllNextEditWindows()
|
||||
return false
|
||||
}
|
||||
|
||||
override fun onDeactivated() {
|
||||
println("NextEditWindowHandler: Deactivated")
|
||||
}
|
||||
|
||||
override fun dispose() {
|
||||
onDeactivated()
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,934 @@
|
|||
package com.github.continuedev.continueintellijextension.nextEdit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.Position
|
||||
import com.github.continuedev.continueintellijextension.listeners.ActiveHandlerManager
|
||||
import com.github.continuedev.continueintellijextension.utils.InlineCompletionUtils
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.application.EDT
|
||||
import com.intellij.openapi.command.WriteCommandAction
|
||||
import com.intellij.openapi.components.Service
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.LogicalPosition
|
||||
import com.intellij.openapi.editor.colors.EditorColorsManager
|
||||
import com.intellij.openapi.editor.markup.*
|
||||
import com.intellij.openapi.fileEditor.FileDocumentManager
|
||||
import com.intellij.openapi.fileTypes.FileType
|
||||
import com.intellij.openapi.fileTypes.FileTypeManager
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.ui.popup.JBPopup
|
||||
import com.intellij.openapi.ui.popup.JBPopupFactory
|
||||
import com.intellij.openapi.util.TextRange
|
||||
import com.intellij.ui.JBColor
|
||||
import com.intellij.ui.components.JBPanel
|
||||
import com.intellij.util.ui.JBUI
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.launch
|
||||
import java.awt.*
|
||||
import java.awt.event.ActionEvent
|
||||
import java.awt.event.KeyEvent
|
||||
import java.awt.geom.RoundRectangle2D
|
||||
import javax.swing.*
|
||||
import javax.swing.border.AbstractBorder
|
||||
|
||||
@Service(Service.Level.PROJECT)
|
||||
class NextEditWindowManager(private val project: Project) {
|
||||
private val coroutineScope = CoroutineScope(Dispatchers.Default + SupervisorJob())
|
||||
|
||||
private var currentPopup: JBPopup? = null
|
||||
private var deletionHighlighters: List<RangeHighlighter> = emptyList()
|
||||
private var isAccepted = false
|
||||
private var currentCompletionId: String? = null
|
||||
|
||||
// Handler management
|
||||
private var windowHandler: NextEditWindowHandler? = null
|
||||
|
||||
suspend fun showNextEditWindow(
|
||||
editor: Editor,
|
||||
currCursorPos: Position,
|
||||
editableRegionStartLine: Int,
|
||||
editableRegionEndLine: Int,
|
||||
oldCode: String,
|
||||
newCode: String,
|
||||
diffLines: List<DiffLine>
|
||||
) {
|
||||
// Clear existing decorations first
|
||||
hideAllNextEditWindows()
|
||||
|
||||
// Register active handler for this window
|
||||
val cursorPosition = LogicalPosition(currCursorPos.line, currCursorPos.character)
|
||||
windowHandler = NextEditWindowHandler(project, this, cursorPosition)
|
||||
val activeHandlerManager = project.getService(ActiveHandlerManager::class.java)
|
||||
activeHandlerManager.setActiveHandler(windowHandler!!)
|
||||
|
||||
// Determine if this is a line deletion case
|
||||
val isLineDelete = determineIfLineDelete(
|
||||
editor,
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
oldCode,
|
||||
newCode,
|
||||
diffLines
|
||||
)
|
||||
|
||||
// Show the code popup with the new suggestion
|
||||
showCodePopup(editor, newCode, diffLines) { action ->
|
||||
when (action) {
|
||||
PopupAction.ACCEPT -> acceptEdit(
|
||||
editor,
|
||||
newCode,
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
isLineDelete
|
||||
)
|
||||
|
||||
PopupAction.REJECT -> rejectEdit()
|
||||
}
|
||||
}
|
||||
|
||||
// Render deletion strikethroughs in the editor
|
||||
renderDeletionDecorations(editor, oldCode, newCode, editableRegionStartLine)
|
||||
}
|
||||
|
||||
private fun determineIfLineDelete(
|
||||
editor: Editor,
|
||||
editableRegionStartLine: Int,
|
||||
editableRegionEndLine: Int,
|
||||
oldCode: String,
|
||||
newCode: String,
|
||||
diffLines: List<DiffLine>
|
||||
): Boolean {
|
||||
// Check if new code is empty and we're dealing with a single line
|
||||
if (newCode != "" || editableRegionStartLine != editableRegionEndLine) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check if diffLines contains only deletions (no additions)
|
||||
val onlyDeletions = diffLines.all { it.type == "old" || it.type == "same" }
|
||||
val hasDeletedLine = diffLines.any { it.type == "old" }
|
||||
|
||||
if (!onlyDeletions || !hasDeletedLine) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Fix: Use the correct method to get line text
|
||||
val startOffset = editor.document.getLineStartOffset(editableRegionStartLine)
|
||||
val endOffset = editor.document.getLineEndOffset(editableRegionStartLine)
|
||||
val line = editor.document.getText(TextRange(startOffset, endOffset))
|
||||
val oldLine = oldCode.trim()
|
||||
|
||||
return line.trim() == oldLine || line.trim().isEmpty()
|
||||
}
|
||||
|
||||
private fun showCodePopup(
|
||||
editor: Editor,
|
||||
code: String,
|
||||
diffLines: List<DiffLine>,
|
||||
onAction: (PopupAction) -> Unit
|
||||
) {
|
||||
val popupComponent = createNextEditPopupComponent(editor, code, diffLines, onAction)
|
||||
|
||||
val popup = JBPopupFactory.getInstance()
|
||||
.createComponentPopupBuilder(popupComponent, popupComponent)
|
||||
.setFocusable(true)
|
||||
.setRequestFocus(true)
|
||||
.setResizable(false)
|
||||
.setMovable(false)
|
||||
.setCancelOnClickOutside(false)
|
||||
.setCancelOnWindowDeactivation(false)
|
||||
.setCancelKeyEnabled(false)
|
||||
.setCancelCallback {
|
||||
onAction(PopupAction.REJECT)
|
||||
true
|
||||
}
|
||||
.createPopup()
|
||||
|
||||
currentPopup = popup
|
||||
|
||||
// Show popup and ensure focus
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
try {
|
||||
val caretPosition = editor.caretModel.primaryCaret.logicalPosition
|
||||
val currentLine = caretPosition.line
|
||||
val lineEndOffset = editor.document.getLineEndOffset(currentLine)
|
||||
val lineText = editor.document.getText(
|
||||
TextRange(
|
||||
editor.document.getLineStartOffset(currentLine),
|
||||
lineEndOffset
|
||||
)
|
||||
)
|
||||
|
||||
val endOfLinePosition = LogicalPosition(currentLine, lineText.length + 4)
|
||||
val endOfLinePoint = editor.logicalPositionToXY(endOfLinePosition)
|
||||
|
||||
val editorComponent = editor.contentComponent
|
||||
val screenPoint = java.awt.Point(endOfLinePoint.x, endOfLinePoint.y)
|
||||
javax.swing.SwingUtilities.convertPointToScreen(screenPoint, editorComponent)
|
||||
|
||||
popup.showInScreenCoordinates(editorComponent, screenPoint)
|
||||
|
||||
// Add ONLY the popup content border with rounded corners
|
||||
val content = popup.content
|
||||
if (content is JComponent) {
|
||||
content.border = object : AbstractBorder() {
|
||||
override fun paintBorder(c: Component, g: Graphics, x: Int, y: Int, width: Int, height: Int) {
|
||||
val g2 = g.create() as Graphics2D
|
||||
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
|
||||
|
||||
val arc = 6f
|
||||
g2.color = Color(0x999998)
|
||||
g2.stroke = BasicStroke(1f)
|
||||
g2.draw(
|
||||
RoundRectangle2D.Float(
|
||||
x.toFloat(),
|
||||
y.toFloat(),
|
||||
width.toFloat() - 1f,
|
||||
height.toFloat() - 1f,
|
||||
arc,
|
||||
arc
|
||||
)
|
||||
)
|
||||
g2.dispose()
|
||||
}
|
||||
|
||||
override fun getBorderInsets(c: Component): Insets = JBUI.insets(1)
|
||||
}
|
||||
}
|
||||
|
||||
// Force focus after popup is shown
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
popupComponent.requestFocusInWindow()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
popup.showInBestPositionFor(editor)
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
popupComponent.requestFocusInWindow()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun createNextEditPopupComponent(
|
||||
editor: Editor,
|
||||
code: String,
|
||||
diffLines: List<DiffLine>,
|
||||
onAction: (PopupAction) -> Unit
|
||||
): JComponent {
|
||||
val panel = JBPanel<JBPanel<*>>().apply {
|
||||
layout = BorderLayout()
|
||||
// border = JBUI.Borders.empty(8, 12)
|
||||
border = null
|
||||
background = EditorColorsManager.getInstance().globalScheme.defaultBackground
|
||||
// No custom paintComponent - just use regular panel
|
||||
}
|
||||
|
||||
// Create syntax-highlighted code display
|
||||
val codePanel = createCodeDisplayPanel(editor, code, diffLines)
|
||||
panel.add(codePanel, BorderLayout.CENTER)
|
||||
|
||||
// Add keyboard shortcuts
|
||||
addKeyboardShortcuts(panel, onAction)
|
||||
|
||||
return panel
|
||||
}
|
||||
|
||||
private fun getActualFontSizeFromEditor(editor: Editor): Int {
|
||||
try {
|
||||
val component = editor.contentComponent
|
||||
val font = component.font
|
||||
val graphics = component.graphics
|
||||
|
||||
if (graphics != null) {
|
||||
val fontMetrics = graphics.getFontMetrics(font)
|
||||
val height = fontMetrics.height
|
||||
val ascent = fontMetrics.ascent
|
||||
|
||||
// Check for DPI scaling
|
||||
val scale = JBUI.scale(1f)
|
||||
|
||||
// Adjust for DPI scaling
|
||||
val adjustedFontSize = if (scale > 1f) {
|
||||
(font.size / scale).toInt()
|
||||
} else {
|
||||
font.size
|
||||
}
|
||||
|
||||
return adjustedFontSize
|
||||
}
|
||||
|
||||
} catch (e: Exception) {
|
||||
println("DEBUG: Error getting font size: ${e.message}")
|
||||
}
|
||||
|
||||
return 13
|
||||
}
|
||||
|
||||
private fun createCodeDisplayPanel(editor: Editor, code: String, diffLines: List<DiffLine>): JComponent {
|
||||
try {
|
||||
val scheme = EditorColorsManager.getInstance().globalScheme
|
||||
val editorFont = editor.colorsScheme.getFont(com.intellij.openapi.editor.colors.EditorFontType.PLAIN)
|
||||
|
||||
// Get the actual font size accounting for DPI scaling
|
||||
val actualFontSize = getActualFontSizeFromEditor(editor)
|
||||
val fontFamily = editorFont.family
|
||||
|
||||
// Also get the line height from editor for consistent spacing
|
||||
val editorLineHeight = editor.lineHeight
|
||||
val uiScale = JBUI.scale(1f)
|
||||
// val adjustedLineHeight = if (uiScale > 1f) (editorLineHeight / uiScale).toInt() else editorLineHeight
|
||||
|
||||
val adjustedLineHeight = actualFontSize
|
||||
|
||||
// Get file type for proper syntax highlighting
|
||||
val fileType = getCurrentFileType(editor)
|
||||
|
||||
// Create panel with proper layout
|
||||
val panel = JPanel().apply {
|
||||
layout = BoxLayout(this, BoxLayout.Y_AXIS)
|
||||
background = scheme.defaultBackground
|
||||
border = null
|
||||
isOpaque = true
|
||||
}
|
||||
|
||||
val visibleLines = diffLines.filter { it.type != "old" }
|
||||
val linesToDisplay = if (visibleLines.isEmpty()) {
|
||||
if (code.isNotEmpty()) {
|
||||
code.split("\n").map { DiffLine(type = "new", line = it) }
|
||||
} else {
|
||||
listOf(DiffLine(type = "new", line = " "))
|
||||
}
|
||||
} else {
|
||||
visibleLines
|
||||
}
|
||||
|
||||
var maxWidth = 200
|
||||
|
||||
// Create syntax-highlighted labels for each line
|
||||
linesToDisplay.forEach { diffLine ->
|
||||
val displayText = if (diffLine.line.isEmpty()) " " else diffLine.line
|
||||
|
||||
val backgroundColor = when (diffLine.type) {
|
||||
"new" -> JBColor(0x2D4A2D, 0x2D4A2D)
|
||||
"same" -> scheme.defaultBackground
|
||||
else -> scheme.defaultBackground
|
||||
}
|
||||
|
||||
val highlightedHtml = createSyntaxHighlightedHtml(
|
||||
displayText,
|
||||
fileType,
|
||||
scheme,
|
||||
fontFamily,
|
||||
actualFontSize,
|
||||
adjustedLineHeight, // Pass the adjusted line height
|
||||
backgroundColor
|
||||
)
|
||||
|
||||
val label = JLabel(highlightedHtml).apply {
|
||||
background = backgroundColor
|
||||
isOpaque = true
|
||||
border = JBUI.Borders.empty(1, 6)
|
||||
alignmentX = Component.LEFT_ALIGNMENT
|
||||
|
||||
// Create font with correct size
|
||||
font = Font(fontFamily, editorFont.style, actualFontSize)
|
||||
}
|
||||
|
||||
maxWidth = maxOf(maxWidth, label.preferredSize.width + 12)
|
||||
panel.add(label)
|
||||
}
|
||||
|
||||
panel.revalidate()
|
||||
val contentHeight = maxOf(panel.preferredSize.height, 20)
|
||||
|
||||
return JScrollPane(panel).apply {
|
||||
border = null
|
||||
preferredSize = Dimension(maxWidth, contentHeight)
|
||||
minimumSize = Dimension(200, 20)
|
||||
maximumSize = Dimension(800, 300)
|
||||
horizontalScrollBarPolicy = JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED
|
||||
verticalScrollBarPolicy = JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
|
||||
viewport.background = scheme.defaultBackground
|
||||
background = scheme.defaultBackground
|
||||
}
|
||||
|
||||
} catch (e: Exception) {
|
||||
println("ERROR: createCodeDisplayPanel failed: ${e.message}")
|
||||
e.printStackTrace()
|
||||
return JLabel("Code preview unavailable").apply {
|
||||
border = JBUI.Borders.empty(10)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun createSyntaxHighlightedHtml(
|
||||
text: String,
|
||||
fileType: FileType,
|
||||
scheme: com.intellij.openapi.editor.colors.EditorColorsScheme,
|
||||
fontFamily: String,
|
||||
fontSize: Int,
|
||||
lineHeight: Int,
|
||||
backgroundColor: Color
|
||||
): String {
|
||||
// Convert background color to hex
|
||||
val backgroundHex =
|
||||
String.format("#%02x%02x%02x", backgroundColor.red, backgroundColor.green, backgroundColor.blue)
|
||||
|
||||
if (text.trim().isEmpty()) {
|
||||
return "<html><body style='margin:0; padding:2px 6px; background-color:$backgroundHex;'>" +
|
||||
"<div style='font-family:\"$fontFamily\"; font-size:${fontSize}px; line-height:${lineHeight}px; background-color:$backgroundHex;'> </div>" +
|
||||
"</body></html>"
|
||||
}
|
||||
|
||||
try {
|
||||
// Get the syntax highlighter for the file type
|
||||
val syntaxHighlighter =
|
||||
com.intellij.openapi.fileTypes.SyntaxHighlighterFactory.getSyntaxHighlighter(fileType, project, null)
|
||||
?: return createBasicHtml(
|
||||
text,
|
||||
fontFamily,
|
||||
fontSize,
|
||||
lineHeight,
|
||||
scheme,
|
||||
backgroundColor
|
||||
) // Updated call
|
||||
|
||||
val lexer = syntaxHighlighter.highlightingLexer
|
||||
lexer.start(text)
|
||||
|
||||
val highlightedText = StringBuilder()
|
||||
var lastOffset = 0
|
||||
|
||||
while (lexer.tokenType != null) {
|
||||
val tokenStart = lexer.tokenStart
|
||||
val tokenEnd = lexer.tokenEnd
|
||||
val tokenType = lexer.tokenType
|
||||
val tokenText = text.substring(tokenStart, tokenEnd)
|
||||
|
||||
// Add any text between tokens
|
||||
if (tokenStart > lastOffset) {
|
||||
val defaultColor = scheme.defaultForeground
|
||||
val defaultColorHex =
|
||||
String.format("#%02x%02x%02x", defaultColor.red, defaultColor.green, defaultColor.blue)
|
||||
highlightedText.append(
|
||||
"<span style='color:$defaultColorHex'>${
|
||||
escapeHtml(
|
||||
text.substring(
|
||||
lastOffset,
|
||||
tokenStart
|
||||
)
|
||||
)
|
||||
}</span>"
|
||||
)
|
||||
}
|
||||
|
||||
// Get TextAttributesKey from the syntax highlighter
|
||||
val textAttributesKeys = syntaxHighlighter.getTokenHighlights(tokenType)
|
||||
|
||||
if (textAttributesKeys.isNotEmpty()) {
|
||||
// Use the first (most specific) attributes key
|
||||
val textAttributes = scheme.getAttributes(textAttributesKeys[0])
|
||||
val color = textAttributes?.foregroundColor ?: scheme.defaultForeground
|
||||
|
||||
val colorHex = String.format("#%02x%02x%02x", color.red, color.green, color.blue)
|
||||
|
||||
var styledToken = "<span style='color:$colorHex"
|
||||
|
||||
// Add font style if needed
|
||||
if (textAttributes != null && textAttributes.fontType != 0) {
|
||||
if (textAttributes.fontType and Font.BOLD != 0) {
|
||||
styledToken += "; font-weight:bold"
|
||||
}
|
||||
if (textAttributes.fontType and Font.ITALIC != 0) {
|
||||
styledToken += "; font-style:italic"
|
||||
}
|
||||
}
|
||||
|
||||
styledToken += "'>${escapeHtml(tokenText)}</span>"
|
||||
highlightedText.append(styledToken)
|
||||
} else {
|
||||
// No specific highlighting, use default color
|
||||
val defaultColor = scheme.defaultForeground
|
||||
val defaultColorHex =
|
||||
String.format("#%02x%02x%02x", defaultColor.red, defaultColor.green, defaultColor.blue)
|
||||
highlightedText.append("<span style='color:$defaultColorHex'>${escapeHtml(tokenText)}</span>")
|
||||
}
|
||||
|
||||
lastOffset = tokenEnd
|
||||
lexer.advance()
|
||||
}
|
||||
|
||||
// Add any remaining text
|
||||
if (lastOffset < text.length) {
|
||||
val defaultColor = scheme.defaultForeground
|
||||
val defaultColorHex =
|
||||
String.format("#%02x%02x%02x", defaultColor.red, defaultColor.green, defaultColor.blue)
|
||||
highlightedText.append("<span style='color:$defaultColorHex'>${escapeHtml(text.substring(lastOffset))}</span>")
|
||||
}
|
||||
|
||||
val toReturn = "<html><body style='margin:0; padding:2px 6px; background-color:$backgroundHex;'>" +
|
||||
"<div style='font-family:\"$fontFamily\"; font-size:${fontSize}px; line-height:${lineHeight}px; background-color:$backgroundHex;'>$highlightedText</div>" +
|
||||
"</body></html>"
|
||||
return toReturn
|
||||
|
||||
} catch (e: Exception) {
|
||||
println("DEBUG: Syntax highlighting failed: ${e.message}")
|
||||
return createBasicHtml(text, fontFamily, fontSize, lineHeight, scheme, backgroundColor) // Updated call
|
||||
}
|
||||
}
|
||||
|
||||
private fun createBasicHtml(
|
||||
text: String,
|
||||
fontFamily: String,
|
||||
fontSize: Int,
|
||||
lineHeight: Int, // Added lineHeight parameter
|
||||
scheme: com.intellij.openapi.editor.colors.EditorColorsScheme,
|
||||
backgroundColor: Color
|
||||
): String {
|
||||
val foregroundColor = scheme.defaultForeground
|
||||
val foregroundHex =
|
||||
String.format("#%02x%02x%02x", foregroundColor.red, foregroundColor.green, foregroundColor.blue)
|
||||
val backgroundHex =
|
||||
String.format("#%02x%02x%02x", backgroundColor.red, backgroundColor.green, backgroundColor.blue)
|
||||
|
||||
return "<html><body style='margin:0; padding:2px 6px; background-color:$backgroundHex;'>" +
|
||||
"<div style='font-family:\"$fontFamily\"; font-size:${fontSize}px; line-height:${lineHeight}px; color:$foregroundHex; background-color:$backgroundHex;'>${
|
||||
escapeHtml(
|
||||
text
|
||||
)
|
||||
}</div>" +
|
||||
"</body></html>"
|
||||
}
|
||||
|
||||
private fun escapeHtml(text: String): String {
|
||||
return text
|
||||
.replace("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
.replace("\"", """)
|
||||
.replace("'", "'")
|
||||
.replace(" ", " ")
|
||||
.replace("\t", " ")
|
||||
}
|
||||
|
||||
// Then update getCurrentFileType to use it
|
||||
private fun getCurrentFileType(editor: Editor): FileType {
|
||||
// Method 1: Use the current editor's virtual file (most reliable)
|
||||
val virtualFile = FileDocumentManager.getInstance().getFile(editor.document)
|
||||
virtualFile?.let { file ->
|
||||
return file.fileType
|
||||
}
|
||||
|
||||
// Method 2: Try to get from FileEditorManager
|
||||
val fileEditorManager = com.intellij.openapi.fileEditor.FileEditorManager.getInstance(project)
|
||||
val currentFile = fileEditorManager.selectedFiles.firstOrNull()
|
||||
|
||||
currentFile?.let { file ->
|
||||
return file.fileType
|
||||
}
|
||||
|
||||
// Method 3: Fallback to plain text
|
||||
return FileTypeManager.getInstance().getFileTypeByExtension("txt")
|
||||
}
|
||||
|
||||
private fun createBasicHighlightedHtml(text: String, font: java.awt.Font): String {
|
||||
if (text.trim()
|
||||
.isEmpty()
|
||||
) return "<html><div style='font-family:${font.family}; font-size:${font.size}px; line-height:1.2; margin:0; padding:2px 4px;'> </div></html>"
|
||||
|
||||
// Basic syntax highlighting patterns (you can extend this)
|
||||
var highlightedText = text
|
||||
.replace("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
.replace(" ", " ") // Preserve spaces
|
||||
.replace("\t", " ") // Convert tabs to spaces
|
||||
|
||||
// Simple keyword highlighting (extend based on your needs)
|
||||
val keywords = arrayOf(
|
||||
"function", "const", "let", "var", "return", "if", "else", "for", "while",
|
||||
"class", "public", "private", "static", "void", "int", "String", "boolean",
|
||||
"def", "import", "from", "as", "try", "except", "finally", "with"
|
||||
)
|
||||
|
||||
keywords.forEach { keyword ->
|
||||
highlightedText = highlightedText.replace(
|
||||
Regex("\\b$keyword\\b"),
|
||||
"<span style='color:#569CD6'>$keyword</span>"
|
||||
)
|
||||
}
|
||||
|
||||
// String highlighting
|
||||
highlightedText = highlightedText.replace(
|
||||
Regex("\"([^\"]*)\"|'([^']*)'"),
|
||||
"<span style='color:#CE9178'>$0</span>"
|
||||
)
|
||||
|
||||
// Comment highlighting
|
||||
highlightedText = highlightedText.replace(
|
||||
Regex("//.*$", RegexOption.MULTILINE),
|
||||
"<span style='color:#6A9955'>$0</span>"
|
||||
)
|
||||
|
||||
// Use div instead of pre for better control over spacing
|
||||
return "<html><div style='font-family:${font.family}; font-size:${font.size}px; line-height:1.2; margin:0; padding:0; white-space:nowrap;'>$highlightedText</div></html>"
|
||||
}
|
||||
|
||||
private fun addKeyboardShortcuts(panel: JComponent, onAction: (PopupAction) -> Unit) {
|
||||
// CRITICAL FIX: Disable focus traversal for Tab key
|
||||
panel.setFocusTraversalKeysEnabled(false)
|
||||
|
||||
val inputMap = panel.getInputMap(JComponent.WHEN_FOCUSED)
|
||||
val actionMap = panel.actionMap
|
||||
|
||||
// Add Tab key for accept
|
||||
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "accept")
|
||||
actionMap.put("accept", object : AbstractAction() {
|
||||
override fun actionPerformed(e: ActionEvent?) {
|
||||
onAction(PopupAction.ACCEPT)
|
||||
}
|
||||
})
|
||||
|
||||
// Add Esc key for reject
|
||||
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "reject")
|
||||
actionMap.put("reject", object : AbstractAction() {
|
||||
override fun actionPerformed(e: ActionEvent?) {
|
||||
onAction(PopupAction.REJECT)
|
||||
}
|
||||
})
|
||||
|
||||
panel.isFocusable = true
|
||||
}
|
||||
|
||||
private fun renderDeletionDecorations(
|
||||
editor: Editor,
|
||||
oldCode: String,
|
||||
newCode: String,
|
||||
startLine: Int
|
||||
) {
|
||||
// Clear any existing decorations first
|
||||
clearAllDeletionDecorations()
|
||||
|
||||
val diffChars = calculateCharDiff(oldCode, newCode)
|
||||
|
||||
deletionHighlighters = diffChars.filter { it.type == "old" }.map { diff ->
|
||||
val lineStartOffset = editor.document.getLineStartOffset(startLine + diff.oldLineIndex!!)
|
||||
val startOffset = lineStartOffset + diff.oldCharIndexInLine!!
|
||||
val endOffset = startOffset + diff.char.length
|
||||
|
||||
editor.markupModel.addRangeHighlighter(
|
||||
startOffset,
|
||||
endOffset,
|
||||
HighlighterLayer.SELECTION - 1,
|
||||
TextAttributes().apply {
|
||||
backgroundColor =
|
||||
JBColor.namedColor("Editor.DiffDeletedLines.background", JBColor(0xFFE6E6, 0x484A4A))
|
||||
effectType = EffectType.STRIKEOUT
|
||||
effectColor = JBColor.namedColor("Editor.DiffDeletedLines.border", JBColor(0xD32F2F, 0xB71C1C))
|
||||
},
|
||||
HighlighterTargetArea.EXACT_RANGE
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun calculateCharDiff(oldCode: String, newCode: String): List<DiffChar> {
|
||||
// This is a simplified diff implementation
|
||||
// For a production-ready solution, consider adding a proper diff library like java-diff-utils
|
||||
|
||||
val result = mutableListOf<DiffChar>()
|
||||
|
||||
// Track indices as we process the diff
|
||||
var oldIndex = 0
|
||||
var newIndex = 0
|
||||
var oldLineIndex = 0
|
||||
var newLineIndex = 0
|
||||
var oldCharIndexInLine = 0
|
||||
var newCharIndexInLine = 0
|
||||
|
||||
// Convert strings to character arrays for easier processing
|
||||
val oldChars = oldCode.toCharArray()
|
||||
val newChars = newCode.toCharArray()
|
||||
|
||||
var i = 0
|
||||
var j = 0
|
||||
|
||||
// Simple longest common subsequence approach
|
||||
while (i < oldChars.size || j < newChars.size) {
|
||||
when {
|
||||
i < oldChars.size && j < newChars.size && oldChars[i] == newChars[j] -> {
|
||||
// Characters match - mark as "same"
|
||||
val char = oldChars[i].toString()
|
||||
|
||||
result.add(
|
||||
DiffChar(
|
||||
type = "same",
|
||||
char = char,
|
||||
oldIndex = oldIndex,
|
||||
newIndex = newIndex,
|
||||
oldLineIndex = oldLineIndex,
|
||||
newLineIndex = newLineIndex,
|
||||
oldCharIndexInLine = oldCharIndexInLine,
|
||||
newCharIndexInLine = newCharIndexInLine
|
||||
)
|
||||
)
|
||||
|
||||
// Update indices
|
||||
oldIndex++
|
||||
newIndex++
|
||||
|
||||
if (char == "\n") {
|
||||
oldLineIndex++
|
||||
newLineIndex++
|
||||
oldCharIndexInLine = 0
|
||||
newCharIndexInLine = 0
|
||||
} else {
|
||||
oldCharIndexInLine++
|
||||
newCharIndexInLine++
|
||||
}
|
||||
|
||||
i++
|
||||
j++
|
||||
}
|
||||
|
||||
i < oldChars.size && (j >= newChars.size || shouldDeleteChar(oldChars, newChars, i, j)) -> {
|
||||
// Character exists in old but not in new - mark as "old"
|
||||
val char = oldChars[i].toString()
|
||||
|
||||
result.add(
|
||||
DiffChar(
|
||||
type = "old",
|
||||
char = char,
|
||||
oldIndex = oldIndex,
|
||||
oldLineIndex = oldLineIndex,
|
||||
oldCharIndexInLine = oldCharIndexInLine
|
||||
)
|
||||
)
|
||||
|
||||
// Update old indices only
|
||||
oldIndex++
|
||||
if (char == "\n") {
|
||||
oldLineIndex++
|
||||
oldCharIndexInLine = 0
|
||||
} else {
|
||||
oldCharIndexInLine++
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
j < newChars.size -> {
|
||||
// Character exists in new but not in old - mark as "new"
|
||||
val char = newChars[j].toString()
|
||||
|
||||
result.add(
|
||||
DiffChar(
|
||||
type = "new",
|
||||
char = char,
|
||||
newIndex = newIndex,
|
||||
newLineIndex = newLineIndex,
|
||||
newCharIndexInLine = newCharIndexInLine
|
||||
)
|
||||
)
|
||||
|
||||
// Update new indices only
|
||||
newIndex++
|
||||
if (char == "\n") {
|
||||
newLineIndex++
|
||||
newCharIndexInLine = 0
|
||||
} else {
|
||||
newCharIndexInLine++
|
||||
}
|
||||
|
||||
j++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// Helper function to determine if a character should be considered deleted
|
||||
// This is a simplified heuristic - a proper diff algorithm would be more sophisticated
|
||||
private fun shouldDeleteChar(oldChars: CharArray, newChars: CharArray, i: Int, j: Int): Boolean {
|
||||
if (j >= newChars.size) return true
|
||||
|
||||
// Look ahead a few characters to see if we can find a match
|
||||
val lookAhead = minOf(5, oldChars.size - i, newChars.size - j)
|
||||
for (k in 1..lookAhead) {
|
||||
if (i + k < oldChars.size && oldChars[i] == newChars[j + k]) {
|
||||
return false // Found a match ahead, so insert new chars first
|
||||
}
|
||||
if (j + k < newChars.size && oldChars[i + k] == newChars[j]) {
|
||||
return true // Found a match ahead, so delete old char first
|
||||
}
|
||||
}
|
||||
|
||||
return true // Default to deletion
|
||||
}
|
||||
|
||||
private fun acceptEdit(
|
||||
editor: Editor,
|
||||
newText: String,
|
||||
startLine: Int,
|
||||
endLine: Int,
|
||||
isLineDelete: Boolean = false
|
||||
) {
|
||||
isAccepted = true
|
||||
|
||||
// Clear handler before making document changes that move cursor
|
||||
clearActiveHandler()
|
||||
|
||||
hideAllNextEditWindows()
|
||||
|
||||
try {
|
||||
// Fix: Use the simpler WriteCommandAction.runWriteCommandAction
|
||||
WriteCommandAction.runWriteCommandAction(project) {
|
||||
val document = editor.document
|
||||
|
||||
// Validate line indices
|
||||
val totalLines = document.lineCount
|
||||
|
||||
if (startLine < 0 || startLine >= totalLines) {
|
||||
return@runWriteCommandAction
|
||||
}
|
||||
|
||||
if (endLine < 0 || endLine >= totalLines) {
|
||||
return@runWriteCommandAction
|
||||
}
|
||||
|
||||
if (isLineDelete) {
|
||||
// Handle line deletion - include the newline character
|
||||
val startOffset = document.getLineStartOffset(startLine)
|
||||
var endOffset: Int
|
||||
|
||||
// If this isn't the last line, extend to include the newline character
|
||||
if (startLine < document.lineCount - 1) {
|
||||
endOffset = document.getLineStartOffset(startLine + 1)
|
||||
} else {
|
||||
// If it's the last line, just delete to end of line
|
||||
endOffset = document.getLineEndOffset(startLine)
|
||||
}
|
||||
|
||||
val oldText = document.getText(TextRange(startOffset, endOffset))
|
||||
|
||||
// Delete the entire line including newline
|
||||
document.deleteString(startOffset, endOffset)
|
||||
|
||||
} else {
|
||||
// Handle normal text replacement
|
||||
val startOffset = document.getLineStartOffset(startLine)
|
||||
val endOffset = document.getLineEndOffset(endLine)
|
||||
|
||||
if (startOffset < 0 || endOffset > document.textLength || startOffset > endOffset) {
|
||||
return@runWriteCommandAction
|
||||
}
|
||||
|
||||
// Show what we're replacing
|
||||
val oldText = document.getText(TextRange(startOffset, endOffset))
|
||||
|
||||
// Perform the replacement
|
||||
document.replaceString(startOffset, endOffset, newText)
|
||||
}
|
||||
}
|
||||
|
||||
coroutineScope.launch(Dispatchers.EDT) {
|
||||
InlineCompletionUtils.triggerInlineCompletion(
|
||||
editor,
|
||||
project
|
||||
)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
println("ERROR: Exception in acceptEdit: ${e.message}")
|
||||
e.printStackTrace()
|
||||
}
|
||||
|
||||
// Log acceptance (placeholder)
|
||||
currentCompletionId?.let {
|
||||
// project.getService(NextEditService::class.java).acceptEdit(it)
|
||||
}
|
||||
|
||||
isAccepted = false
|
||||
}
|
||||
|
||||
private fun rejectEdit() {
|
||||
clearActiveHandler()
|
||||
|
||||
hideAllNextEditWindows()
|
||||
|
||||
// Log rejection and delete chain (placeholder)
|
||||
currentCompletionId?.let {
|
||||
// project.getService(NextEditService::class.java).rejectEdit(it)
|
||||
}
|
||||
}
|
||||
|
||||
fun hideAllNextEditWindows() {
|
||||
currentPopup?.let { popup ->
|
||||
// Clear keyboard shortcuts before closing popup
|
||||
val content = popup.content
|
||||
if (content is JComponent) {
|
||||
content.inputMap.clear()
|
||||
content.actionMap.clear()
|
||||
}
|
||||
|
||||
popup.cancel()
|
||||
currentPopup = null
|
||||
}
|
||||
|
||||
// Clear all deletion decorations without tracking editors
|
||||
clearAllDeletionDecorations()
|
||||
deletionHighlighters = emptyList()
|
||||
|
||||
clearActiveHandler() // TODO: might be redundant
|
||||
}
|
||||
|
||||
private fun clearAllDeletionDecorations() {
|
||||
// Remove highlighters using their dispose method - they know which editor they belong to
|
||||
deletionHighlighters.forEach { highlighter ->
|
||||
try {
|
||||
highlighter.dispose()
|
||||
} catch (e: Exception) {
|
||||
// Highlighter might already be disposed, ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun clearActiveHandler() {
|
||||
windowHandler?.let { handler ->
|
||||
val activeHandlerManager = project.getService(ActiveHandlerManager::class.java)
|
||||
activeHandlerManager.clearActiveHandler()
|
||||
handler.dispose()
|
||||
}
|
||||
windowHandler = null
|
||||
}
|
||||
|
||||
fun hasAccepted(): Boolean = isAccepted
|
||||
|
||||
fun setAccepted(accepted: Boolean) {
|
||||
isAccepted = accepted
|
||||
}
|
||||
|
||||
fun updateCurrentCompletionId(completionId: String) {
|
||||
currentCompletionId = completionId
|
||||
}
|
||||
|
||||
fun cleanup() {
|
||||
hideAllNextEditWindows()
|
||||
currentCompletionId = null
|
||||
}
|
||||
}
|
||||
|
||||
enum class PopupAction {
|
||||
ACCEPT,
|
||||
REJECT
|
||||
}
|
||||
|
||||
data class DiffChar(
|
||||
val type: String, // "old", "new", "same"
|
||||
val char: String,
|
||||
val oldIndex: Int? = null, // Character index assuming a flattened line string
|
||||
val newIndex: Int? = null,
|
||||
val oldLineIndex: Int? = null, // Line index
|
||||
val newLineIndex: Int? = null,
|
||||
val oldCharIndexInLine: Int? = null, // Character index within the line
|
||||
val newCharIndexInLine: Int? = null
|
||||
)
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
package com.github.continuedev.continueintellijextension.nextEdit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.Position
|
||||
import com.github.continuedev.continueintellijextension.RangeInFile
|
||||
|
||||
//data class NextEditOutcome(
|
||||
// val completion: String,
|
||||
// val diffLines: List<DiffLine>,
|
||||
// val editableRegionStartLine: Int,
|
||||
// val editableRegionEndLine: Int,
|
||||
// val oldCode: String,
|
||||
// val newCode: String
|
||||
//)
|
||||
|
||||
data class DiffLine(
|
||||
val type: String, // "old", "new", "same"
|
||||
val line: String
|
||||
)
|
||||
|
||||
data class NextEditOutcome(
|
||||
// Fields from TabAutocompleteOptions
|
||||
val disable: Boolean,
|
||||
val maxPromptTokens: Int,
|
||||
val debounceDelay: Int,
|
||||
val maxSuffixPercentage: Int,
|
||||
val prefixPercentage: Int,
|
||||
val transform: Boolean?,
|
||||
val template: String?,
|
||||
val multilineCompletions: String, // "always" | "never" | "auto"
|
||||
val slidingWindowPrefixPercentage: Int,
|
||||
val slidingWindowSize: Int,
|
||||
val useCache: Boolean,
|
||||
val onlyMyCode: Boolean,
|
||||
val useRecentlyEdited: Boolean,
|
||||
val disableInFiles: List<String>?,
|
||||
val useImports: Boolean?,
|
||||
val showWhateverWeHaveAtXMs: Int?,
|
||||
|
||||
// Originally from Autocomplete (commented fields would be nullable if needed)
|
||||
val elapsed: Long,
|
||||
val modelProvider: String,
|
||||
val modelName: String,
|
||||
val completionOptions: Any, // Using Any since TypeScript uses 'any'
|
||||
val completionId: String,
|
||||
val gitRepo: String?,
|
||||
val uniqueId: String,
|
||||
val timestamp: Long,
|
||||
|
||||
// New for Next Edit
|
||||
val fileUri: String,
|
||||
val workspaceDirUri: String,
|
||||
val prompt: String,
|
||||
val userEdits: String,
|
||||
val userExcerpts: String,
|
||||
val originalEditableRange: String,
|
||||
val completion: String,
|
||||
val cursorPosition: Position,
|
||||
val finalCursorPosition: Position,
|
||||
val accepted: Boolean?,
|
||||
val editableRegionStartLine: Int,
|
||||
val editableRegionEndLine: Int,
|
||||
val diffLines: List<DiffLine>
|
||||
)
|
||||
|
||||
enum class DiffLineType {
|
||||
NEW,
|
||||
OLD,
|
||||
SAME
|
||||
}
|
||||
|
||||
data class ProcessedItem(
|
||||
val location: RangeInFile,
|
||||
val outcome: NextEditOutcome
|
||||
)
|
||||
|
|
@ -4,17 +4,23 @@ import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger
|
|||
import com.github.continuedev.continueintellijextension.`continue`.CoreMessengerManager
|
||||
import com.github.continuedev.continueintellijextension.`continue`.DiffManager
|
||||
import com.github.continuedev.continueintellijextension.`continue`.IdeProtocolClient
|
||||
import com.github.continuedev.continueintellijextension.listeners.ActiveHandlerManager
|
||||
import com.github.continuedev.continueintellijextension.listeners.DocumentChangeTracker
|
||||
import com.github.continuedev.continueintellijextension.toolWindow.ContinuePluginToolWindowFactory
|
||||
import com.github.continuedev.continueintellijextension.utils.uuid
|
||||
import com.intellij.openapi.Disposable
|
||||
import com.intellij.openapi.components.Service
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.editor.EditorFactory
|
||||
import com.intellij.openapi.project.DumbAware
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.util.Disposer
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlin.properties.Delegates
|
||||
|
||||
@Service(Service.Level.PROJECT)
|
||||
class ContinuePluginService : Disposable, DumbAware {
|
||||
class ContinuePluginService(private val project: Project) : DumbAware {
|
||||
private val coroutineScope = CoroutineScope(Dispatchers.Main)
|
||||
var listener: (() -> Unit)? = null
|
||||
var ideProtocolClient: IdeProtocolClient? by Delegates.observable(null) { _, _, _ ->
|
||||
|
|
@ -27,7 +33,31 @@ class ContinuePluginService : Disposable, DumbAware {
|
|||
var windowId: String = uuid()
|
||||
var diffManager: DiffManager? = null
|
||||
|
||||
override fun dispose() {
|
||||
init {
|
||||
// Set up active handler manager and document change tracking
|
||||
setupCursorMovementTracking()
|
||||
}
|
||||
|
||||
private fun setupCursorMovementTracking() {
|
||||
val activeHandlerManager = project.service<ActiveHandlerManager>()
|
||||
val documentChangeTracker = project.service<DocumentChangeTracker>()
|
||||
|
||||
// Register listeners with EditorFactory to handle all editors
|
||||
// Use Disposer to ensure they get cleaned up when the project is disposed
|
||||
val editorFactory = EditorFactory.getInstance()
|
||||
|
||||
editorFactory.eventMulticaster.addSelectionListener(activeHandlerManager, project)
|
||||
editorFactory.eventMulticaster.addCaretListener(activeHandlerManager, project)
|
||||
editorFactory.eventMulticaster.addDocumentListener(documentChangeTracker, project)
|
||||
|
||||
// Also register disposal cleanup
|
||||
Disposer.register(project) {
|
||||
activeHandlerManager.dispose()
|
||||
documentChangeTracker.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
fun dispose() {
|
||||
coroutineScope.cancel()
|
||||
coreMessenger?.coroutineScope?.let {
|
||||
it.cancel()
|
||||
|
|
|
|||
|
|
@ -0,0 +1,76 @@
|
|||
package com.github.continuedev.continueintellijextension.utils
|
||||
|
||||
import com.intellij.openapi.actionSystem.ActionManager
|
||||
import com.intellij.openapi.actionSystem.AnActionEvent
|
||||
import com.intellij.openapi.actionSystem.CommonDataKeys
|
||||
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
|
||||
import com.intellij.openapi.application.EDT
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.project.Project
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
object InlineCompletionUtils {
|
||||
/**
|
||||
* Triggers inline completion for the given editor.
|
||||
* This is equivalent to pressing Shift+Alt+Backslash or calling the "Generate Inline Completion" action.
|
||||
* Always executes on the EDT to avoid threading issues.
|
||||
*
|
||||
* @param editor The editor to trigger completion for
|
||||
* @param project The project context (optional, will be inferred from editor if null)
|
||||
*/
|
||||
suspend fun triggerInlineCompletion(
|
||||
editor: Editor,
|
||||
project: Project? = null
|
||||
): Boolean = withContext(Dispatchers.EDT) {
|
||||
performTrigger(editor, project)
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal method that performs the actual trigger logic.
|
||||
* Must be called on the EDT.
|
||||
*/
|
||||
private fun performTrigger(editor: Editor, project: Project?): Boolean {
|
||||
return try {
|
||||
val actionManager = ActionManager.getInstance()
|
||||
val action = actionManager.getAction("CallInlineCompletionAction")
|
||||
|
||||
if (action != null) {
|
||||
println("Found CallInlineCompletionAction, checking if enabled...")
|
||||
|
||||
val effectiveProject = project ?: editor.project
|
||||
val dataContext = SimpleDataContext.builder()
|
||||
.add(CommonDataKeys.EDITOR, editor)
|
||||
.add(CommonDataKeys.PROJECT, effectiveProject)
|
||||
.build()
|
||||
|
||||
val event = AnActionEvent.createFromDataContext(
|
||||
"ProgrammaticInlineCompletion",
|
||||
null,
|
||||
dataContext
|
||||
)
|
||||
|
||||
// Check if action is enabled before performing it
|
||||
action.update(event)
|
||||
val isEnabled = event.presentation.isEnabled
|
||||
println("Action enabled: $isEnabled")
|
||||
|
||||
if (isEnabled) {
|
||||
action.actionPerformed(event)
|
||||
println("Action performed successfully")
|
||||
true
|
||||
} else {
|
||||
println("Action is disabled, not performing")
|
||||
false
|
||||
}
|
||||
} else {
|
||||
println("CallInlineCompletionAction not found!")
|
||||
false
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
println("Exception in performTrigger: ${e.message}")
|
||||
e.printStackTrace()
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -118,71 +118,4 @@ fun getOsAndArchTarget(): String {
|
|||
}
|
||||
|
||||
return "$osStr-$arch"
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the diff is indeed a FIM (Fill-In-Middle).
|
||||
* @param oldEditRange Original string content.
|
||||
* @param newEditRange New string content.
|
||||
* @param cursorPosition The position of the cursor in the old string.
|
||||
* @return A Pair where the first value is a boolean indicating if the change is purely additive (FIM)
|
||||
* and the second value is the FIM text content or null if not a FIM.
|
||||
*/
|
||||
fun checkFim(
|
||||
oldEditRange: String,
|
||||
newEditRange: String,
|
||||
cursorPosition: Pair<Int, Int> // line, character
|
||||
): FimResult {
|
||||
// Find the common prefix
|
||||
var prefixLength = 0
|
||||
while (prefixLength < oldEditRange.length &&
|
||||
prefixLength < newEditRange.length &&
|
||||
oldEditRange[prefixLength] == newEditRange[prefixLength]) {
|
||||
prefixLength++
|
||||
}
|
||||
|
||||
// Find the common suffix
|
||||
var oldSuffixPos = oldEditRange.length - 1
|
||||
var newSuffixPos = newEditRange.length - 1
|
||||
|
||||
while (oldSuffixPos >= prefixLength &&
|
||||
newSuffixPos >= prefixLength &&
|
||||
oldEditRange[oldSuffixPos] == newEditRange[newSuffixPos]) {
|
||||
oldSuffixPos--
|
||||
newSuffixPos--
|
||||
}
|
||||
|
||||
// The old text is purely preserved if:
|
||||
// 1. The prefix ends before or at the cursor.
|
||||
// 2. The suffix starts after or at the cursor.
|
||||
// 3. There's no gap between prefix and suffix in the old text.
|
||||
|
||||
val suffixStartInOld = oldSuffixPos + 1
|
||||
val suffixStartInNew = newSuffixPos + 1
|
||||
|
||||
// Convert cursor position to an offset in the string.
|
||||
// For simplicity, we need to calculate the cursor's position in the string.
|
||||
// This requires knowledge of line endings in the oldEditRange.
|
||||
val lines = oldEditRange.substring(0, prefixLength).split("\n")
|
||||
val cursorOffset = if (lines.size > 1) {
|
||||
lines.dropLast(1).sumOf { it.length + 1 } + cursorPosition.second
|
||||
} else {
|
||||
cursorPosition.second
|
||||
}
|
||||
|
||||
// Check if the cursor is positioned between the prefix and suffix.
|
||||
val cursorBetweenPrefixAndSuffix =
|
||||
prefixLength <= cursorOffset && cursorOffset <= suffixStartInOld
|
||||
|
||||
// Check if the old text is completely preserved (no deletion).
|
||||
val noTextDeleted = suffixStartInOld - prefixLength <= 0
|
||||
|
||||
val isFim = cursorBetweenPrefixAndSuffix && noTextDeleted
|
||||
|
||||
return if (isFim) {
|
||||
// Extract the content between prefix and suffix in the new string.
|
||||
FimResult.FimEdit(newEditRange.substring(prefixLength, suffixStartInNew))
|
||||
} else {
|
||||
FimResult.NotFimEdit
|
||||
}
|
||||
}
|
||||
|
|
@ -25,8 +25,18 @@
|
|||
|
||||
<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"/>
|
||||
<projectService
|
||||
serviceInterface="com.github.continuedev.continueintellijextension.nextEdit.NextEditService"
|
||||
serviceImplementation="com.github.continuedev.continueintellijextension.nextEdit.ContinueNextEditService"/>
|
||||
|
||||
<projectService
|
||||
serviceImplementation="com.github.continuedev.continueintellijextension.nextEdit.NextEditWindowManager"/>
|
||||
|
||||
<projectService
|
||||
serviceImplementation="com.github.continuedev.continueintellijextension.nextEdit.NextEditJumpManager"/>
|
||||
|
||||
<inline.completion.provider id="Continue" implementation="com.github.continuedev.continueintellijextension.autocomplete.ContinueInlineCompletionProvider"/>
|
||||
|
||||
<notificationGroup id="Continue"
|
||||
displayType="BALLOON"/>
|
||||
<actionPromoter order="last"
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package com.github.continuedev.continueintellijextension.unit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.FimResult
|
||||
import com.github.continuedev.continueintellijextension.utils.checkFim
|
||||
import com.github.continuedev.continueintellijextension.nextEdit.NextEditUtils.checkFim
|
||||
import junit.framework.TestCase
|
||||
|
||||
class CheckFimTest : TestCase() {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue