diff --git a/.continue/mcpServers/continue-docs-mcp.yaml b/.continue/mcpServers/continue-docs-mcp.yaml deleted file mode 100644 index a295b5546..000000000 --- a/.continue/mcpServers/continue-docs-mcp.yaml +++ /dev/null @@ -1,11 +0,0 @@ -name: Continue Documentation MCP -version: 0.0.1 -schema: v1 -mcpServers: - - name: Continue Docs Search - type: stdio - command: npx - args: - - mint-mcp - - add - - continue-docs diff --git a/core/control-plane/mdm/mdm.ts b/core/control-plane/mdm/mdm.ts index c782105ed..6971a9882 100644 --- a/core/control-plane/mdm/mdm.ts +++ b/core/control-plane/mdm/mdm.ts @@ -132,7 +132,10 @@ function readMdmKeysWindows(): MdmKeys | undefined { try { // Use REG QUERY command to read registry values const licenseKeyCmd = `reg query "${regPath}" /v licenseKey`; - const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" }); + const licenseKeyOutput = execSync(licenseKeyCmd, { + encoding: "utf8", + stdio: ["pipe", "pipe", "pipe"], + }); // Extract values from command output const licenseKey = extractRegValue(licenseKeyOutput); if (licenseKey) { @@ -145,7 +148,10 @@ function readMdmKeysWindows(): MdmKeys | undefined { // Try HKEY_CURRENT_USER if not found in HKEY_LOCAL_MACHINE try { const licenseKeyCmd = `reg query "${userRegPath}" /v licenseKey`; - const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" }); + const licenseKeyOutput = execSync(licenseKeyCmd, { + encoding: "utf8", + stdio: ["pipe", "pipe", "pipe"], + }); // Extract values from command output const licenseKey = extractRegValue(licenseKeyOutput); if (licenseKey) { diff --git a/core/core.ts b/core/core.ts index 57ce98d97..c1dff0e48 100644 --- a/core/core.ts +++ b/core/core.ts @@ -73,6 +73,7 @@ import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import { OnboardingModes } from "./protocol/core"; import type { IMessenger, Message } from "./protocol/messenger"; import { getUriPathBasename } from "./util/uri"; +import { NextEditProvider } from "./nextEdit/NextEditProvider"; const hasRulesFiles = (uris: string[]): boolean => { for (const uri of uris) { @@ -88,6 +89,7 @@ export class Core { configHandler: ConfigHandler; codeBaseIndexer: CodebaseIndexer; completionProvider: CompletionProvider; + nextEditProvider: NextEditProvider; private docsService: DocsService; private globalContext = new GlobalContext(); llmLogger = new LLMLogger(); @@ -233,6 +235,15 @@ export class Core { (..._) => Promise.resolve([]), ); + this.nextEditProvider = NextEditProvider.initialize( + this.configHandler, + ide, + getLlm, + (e) => {}, + (..._) => Promise.resolve([]), + "fineTuned", + ); + this.registerMessageHandlers(ideSettingsPromise); } @@ -542,6 +553,21 @@ export class Core { this.completionProvider.cancel(); }); + // Next Edit + on("nextEdit/predict", async (msg) => { + const outcome = await this.nextEditProvider.provideInlineCompletionItems( + msg.data, + undefined, + ); + return outcome ? [outcome.completion, outcome.originalEditableRange] : []; + }); + on("nextEdit/accept", async (msg) => { + this.nextEditProvider.accept(msg.data.completionId); + }); + on("nextEdit/reject", async (msg) => { + this.nextEditProvider.reject(msg.data.completionId); + }); + on("streamDiffLines", async (msg) => { const { config } = await this.configHandler.loadConfig(); if (!config) { diff --git a/core/indexing/docs/DocsCache.ts b/core/indexing/docs/DocsCache.ts index f250b797c..caa30139b 100644 --- a/core/indexing/docs/DocsCache.ts +++ b/core/indexing/docs/DocsCache.ts @@ -7,6 +7,15 @@ export interface SiteIndexingResults { title: string; } +/** + * Strip off the trailing forward slash from the given URL + * @param url The URL of the document + * @returns A sanitized URL without trailing forward slash + */ +const stripTrailingSlash = (url: string): string => { + return url.replace(/\/+$/, ""); +}; + export class DocsCache { static readonly AWS_REGION: string = "us-west-1"; static readonly BUCKET_NAME: string = "continue-preindexed-docs"; @@ -33,7 +42,8 @@ export class DocsCache { url: string, ): string { const normalizedEmbeddingId = DocsCache.normalizeEmbeddingId(embeddingId); - const normalizedUrl = encodeURIComponent(url.replace(/\//g, "_")); + const sanitizedUrl = stripTrailingSlash(url); + const normalizedUrl = encodeURIComponent(sanitizedUrl.replace(/\//g, "_")); return normalizedEmbeddingId + "/" + normalizedUrl; } diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index fba86df33..0f0d6ff48 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -158,19 +158,19 @@ export class NextEditProvider { this.loggingService.cancel(); } - // public accept(completionId: string) { - // const outcome = this.loggingService.accept(completionId); - // if (!outcome) { - // return; - // } - // } + public accept(completionId: string) { + const outcome = this.loggingService.accept(completionId); + if (!outcome) { + return; + } + } - // public reject(completionId: string) { - // const outcome = this.loggingService.reject(completionId); - // if (!outcome) { - // return; - // } - // } + public reject(completionId: string) { + const outcome = this.loggingService.reject(completionId); + if (!outcome) { + return; + } + } public markDisplayed(completionId: string, outcome: NextEditOutcome) { this.loggingService.markDisplayed(completionId, outcome); @@ -237,7 +237,6 @@ export class NextEditProvider { // TODO: Toggle between the default endpoint and the finetuned endpoint. const prompts: Prompt[] = []; - if (this.endpointType === "default") { prompts.push(renderDefaultSystemPrompt()); prompts.push(renderDefaultUserPrompt(snippetPayload, helper)); @@ -272,17 +271,30 @@ export class NextEditProvider { cursorPosition: helper.pos, ...helper.options, }; + + // When using the JetBrains extension, mark as displayed. + // This helps us not need to make additional network calls just to mark as displayed. + const ideType = (await this.ide.getIdeInfo()).ideType; + if (ideType === "jetbrains") { + this.markDisplayed(input.completionId, outcomeNext); + } + return outcomeNext; } else { return undefined; } } else { const msg: ChatMessage = await llm.chat(prompts, token); + if (typeof msg.content === "string") { - // TODO: There are cases where msg.conetnt.split("<|start|>")[1] is undefined - const nextCompletion = replaceEscapedCharacters( - msg.content.split("<|editable_region_start|>\n")[1], - ).replace(/\n$/, ""); + // NOTE: There are cases where msg.conetnt.split("<|start|>")[1] is undefined + const nextCompletion = msg.content.split( + "<|editable_region_start|>\n", + )[1] + ? replaceEscapedCharacters( + msg.content.split("<|editable_region_start|>\n")[1], + ).replace(/\n$/, "") + : ""; const currCursorPos = helper.pos; const editableRegionStartLine = Math.max( @@ -319,6 +331,14 @@ export class NextEditProvider { cursorPosition: helper.pos, ...helper.options, }; + + // When using the JetBrains extension, mark as displayed. + // This helps us not need to make additional network calls just to mark as displayed. + const ideType = (await this.ide.getIdeInfo()).ideType; + if (ideType === "jetbrains") { + this.markDisplayed(input.completionId, outcomeNext); + } + return outcomeNext; } else { return undefined; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 2bbc75620..03f4d6b2a 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -147,6 +147,9 @@ export type ToCoreFromIdeOrWebviewProtocol = { "context/indexDocs": [{ reIndex: boolean }, void]; "autocomplete/cancel": [undefined, void]; "autocomplete/accept": [{ completionId: string }, void]; + "nextEdit/predict": [AutocompleteInput, string[]]; + "nextEdit/reject": [{ completionId: string }, void]; + "nextEdit/accept": [{ completionId: string }, void]; "llm/complete": [ { prompt: string; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index f4ad6c04c..714e46cba 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -37,6 +37,9 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "autocomplete/complete", "autocomplete/cancel", "autocomplete/accept", + "nextEdit/predict", + "nextEdit/reject", + "nextEdit/accept", "tts/kill", "llm/complete", "llm/streamChat", diff --git a/docs/customize/deep-dives/mcp.mdx b/docs/customize/deep-dives/mcp.mdx index c71d8c021..dcbff566e 100644 --- a/docs/customize/deep-dives/mcp.mdx +++ b/docs/customize/deep-dives/mcp.mdx @@ -57,41 +57,7 @@ The result will be a generated file called `hn.txt` in the current working direc You can set up an MCP server to search the Continue documentation directly from your agent. This is particularly useful for getting help with Continue configuration and features. -1. Create a folder called `.continue/mcpServers` at the top level of your workspace -2. Add a file called `continue-docs-mcp.yaml` to this folder -3. Write the following contents and save: - -```yaml title=".continue/mcpServers/continue-docs-mcp.yaml" -name: Continue Documentation MCP -version: 0.0.1 -schema: v1 -mcpServers: - - name: Continue Docs Search - type: stdio - command: npx - args: - - mint-mcp - - add - - continue-docs -``` - -Now you can search the Continue documentation by asking questions like: - -``` -Search for model setup instructions in the Continue docs -``` - -``` -Find documentation about context providers -``` - -``` -How do I configure autocomplete in Continue? -``` - -The MCP server will search the Continue documentation and provide relevant information to help with your questions. - -For detailed setup instructions and troubleshooting, see the [Continue MCP Reference](/reference/continue-mcp). +For complete setup instructions, troubleshooting, and usage examples, see the [Continue MCP Reference](/reference/continue-mcp). ## Using MCP Servers diff --git a/docs/docs.json b/docs/docs.json index 1cea55860..86657b4b8 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -258,7 +258,8 @@ "pages": [ "reference", "reference/json-reference", - "reference/yaml-migration" + "reference/yaml-migration", + "reference/continue-mcp" ] } ] diff --git a/docs/images/mintlify-cli-selection-tree.png b/docs/images/mintlify-cli-selection-tree.png new file mode 100644 index 000000000..0c81517e1 Binary files /dev/null and b/docs/images/mintlify-cli-selection-tree.png differ diff --git a/docs/reference/continue-mcp.mdx b/docs/reference/continue-mcp.mdx index b3cc971c4..6045d0ff1 100644 --- a/docs/reference/continue-mcp.mdx +++ b/docs/reference/continue-mcp.mdx @@ -4,45 +4,52 @@ description: Set up an MCP server to search Continue documentation keywords: [mcp, documentation, search, mintlify, reference] --- -# Continue Documentation MCP Server - -The Continue Documentation MCP Server allows you to search and retrieve information from the Continue documentation directly within your agent conversations. This is powered by Mintlify's MCP server generation. +The continue-docs MCP Server allows you to search and retrieve information from the Continue documentation directly within your agent conversations. This is powered by Mintlify's MCP server generation. ## Installation ### Step 1: Install the MCP Server -Run the following command to install the Continue documentation MCP server: +Run the following command to install the continue-docs MCP server: ```bash -npx mint-mcp add continue-docs +npx mint-mcp add docs.continue.dev ``` -This will: +When prompted, select "All" from the selection menu: + +![mintlify cli selection tree](/images/mintlify-cli-selection-tree.png) + +This command will: - Download and install the MCP server locally - Set up the search tool for Continue documentation - Create the necessary configuration files + +Take note of the installation path displayed after running the command above. You'll need to replace in the configuration below with your actual installation path. + +It will look like this: `/path/to/user/.mcp/docs.continue.dev/src/index.js` + + + ### Step 2: Configure Continue 1. Create a folder called `.continue/mcpServers` at the top level of your workspace 2. Add a file called `continue-docs-mcp.yaml` to this folder 3. Write the following contents and save: +````yaml title=".continue/mcpServers/continue-docs-mcp.yaml" ```yaml title=".continue/mcpServers/continue-docs-mcp.yaml" name: Continue Documentation MCP version: 0.0.1 schema: v1 mcpServers: - name: Continue Docs Search - type: stdio - command: npx + command: node args: - - mint-mcp - - add - - continue-docs -``` + - "/path/to/user/.mcp/docs.continue.dev/src/index.js" +```` ### Step 3: Enable Agent Mode diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt index 43ae74881..747fefd03 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt @@ -1,6 +1,7 @@ package com.github.continuedev.continueintellijextension.actions import com.github.continuedev.continueintellijextension.autocomplete.AcceptAutocompleteAction +import com.github.continuedev.continueintellijextension.nextEdit.AcceptNextEditAction import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.intellij.openapi.actionSystem.ActionPromoter import com.intellij.openapi.actionSystem.AnAction @@ -19,6 +20,13 @@ class ContinueActionPromote : ActionPromoter { } } + if (actions.any { it is AcceptNextEditAction }) { + val settings = service() + if (settings.continueState.showIDECompletionSideBySide) { + return actions.filterIsInstance() + } + } + val rejectDiffActions = actions.filterIsInstance() if (rejectDiffActions.isNotEmpty()) { return rejectDiffActions diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteEditorListener.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteEditorListener.kt index 19b0dfa3a..9fca20413 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteEditorListener.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteEditorListener.kt @@ -1,5 +1,8 @@ package com.github.continuedev.continueintellijextension.autocomplete +import com.github.continuedev.continueintellijextension.nextEdit.NextEditService +import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.github.continuedev.continueintellijextension.utils.castNestedOrNull import com.intellij.openapi.application.invokeLater import com.intellij.openapi.components.service import com.intellij.openapi.editor.Editor @@ -37,6 +40,16 @@ class AutocompleteCaretListener : CaretListener { class AutocompleteDocumentListener(private val editorManager: FileEditorManager, private val editor: Editor) : DocumentListener { override fun documentChanged(event: DocumentEvent) { + // Ignore empty changes or changes where content didn't actually change. + if (event.newFragment.isEmpty() && event.oldFragment.isEmpty()) { + return + } + + // Make sure this is an actual text modification event. + if (!event.isWholeTextReplaced && event.offset == 0 && event.oldLength == 0 && event.newLength == 0) { + return + } + if (editor != editorManager.selectedTextEditor) { return } @@ -46,12 +59,55 @@ class AutocompleteDocumentListener(private val editorManager: FileEditorManager, return } - // Invoke later is important, otherwise the completion will be triggered before the document is updated - // causing the old caret offset to be used - // TODO: concurrency - invokeLater { - service.triggerCompletion(editor) + val nextEditService = editor.project?.service() ?: return + + // Check if we're in a test environment based on some property or condition + val isAutocompleteTestEnvironment = System.getProperty("continue.autocomplete.test.environment") == "true" + val isNextEditTestEnvironment = System.getProperty("continue.nextEdit.test.environment") == "true" + + if (isAutocompleteTestEnvironment) { + invokeLater { + service.triggerCompletion(editor) + } + return + } else if (isNextEditTestEnvironment) { + invokeLater { + nextEditService.triggerNextEdit(editor) + } + return } + + // Check settings to see if next edit is enabled, and then trigger either autocomplete or next exit. + val continuePluginService = editor.project?.service() + if (continuePluginService == null) { + return + } + + continuePluginService.coreMessenger?.request( + "config/getSerializedProfileInfo", + null, + null, + ({ response -> + val optInNextEditFeature = response.castNestedOrNull( + "content", + "result", + "config", + "experimental", + "optInNextEditFeature" + ) ?: false + + invokeLater { + if (optInNextEditFeature) { + nextEditService.triggerNextEdit(editor) + } else { + // Invoke later is important, otherwise the completion will be triggered before the document is updated + // causing the old caret offset to be used + // TODO: concurrency + service.triggerCompletion(editor) + } + } + }) + ) } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index ae2ae6165..d9eb5f62d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -103,6 +103,9 @@ class MessageTypes { "autocomplete/complete", "autocomplete/cancel", "autocomplete/accept", + "nextEdit/predict", + "nextEdit/reject", + "nextEdit/accept", "tts/kill", "llm/complete", "llm/streamChat", @@ -135,4 +138,4 @@ class MessageTypes { "process/isBackgrounded", ) } -} \ No newline at end of file +} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/AcceptNextEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/AcceptNextEditAction.kt new file mode 100644 index 000000000..88d43bdb8 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/AcceptNextEditAction.kt @@ -0,0 +1,25 @@ +package com.github.continuedev.continueintellijextension.nextEdit + +import com.intellij.openapi.actionSystem.DataContext +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.components.service +import com.intellij.openapi.editor.Caret +import com.intellij.openapi.editor.Editor +import com.intellij.openapi.editor.actionSystem.EditorAction +import com.intellij.openapi.editor.actionSystem.EditorActionHandler + +class AcceptNextEditAction : EditorAction(object : EditorActionHandler() { + override fun doExecute(editor: Editor, caret: Caret?, dataContext: DataContext?) { + ApplicationManager.getApplication().runWriteAction { + editor.project?.service()?.accept() + } + } + + override fun isEnabledForCaret(editor: Editor, caret: Caret, dataContext: DataContext?): Boolean { + val nextEditService = editor.project?.service(); + val enabled = editor == nextEditService?.pendingCompletion?.editor +// && caret.offset == autocompleteService.pendingCompletion?.offset + && nextEditService.pendingCompletion?.text != null + return enabled + } +}) \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt new file mode 100644 index 000000000..f9279b9b9 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt @@ -0,0 +1,321 @@ +package com.github.continuedev.continueintellijextension.nextEdit + +import com.github.continuedev.continueintellijextension.FimResult +import com.github.continuedev.continueintellijextension.autocomplete.AutocompleteLookupListener +import com.github.continuedev.continueintellijextension.autocomplete.AutocompleteSpinnerWidget +import com.github.continuedev.continueintellijextension.autocomplete.ContinueInlayRenderer +import com.github.continuedev.continueintellijextension.autocomplete.PendingCompletion +import com.github.continuedev.continueintellijextension.autocomplete.addInlayElement +import com.github.continuedev.continueintellijextension.autocomplete.isInjectedText +import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings +import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.github.continuedev.continueintellijextension.utils.checkFim +import com.github.continuedev.continueintellijextension.utils.toUriOrNull +import com.github.continuedev.continueintellijextension.utils.uuid +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.application.WriteAction +import com.intellij.openapi.application.invokeLater +import com.intellij.openapi.application.runReadAction +import com.intellij.openapi.components.Service +import com.intellij.openapi.components.service +import com.intellij.openapi.editor.Editor +import com.intellij.openapi.editor.InlayProperties +import com.intellij.openapi.fileEditor.FileDocumentManager +import com.intellij.openapi.project.Project +import com.intellij.openapi.util.TextRange +import com.intellij.openapi.wm.WindowManager +import com.intellij.psi.PsiDocumentManager + +@Service(Service.Level.PROJECT) +class NextEditService(private val project: Project) { + var pendingCompletion: PendingCompletion? = null + private val autocompleteLookupListener = project.service() + private val widget: AutocompleteSpinnerWidget? by lazy { + WindowManager.getInstance().getStatusBar(project) + ?.getWidget(AutocompleteSpinnerWidget.ID) as? AutocompleteSpinnerWidget + } + + // To avoid triggering another completion on partial acceptance, + // we need to keep track of whether the last change was a partial accept. + var lastChangeWasPartialAccept = false + + fun triggerNextEdit(editor: Editor) { + val settings = service() + if (!settings.continueState.enableTabAutocomplete) { + return + } + + if (pendingCompletion != null) { + clearCompletions(pendingCompletion!!.editor) + } + + // Set pending completion. + val completionId = uuid() + val offset = editor.caretModel.primaryCaret.offset + pendingCompletion = PendingCompletion(editor, offset, completionId, null) + + // Request a completion from the core. + val virtualFile = FileDocumentManager.getInstance().getFile(editor.document) + + val uri = virtualFile?.toUriOrNull() ?: return + + widget?.setLoading(true) + + val line = editor.caretModel.primaryCaret.logicalPosition.line + val column = editor.caretModel.primaryCaret.logicalPosition.column + val input = mapOf( + "completionId" to completionId, + "filepath" to uri, + "pos" to mapOf( + "line" to line, + "character" to column + ), + "clipboardText" to "", + "recentlyEditedRanges" to emptyList(), + "recentlyVisitedRanges" to emptyList(), + ) + + // TODO: Add message support for nextEdit/predict. + project.service().coreMessenger?.request( + "nextEdit/predict", + input, + null, + ({ response -> + if (pendingCompletion == null || pendingCompletion?.completionId == completionId) { + widget?.setLoading(false) + } + + val responseObject = response as Map<*, *> + val predictions = responseObject["content"] as List<*> + + if (predictions.isNotEmpty()) { + val prediction = predictions[0].toString() + val oldEditRange = predictions[1].toString() + // Check if the prediction is purely additive. + val result = checkFim( + oldEditRange, + prediction, + Pair(line, column) + ) + when (result) { + is FimResult.FimEdit -> { + // If so, render ghost text. + val finalTextToInsert = deduplicateCompletion(editor, offset, result.fimText) + if (shouldRenderCompletion(finalTextToInsert, offset, line, editor)) { + renderCompletion(editor, offset, finalTextToInsert) + pendingCompletion = PendingCompletion(editor, offset, completionId, finalTextToInsert) + } + } + is FimResult.NotFimEdit -> { + // Else, render a window. + if (shouldRenderCompletion(prediction, offset, line, editor)) { + val nextEditWindowService = NextEditWindowService.getInstance(project) + nextEditWindowService.showCodePreview(prediction, editor, completionId) + } + } + } + } + }) + ) + } + + private fun shouldRenderCompletion(completion: String, offset: Int, line: Int, editor: Editor): Boolean { + if (completion.isEmpty() || runReadAction { offset != editor.caretModel.offset }) { + return false + } + + if (completion.lines().size == 1) { + return true + } + + val endOffset = editor.document.getLineEndOffset(line) + + // Do not render if completion is multi-line and caret is in middle of line + return offset <= endOffset && editor.document.getText(TextRange(offset, endOffset)).isBlank() + } + + private fun deduplicateCompletion(editor: Editor, offset: Int, completion: String): String { + // Check if completion matches the first 10 characters after the cursor + return ApplicationManager.getApplication().runReadAction { + val document = editor.document + val caretOffset = editor.caretModel.offset + + // Don't care about it if it's at the end of the document + if (caretOffset == document.textLength) return@runReadAction completion + + val N = 10 + var textAfterCursor = if (caretOffset + N <= document.textLength) { + document.getText(TextRange(caretOffset, caretOffset + N)) + } else { + document.getText(TextRange(caretOffset, document.textLength)) + } + + // Avoid truncating the completion text when the text after the cursor is blank + if (textAfterCursor.isBlank()) return@runReadAction completion + + // Determine the index of a newline character within the text following the cursor. + val newlineIndex = textAfterCursor.indexOf("\r\n").takeIf { it >= 0 } ?: textAfterCursor.indexOf('\n') + // If a newline character is found and the current line is not empty, truncate the text at that point. + if (newlineIndex > 0) { + textAfterCursor = textAfterCursor.substring(0, newlineIndex) + } + + val indexOfTextAfterCursorInCompletion = completion.indexOf(textAfterCursor) + if (indexOfTextAfterCursorInCompletion > 0) { + return@runReadAction completion.slice(0..indexOfTextAfterCursorInCompletion - 1) + } else if (indexOfTextAfterCursorInCompletion == 0) { + return@runReadAction "" + } + + return@runReadAction completion + } + } + + private fun renderCompletion(editor: Editor, offset: Int, completion: String) { + if (completion.isEmpty()) { + return + } + if (isInjectedFile(editor)) return + // Skip rendering completions if the code completion dropdown is already visible and the IDE completion side-by-side setting is disabled + if (shouldSkipRender()) { + return + } + + ApplicationManager.getApplication().invokeLater { + WriteAction.run { + // Clear existing completions + hideCompletions(editor) + + val properties = InlayProperties() + properties.relatesToPrecedingText(true) + properties.disableSoftWrapping(true) + + val lines = completion.lines() + pendingCompletion = pendingCompletion?.copy(text = lines.joinToString("\n")) + editor.addInlayElement(lines, offset, properties) + +// val attributes = TextAttributes().apply { +// backgroundColor = JBColor.GREEN +// } +// val key = TextAttributesKey.createTextAttributesKey("CONTINUE_AUTOCOMPLETE") +// key.let { editor.colorsScheme.setAttributes(it, attributes) } +// editor.markupModel.addLineHighlighter(key, editor.caretModel.logicalPosition.line, HighlighterLayer.LAST) + } + } + } + + fun accept() { + val completion = pendingCompletion ?: return + val text = completion.text ?: return + val editor = completion.editor + val offset = completion.offset + editor.document.insertString(offset, text) + + editor.caretModel.moveToOffset(offset + text.length) + + project.service().coreMessenger?.request( + "nextEdit/accept", + hashMapOf("completionId" to completion.completionId), + null, + ({}) + ) + invokeLater { + clearCompletions(editor, completion) + } + } + + private fun shouldSkipRender(): Boolean { + val settings = service() + return !settings.continueState.showIDECompletionSideBySide && !autocompleteLookupListener.isLookupEmpty() + } + + private fun splitKeepingDelimiters(input: String, delimiterPattern: String = "\\s+"): List { + val initialSplit = input.split("(?<=$delimiterPattern)|(?=$delimiterPattern)".toRegex()) + .filter { it.isNotEmpty() } + + val result = mutableListOf() + var currentDelimiter = "" + + for (part in initialSplit) { + if (part.matches(delimiterPattern.toRegex())) { + currentDelimiter += part + } else { + if (currentDelimiter.isNotEmpty()) { + result.add(currentDelimiter) + currentDelimiter = "" + } + result.add(part) + } + } + + if (currentDelimiter.isNotEmpty()) { + result.add(currentDelimiter) + + } + + return result + } + + fun partialAccept() { + val completion = pendingCompletion ?: return + val text = completion.text ?: return + val editor = completion.editor + val offset = completion.offset + + lastChangeWasPartialAccept = true + + // Split the text into words, keeping delimiters + val words = splitKeepingDelimiters(text) + println(words) + val word = words[0] + editor.document.insertString(offset, word) + editor.caretModel.moveToOffset(offset + word.length) + + // Remove the completion and re-display it + hideCompletions(editor) + completion.text = text.substring(word.length) + completion.offset += word.length + renderCompletion(editor, completion.offset, completion.text!!) + } + + private fun rejectCompletion(completion: PendingCompletion) { + // Send rejection message to core + widget?.setLoading(false) + project.service().coreMessenger?.request("nextEdit/reject", null, null, ({})) + } + + fun clearCompletions(editor: Editor, completion: PendingCompletion? = pendingCompletion) { + if (isInjectedFile(editor)) return + + if (completion != null) { +// cancelCompletion(completion) + if (completion.completionId == pendingCompletion?.completionId) pendingCompletion = null + } + disposeInlayRenderer(editor) + } + + private fun isInjectedFile(editor: Editor): Boolean { + return runReadAction { + PsiDocumentManager.getInstance(project).getPsiFile(editor.document)?.isInjectedText() ?: false + } + } + + fun hideCompletions(editor: Editor) { + if (isInjectedFile(editor)) return + + disposeInlayRenderer(editor) + } + + private fun disposeInlayRenderer(editor: Editor) { + editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength).forEach { + if (it.renderer is ContinueInlayRenderer) { + it.dispose() + } + } + editor.inlayModel.getBlockElementsInRange(0, editor.document.textLength).forEach { + if (it.renderer is ContinueInlayRenderer) { + it.dispose() + } + } + } +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowService.kt new file mode 100644 index 000000000..846db780e --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowService.kt @@ -0,0 +1,304 @@ +package com.github.continuedev.continueintellijextension.nextEdit + +import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.intellij.openapi.actionSystem.AnAction +import com.intellij.openapi.actionSystem.AnActionEvent +import com.intellij.openapi.actionSystem.CustomShortcutSet +import com.intellij.openapi.command.WriteCommandAction +import com.intellij.openapi.components.Service +import com.intellij.openapi.components.service +import com.intellij.openapi.editor.Document +import com.intellij.openapi.editor.Editor +import com.intellij.openapi.editor.EditorSettings +import com.intellij.openapi.editor.colors.EditorColorsManager +import com.intellij.openapi.editor.ex.EditorEx +import com.intellij.openapi.editor.ex.EditorSettingsExternalizable +import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory +import com.intellij.openapi.fileEditor.FileDocumentManager +import com.intellij.openapi.fileTypes.FileTypeManager +import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory +import com.intellij.openapi.project.Project +import com.intellij.openapi.ui.popup.JBPopupFactory +import com.intellij.openapi.ui.popup.JBPopupListener +import com.intellij.openapi.ui.popup.LightweightWindowEvent +import com.intellij.psi.PsiDocumentManager +import com.intellij.ui.EditorTextField +import com.intellij.ui.components.JBScrollPane +import java.awt.BorderLayout +import java.awt.Color +import java.awt.Dimension +import java.awt.FlowLayout +import java.awt.Point +import java.awt.event.ActionEvent +import java.awt.event.KeyAdapter +import java.awt.event.KeyEvent +import javax.swing.AbstractAction +import javax.swing.JButton +import javax.swing.JComponent +import javax.swing.JPanel +import javax.swing.JScrollPane +import javax.swing.KeyStroke + +@Service(Service.Level.PROJECT) +class NextEditWindowService(private val project: Project) { + /** + * Creates a Swing component that displays syntax-highlighted code. + * + * @param code The code to display + * @param language The language/file extension of the code (e.g. "java", "kotlin", "py") + * @param isEditable Whether the code should be editable (default: false) + * @return A JComponent that can be added to the UI + */ + fun createCodeViewer(code: String, language: String, document: Document, isEditable: Boolean = false): JComponent { + // Get file type based on extension. + // NOTE: This is actually IDE and tier-dependent. For example, TypeScript won't work on IntelliJ CE. + val fileType = FileTypeManager.getInstance().getFileTypeByExtension(language) + + // Create an EditorTextField with the specified code and file type. + val editorTextField = object : EditorTextField(code, project, fileType) { + override fun createEditor(): EditorEx { + val editor = super.createEditor() + + // Configure editor settings. + val settings: EditorSettings = editor.settings + settings.isLineNumbersShown = true + settings.isLineMarkerAreaShown = true + settings.isIndentGuidesShown = true + settings.isVirtualSpace = false + settings.isRightMarginShown = false + settings.additionalLinesCount = 0 + settings.isShowingSpecialChars = false + settings.isCaretRowShown = true + + // Set read-only if not editable. + editor.isViewer = !isEditable + + // Syntax highlighter. + // Get current editor color scheme. + val currentScheme = EditorColorsManager.getInstance().globalScheme + + // Apply syntax highlighting with current theme. + val virtualFile = FileDocumentManager.getInstance().getFile(document) + var syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(fileType, project, virtualFile) + + // If we couldn't get a syntax highlighter from the file, try to get one just from the file type. + if (syntaxHighlighter == null) { + syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(fileType, project, null) + } + + // If we have a highlighter, apply it. + if (syntaxHighlighter != null) { + editor.highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter( + syntaxHighlighter, + currentScheme + ) + } else { + // Fallback to plain text highlighting if all attempts fail. + val plainTextFileType = FileTypeManager.getInstance().getFileTypeByExtension("txt") + editor.highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter( + project, + plainTextFileType + ) + } + + // Apply the theme's background color. + editor.backgroundColor = currentScheme.defaultBackground + + return editor + } + + // Override to ensure multi-line support. + override fun getPreferredSize(): Dimension { + val lineCount = code.lines().size + // Adjust height based on line count (with some minimum). + val preferredSize = super.getPreferredSize() + val lineHeight = preferredSize.height / (if (lineCount > 0) lineCount else 1) + val newHeight = lineHeight * (if (lineCount > 0) lineCount else 1) + 10 // Add padding + return Dimension(preferredSize.width, newHeight) + } + } + + // Enable multi-line mode. + editorTextField.setOneLineMode(false) + + // Wrap in a scroll pane for larger code blocks. + val panel = JPanel(BorderLayout()) + panel.add(JBScrollPane(editorTextField), BorderLayout.CENTER) + + return panel + } + + /** + * Shows a popup dialog with the code preview. + */ + fun showCodePreview(code: String, parentEditor: Editor, completionId: String) { + // Use invokeAndWait or invokeLater to ensure we're on the EDT. + com.intellij.openapi.application.ApplicationManager.getApplication().invokeLater { + val codeViewer = createCodeViewer(code, getFileLanguage(parentEditor.document), parentEditor.document) + + // Create a button panel. + val buttonPanel = JPanel(FlowLayout(FlowLayout.RIGHT)) + val acceptButton = JButton("Accept (Tab)") + val dismissButton = JButton("Dismiss (Esc)") + buttonPanel.add(acceptButton) + buttonPanel.add(dismissButton) + + // Create a panel to hold the code viewer and buttons. + val panel = JPanel(BorderLayout()) + panel.add(codeViewer, BorderLayout.CENTER) + panel.add(buttonPanel, BorderLayout.SOUTH) + + + // Create the popup. + val popup = JBPopupFactory.getInstance() + .createComponentPopupBuilder(panel, codeViewer) + .setMovable(true) + .setResizable(true) + .setRequestFocus(true) + .setCancelOnClickOutside(true) + .setCancelOnOtherWindowOpen(true) + .setFocusable(true) + .addListener(object : JBPopupListener { + override fun onClosed(event: LightweightWindowEvent) { + if (!event.isOk) { + // This only triggers when dismissed, not when accepted. + println("Dismissing code preview popup") + project.service().coreMessenger?.request( + "nextEdit/reject", + hashMapOf("completionId" to completionId), + null, ({}) + ) + } + } + }) + .createPopup() + + // Helper function to accept the code and apply it to the editor. + fun acceptCode() { + val document = parentEditor.document + val caretModel = parentEditor.caretModel + val caretOffset = caretModel.offset + val caretPosition = document.getLineNumber(caretOffset) + + // Calculate start and end lines. + val totalLines = document.lineCount + val startLine = maxOf(0, caretPosition - 5) + val endLine = minOf(totalLines - 1, caretPosition + 5) + + // Get start and end offsets. + val startOffset = document.getLineStartOffset(startLine) + val endOffset = document.getLineEndOffset(endLine) + + // Write command to replace the text. + WriteCommandAction.runWriteCommandAction(project) { + document.replaceString(startOffset, endOffset, code) + } + + project.service().coreMessenger?.request( + "nextEdit/accept", + hashMapOf("completionId" to completionId), + null, ({}) + ) + } + + // Use ActionManager to handle Tab key globally during popup display. + val acceptAction = object : AnAction() { + override fun actionPerformed(e: AnActionEvent) { + acceptCode() + popup.closeOk(null) + } + } + + // Create a custom shortcut set for the Tab key. + val customShortcutSet = CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0)) + + + // Register action with shortcut. + acceptAction.registerCustomShortcutSet(customShortcutSet, panel) + + // Add button actions. + acceptButton.addActionListener { + acceptCode() + popup.closeOk(null) + } + + dismissButton.addActionListener { + popup.cancel() + } + + // Get the exact position of the cursor. + val visualPosition = parentEditor.caretModel.visualPosition + val cursorPoint = parentEditor.visualPositionToXY(visualPosition) + + // Convert to screen coordinates. + val editorComponent = parentEditor.component + val locationOnScreen = editorComponent.locationOnScreen + val screenPoint = Point( + locationOnScreen.x + cursorPoint.x, + locationOnScreen.y + cursorPoint.y + ) + + // Show the popup at the cursor position. + popup.showInScreenCoordinates(editorComponent, screenPoint) + + // Ensure proper focus for keyboard shortcuts. + codeViewer.requestFocusInWindow() + } + } + + // Move editorConfig to a proper instance property that gets actual editor settings. + private val editorConfig: EditorConfig by lazy { + val settings = EditorSettingsExternalizable.getInstance() + val editorFontSize = EditorColorsManager.getInstance().globalScheme.editorFontSize + val editorFontFamily = EditorColorsManager.getInstance().globalScheme.editorFontName + + EditorConfig( + fontSize = editorFontSize.toDouble(), + fontFamily = editorFontFamily + ) + } + + // Data class to hold editor configuration. + private data class EditorConfig( + val fontSize: Double = 14.0, + val fontFamily: String = "JetBrains Mono" + ) + + /** + * Convenience method to map common programming languages to their file extensions. + */ + fun mapLanguageToExtension(language: String): String { + return when (language.lowercase()) { + "javascript" -> "js" + "typescript" -> "ts" + "python" -> "py" + "java" -> "java" + "kotlin" -> "kt" + "c++" -> "cpp" + "c#" -> "cs" + "go" -> "go" + "rust" -> "rs" + "ruby" -> "rb" + "php" -> "php" + "swift" -> "swift" + "shell", "bash" -> "sh" + "html" -> "html" + "css" -> "css" + "json" -> "json" + "xml" -> "xml" + "yaml", "yml" -> "yaml" + "markdown", "md" -> "md" + // Add more mappings as needed + else -> language + } + } + + private fun getFileLanguage(document: Document): String { + val virtualFile = FileDocumentManager.getInstance().getFile(document) + return virtualFile?.extension?.lowercase() ?: "text" + } + + companion object { + fun getInstance(project: Project): NextEditWindowService = project.service() + } +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt index 492356ed3..4afa1cb45 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt @@ -46,6 +46,7 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { init { System.setProperty("ide.browser.jcef.jsQueryPoolSize", JS_QUERY_POOL_SIZE) System.setProperty("ide.browser.jcef.contextMenu.devTools.enabled", "true") + System.setProperty("ide.browser.jcef.out-of-process.enabled", "false") } val browser: ContinueBrowser by lazy { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index 5ff9e9454..dae734881 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -247,4 +247,9 @@ data class AcceptOrRejectDiffPayload( data class ShowFilePayload( val filepath: String -) \ No newline at end of file +) + +sealed class FimResult { + data class FimEdit(val fimText: String) : FimResult() + object NotFimEdit : FimResult() +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Utils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Utils.kt index 52a4884f0..888b59359 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Utils.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Utils.kt @@ -1,5 +1,6 @@ package com.github.continuedev.continueintellijextension.utils +import com.github.continuedev.continueintellijextension.FimResult import com.intellij.openapi.vfs.VirtualFile import java.net.NetworkInterface import java.util.* @@ -117,4 +118,71 @@ 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 // 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 + } } \ No newline at end of file diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index a0ec2afe7..951338698 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -176,6 +176,13 @@ + + + + + diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt index 694ce526f..a8bdab796 100644 --- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt +++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt @@ -28,11 +28,15 @@ class Autocomplete { @BeforeEach fun waitForIde(remoteRobot: RemoteRobot) { + System.setProperty("continue.autocomplete.test.environment", "true") waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") } } @AfterEach - fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject() + fun closeProject(remoteRobot: RemoteRobot) { + System.clearProperty("continue.autocomplete.test.environment") + CommonSteps(remoteRobot).closeProject() + } @Test @Video diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/CheckFimTest.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/CheckFimTest.kt new file mode 100644 index 000000000..b23bcf7ec --- /dev/null +++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/CheckFimTest.kt @@ -0,0 +1,51 @@ +package com.github.continuedev.continueintellijextension.unit + +import com.github.continuedev.continueintellijextension.FimResult +import com.github.continuedev.continueintellijextension.`continue`.UriUtils +import com.github.continuedev.continueintellijextension.utils.checkFim +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import java.io.File +import kotlin.test.assertEquals + +class CheckFimTest { + @Test + fun testFim() { + val oldEditRange = "hello world" + val newEditRange = "hello this world" + val cursorPosition = Pair(0, 6) + assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.FimEdit("this ")) + } + + @Test + fun testMultilineFim() { + val oldEditRange = "hello {\n world\n}" + val newEditRange = "hello {\n print()\n world\n}" + val cursorPosition = Pair(1, 2) + assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.FimEdit("print()\n ")) + } + + @Test + fun testNotFim() { + val oldEditRange = "hello world" + val newEditRange = "hello this world" + val cursorPosition = Pair(0, 8) + assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.NotFimEdit) + } + + @Test + fun testMultilineNotFim() { + val oldEditRange = "hello {\n world\n}" + val newEditRange = "hello {\n world\n}\nprint()" + val cursorPosition = Pair(1, 2) + assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.NotFimEdit) + } + + @Test + fun testFimEdge() { + val oldEditRange = "" + val newEditRange = "" + val cursorPosition = Pair(0, 0) + assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.FimEdit("")) + } +}