From 98affeaa81590af3862ce4fe6b0837912f84000e Mon Sep 17 00:00:00 2001 From: Nate Sesti <33237525+sestinj@users.noreply.github.com> Date: Tue, 26 Mar 2024 15:55:32 -0700 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A5=20Improved=20Ctrl/Cmd+I=20(#1023)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * โšก๏ธ improved diff streaming algo * ๐ŸŽจ better messaging/formatting for further cmd/ctrl+I instructions * โšก๏ธ more reliably filter out unwanted explanations * ๐Ÿšธ better follow up edits * ๐Ÿ’„ accept/reject diffs block-by-block * โœจ cmd/ctrl+z to reject diff * ๐Ÿšš rename variables * ๐Ÿ’„ allow switching files when inline diff still visible * ๐Ÿšธ don't show quick pick if not ctx providers exist * ๐Ÿšง (sort of) allow switching editors while streaming diff * ๐Ÿ’„ show model being used for cmd/ctrl+I * ๐Ÿ’„ don't add undo stops when generating diff * ๐Ÿ› fix shortcuts for accept/reject diff blocks * โœจ improved GPT edit prompt, taking prefix/suffix into account * โœจ improved prompting for empty selection ctrl/cmd+I * โšก๏ธ immediately refresh codelens * ๐Ÿ› use first model if default undefined * โšก๏ธ refresh codelens after diff cleared * ๐Ÿ’„ update keyboard shortcuts --- core/autocomplete/lineStream.ts | 3 + core/diff/streamDiff.ts | 2 + core/diff/util.ts | 21 ++- core/llm/templates/edit.ts | 42 +++++- core/util/verticalEdit.ts | 48 +++++-- .../continue/Diffs.kt | 2 +- extensions/vscode/package.json | 24 +++- extensions/vscode/src/commands.ts | 79 ++++++----- extensions/vscode/src/diff/horizontal.ts | 2 +- .../src/diff/verticalPerLine/decorations.ts | 5 + .../src/diff/verticalPerLine/handler.ts | 132 +++++++++++++----- .../src/diff/verticalPerLine/manager.ts | 71 ++++++---- .../vscode/src/extension/vscodeExtension.ts | 6 +- extensions/vscode/src/lang-server/codeLens.ts | 50 ++++++- extensions/vscode/src/util/util.ts | 8 ++ .../components/dialogs/KeyboardShortcuts.tsx | 17 ++- 16 files changed, 382 insertions(+), 130 deletions(-) diff --git a/core/autocomplete/lineStream.ts b/core/autocomplete/lineStream.ts index 735eb9995..d3ac0b715 100644 --- a/core/autocomplete/lineStream.ts +++ b/core/autocomplete/lineStream.ts @@ -158,6 +158,9 @@ export async function* filterEnglishLinesAtStart(lines: LineStream) { let i = 0; let wasEnglishFirstLine = false; for await (let line of lines) { + if (i === 0 && line.trim() === "") { + continue; + } if (i === 0) { if (isEnglishFirstLine(line)) { wasEnglishFirstLine = true; diff --git a/core/diff/streamDiff.ts b/core/diff/streamDiff.ts index a86bda9b3..f30e76e07 100644 --- a/core/diff/streamDiff.ts +++ b/core/diff/streamDiff.ts @@ -14,6 +14,8 @@ export async function* streamDiff( newLines: LineStream, ): AsyncGenerator { const mutatedOldLines = [...oldLines]; // be careful + + // If one indentation mistake is made, others are likely. So we are more permissive about matching let seenIndentationMistake = false; let newLineResult = await newLines.next(); diff --git a/core/diff/util.ts b/core/diff/util.ts index 2558a1f62..ade376291 100644 --- a/core/diff/util.ts +++ b/core/diff/util.ts @@ -8,16 +8,23 @@ function linesMatchPerfectly(lineA: string, lineB: string): boolean { return lineA === lineB && lineA !== ""; } -function linesMatch(lineA: string, lineB: string): boolean { +const END_BRACKETS = ["}", "});", "})"]; + +function linesMatch( + lineA: string, + lineB: string, + linesBetween: number = 0, +): boolean { // Require a perfect (without padding) match for these lines // Otherwise they are edit distance 1 from empty lines and other single char lines (e.g. each other) - if (["}", "*"].includes(lineA.trim())) { + if (["}", "*", "});", "})"].includes(lineA.trim())) { return lineA.trim() === lineB.trim(); } const d = distance(lineA, lineB); return ( - (d / Math.max(lineA.length, lineB.length) < 0.5 || + // Should be more unlikely for lines to fuzzy match if they are further away + (d / Math.max(lineA.length, lineB.length) < 0.5 - linesBetween * 0.05 || lineA.trim() === lineB.trim()) && lineA.trim() !== "" ); @@ -37,10 +44,16 @@ export function matchLine( return [0, true, newLine.trim()]; } + const isEndBracket = END_BRACKETS.includes(newLine.trim()); for (let i = 0; i < oldLines.length; i++) { + // Don't match end bracket lines if too far away + if (i > 4 && isEndBracket) { + return [-1, false, newLine]; + } + if (linesMatchPerfectly(newLine, oldLines[i])) { return [i, true, newLine]; - } else if (linesMatch(newLine, oldLines[i])) { + } else if (linesMatch(newLine, oldLines[i], i)) { // This is a way to fix indentation, but only for sufficiently long lines to avoid matching whitespace or short lines if ( newLine.trimStart() === oldLines[i].trimStart() && diff --git a/core/llm/templates/edit.ts b/core/llm/templates/edit.ts index abe914f74..b1d6f7b89 100644 --- a/core/llm/templates/edit.ts +++ b/core/llm/templates/edit.ts @@ -19,16 +19,46 @@ Here is the edit requested: Here is the code after editing:`; -const gptEditPrompt = `\ -\`\`\`{{{language}}} -{{{codeToEdit}}} +const gptEditPrompt: PromptTemplate = (_, otherData) => { + if (otherData?.codeToEdit?.trim().length === 0) { + return `\ +\`\`\`${otherData.language} +${otherData.prefix}[BLANK]${otherData.codeToEdit}${otherData.suffix} \`\`\` -You are an expert programmer. You will rewrite the above code to do the following: +Given the user's request: "${otherData.userInput}" -{{{userInput}}} +Here is the code that should fill in the [BLANK]:`; + } -Output only a code block with the rewritten code:`; + const paragraphs = [ + "The user has requested a section of code in a file to be rewritten.", + ]; + if (otherData.prefix?.trim().length > 0) { + paragraphs.push(`This is the prefix of the file: +\`\`\`${otherData.language} +${otherData.prefix} +\`\`\``); + } + + if (otherData.suffix?.trim().length > 0) { + paragraphs.push(`This is the suffix of the file: +\`\`\`${otherData.language} +${otherData.suffix} +\`\`\``); + } + + paragraphs.push(`This is the code to rewrite: +\`\`\`${otherData.language} +${otherData.codeToEdit} +\`\`\` + +The user's request is: "${otherData.userInput}" + +Here is the rewritten code:`); + + return paragraphs.join("\n\n"); +}; const codellamaInfillEditPrompt = "{{filePrefix}}{{fileSuffix}}"; diff --git a/core/util/verticalEdit.ts b/core/util/verticalEdit.ts index 1cbe6936d..876b713f0 100644 --- a/core/util/verticalEdit.ts +++ b/core/util/verticalEdit.ts @@ -9,10 +9,12 @@ import { import { streamDiff } from "../diff/streamDiff"; import { streamLines } from "../diff/util"; import { gptEditPrompt } from "../llm/templates/edit"; -import { dedentAndGetCommonWhitespace, renderPromptTemplate } from "../util"; +import { renderPromptTemplate } from "../util"; function constructPrompt( - codeToEdit: string, + prefix: string, + highlighted: string, + suffix: string, llm: ILLM, userInput: string, language: string | undefined, @@ -20,7 +22,9 @@ function constructPrompt( const template = llm.promptTemplates?.edit ?? gptEditPrompt; return renderPromptTemplate(template, [], { userInput, - codeToEdit, + prefix, + codeToEdit: highlighted, + suffix, language: language ?? "", }); } @@ -42,17 +46,33 @@ function modelIsInept(model: string): boolean { } export async function* streamDiffLines( - oldCode: string, + prefix: string, + highlighted: string, + suffix: string, llm: ILLM, input: string, language: string | undefined, ): AsyncGenerator { // Strip common indentation for the LLM, then add back after generation - const [withoutIndentation, commonIndentation] = - dedentAndGetCommonWhitespace(oldCode); - oldCode = withoutIndentation; - const oldLines = oldCode.split("\n"); - const prompt = constructPrompt(oldCode, llm, input, language); + let oldLines = + highlighted.length > 0 + ? highlighted.split("\n") + : // When highlighted is empty, we need to combine last line of prefix and first line of suffix to determine the line being edited + [(prefix + suffix).split("\n")[prefix.split("\n").length - 1]]; + + // But if that line is empty, we can assume we are insertion-only + if (oldLines.length === 1 && oldLines[0].trim() === "") { + oldLines = []; + } + + const prompt = constructPrompt( + prefix, + highlighted, + suffix, + llm, + input, + language, + ); const inept = modelIsInept(llm.model); const completion = @@ -62,17 +82,19 @@ export async function* streamDiffLines( let lines = streamLines(completion); - if (inept) { - lines = filterEnglishLinesAtStart(lines); - } + lines = filterEnglishLinesAtStart(lines); lines = filterCodeBlockLines(lines); if (inept) { lines = filterEnglishLinesAtEnd(fixCodeLlamaFirstLineIndentation(lines)); } let diffLines = streamDiff(oldLines, lines); - diffLines = addIndentation(diffLines, commonIndentation); diffLines = filterLeadingAndTrailingNewLineInsertion(diffLines); + if (highlighted.length === 0) { + const line = prefix.split("\n").slice(-1)[0]; + const indentation = line.slice(0, line.length - line.trimStart().length); + diffLines = addIndentation(diffLines, indentation); + } for await (let diffLine of diffLines) { yield diffLine; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt index d05a7ff96..3a7e81b6b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt @@ -27,7 +27,7 @@ import javax.swing.JComponent fun getDiffDirectory(): File { val homeDirectory = System.getProperty("user.home") - val diffDirPath = Paths.get(homeDirectory).resolve(".continue").resolve("diffs").toString() + val diffDirPath = Paths.get(homeDirectory).resolve(".continue").resolve(".diffs").toString() val diffDir = File(diffDirPath) if (!diffDir.exists()) { diffDir.mkdirs() diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 50d9a7872..510bea4b5 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -100,6 +100,18 @@ "group": "Continue", "icon": "$(stop)" }, + { + "command": "continue.acceptVerticalDiffBlock", + "category": "Continue", + "title": "Accept Vertical Diff Block", + "group": "Continue" + }, + { + "command": "continue.rejectVerticalDiffBlock", + "category": "Continue", + "title": "Reject Vertical Diff Block", + "group": "Continue" + }, { "command": "continue.quickEdit", "category": "Continue", @@ -219,7 +231,17 @@ "command": "continue.rejectDiff", "mac": "cmd+z", "key": "ctrl+z", - "when": "continue.streamingDiff" + "when": "continue.diffVisible" + }, + { + "command": "continue.acceptVerticalDiffBlock", + "mac": "alt+cmd+y", + "key": "alt+ctrl+y" + }, + { + "command": "continue.rejectVerticalDiffBlock", + "mac": "alt+cmd+n", + "key": "alt+ctrl+n" }, { "command": "continue.quickEdit", diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index f5a38e7eb..b45de441e 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -164,18 +164,56 @@ const commandsMap: ( "continue.quickEdit": async () => { const selectionEmpty = vscode.window.activeTextEditor?.selection.isEmpty; - let text = await vscode.window.showInputBox({ + const editor = vscode.window.activeTextEditor; + const existingHandler = verticalDiffManager.getHandlerForFile( + editor?.document.uri.fsPath ?? "", + ); + const previousInput = existingHandler?.input; + + let defaultModelTitle = await sidebar.webviewProtocol.request( + "getDefaultModelTitle", + undefined, + ); + const config = await configHandler.loadConfig(); + if (!defaultModelTitle) { + defaultModelTitle = config.models[0]?.title!; + } + const quickPickItems = + config.contextProviders + ?.filter((provider) => provider.description.type === "normal") + .map((provider) => { + return { + label: provider.description.displayTitle, + description: provider.description.title, + detail: provider.description.description, + }; + }) || []; + + const addContextMsg = quickPickItems.length + ? " (or press enter to add context first)" + : ""; + const textInputOptions: vscode.InputBoxOptions = { placeHolder: selectionEmpty - ? "Describe the code you want to generate (or press enter to add context first)" - : "Describe how to edit the highlighted code (or press enter to add context first)", + ? `Type instructions to generate code${addContextMsg}` + : `Describe how to edit the highlighted code${addContextMsg}`, title: "Continue Quick Edit", - }); + prompt: `[${defaultModelTitle}]`, + }; + if (previousInput) { + textInputOptions.value = previousInput + ", "; + textInputOptions.valueSelection = [ + textInputOptions.value.length, + textInputOptions.value.length, + ]; + } + + let text = await vscode.window.showInputBox(textInputOptions); if (text === undefined) { return; } - if (text.length > 0) { + if (text.length > 0 || quickPickItems.length === 0) { const modelName = await sidebar.webviewProtocol.request( "getDefaultModelTitle", undefined, @@ -183,22 +221,6 @@ const commandsMap: ( await verticalDiffManager.streamEdit(text, modelName); } else { // Pick context first - const quickPickItems: Promise = configHandler - .loadConfig() - .then((config) => { - return ( - config.contextProviders - ?.filter((provider) => provider.description.type === "normal") - .map((provider) => { - return { - label: provider.description.displayTitle, - description: provider.description.title, - detail: provider.description.description, - }; - }) || [] - ); - }); - const selectedProviders = await vscode.window.showQuickPick( quickPickItems, { @@ -207,12 +229,7 @@ const commandsMap: ( }, ); - let text = await vscode.window.showInputBox({ - placeHolder: selectionEmpty - ? "Describe the code you want to generate (or press enter to add context first)" - : "Describe how to edit the highlighted code (or press enter to add context first)", - title: "Continue Quick Edit", - }); + let text = await vscode.window.showInputBox(textInputOptions); if (text) { const llm = await configHandler.llmFromTitle(); const config = await configHandler.loadConfig(); @@ -243,13 +260,7 @@ const commandsMap: ( "\n\n---\n\n" + text; - await verticalDiffManager.streamEdit( - text, - await sidebar.webviewProtocol.request( - "getDefaultModelTitle", - undefined, - ), - ); + await verticalDiffManager.streamEdit(text, defaultModelTitle); } } }, diff --git a/extensions/vscode/src/diff/horizontal.ts b/extensions/vscode/src/diff/horizontal.ts index dbf251f5a..fcb77bded 100644 --- a/extensions/vscode/src/diff/horizontal.ts +++ b/extensions/vscode/src/diff/horizontal.ts @@ -27,7 +27,7 @@ async function writeFile(uri: vscode.Uri, contents: string) { // THIS IS LOCAL export const DIFF_DIRECTORY = path - .join(os.homedir(), ".continue", "diffs") + .join(os.homedir(), ".continue", ".diffs") .replace(/^C:/, "c:"); export class DiffManager { diff --git a/extensions/vscode/src/diff/verticalPerLine/decorations.ts b/extensions/vscode/src/diff/verticalPerLine/decorations.ts index 96cc4372e..fa6e70baf 100644 --- a/extensions/vscode/src/diff/verticalPerLine/decorations.ts +++ b/extensions/vscode/src/diff/verticalPerLine/decorations.ts @@ -43,6 +43,11 @@ export class DecorationTypeRangeManager { private ranges: vscode.Range[] = []; + applyToNewEditor(newEditor: vscode.TextEditor) { + this.editor = newEditor; + this.editor.setDecorations(this.decorationType, this.ranges); + } + addLines(startIndex: number, numLines: number) { const lastRange = this.ranges[this.ranges.length - 1]; if (lastRange && lastRange.end.line === startIndex - 1) { diff --git a/extensions/vscode/src/diff/verticalPerLine/handler.ts b/extensions/vscode/src/diff/verticalPerLine/handler.ts index 302456eef..fed6e0737 100644 --- a/extensions/vscode/src/diff/verticalPerLine/handler.ts +++ b/extensions/vscode/src/diff/verticalPerLine/handler.ts @@ -38,6 +38,7 @@ export class VerticalPerLineDiffHandler { filepath: string | undefined, accept: boolean, ) => void, + private readonly refreshCodeLens: () => void, input?: string, ) { this.currentLineIndex = startLine; @@ -54,6 +55,20 @@ export class VerticalPerLineDiffHandler { greenDecorationType, this.editor, ); + + vscode.window.onDidChangeActiveTextEditor((editor) => { + // When we switch away and back to this editor, need to re-draw decorations + if (editor?.document.uri.fsPath === this.filepath) { + this.editor = editor; + this.redDecorationManager.applyToNewEditor(editor); + this.greenDecorationManager.applyToNewEditor(editor); + this.updateIndexLineDecorations(); + this.refreshCodeLens(); + + // Handle any lines received while editor was closed + this.queueDiffLine(undefined); + } + }); } private get filepath() { @@ -121,21 +136,27 @@ export class VerticalPerLineDiffHandler { private greenDecorationManager: DecorationTypeRangeManager; private async insertTextAboveLine(index: number, text: string) { - await this.editor.edit((editBuilder) => { - const lineCount = this.editor.document.lineCount; - if (index >= lineCount) { - // Append to end of file - editBuilder.insert( - new vscode.Position( - lineCount, - this.editor.document.lineAt(lineCount - 1).text.length, - ), - "\n" + text, - ); - } else { - editBuilder.insert(new vscode.Position(index, 0), text + "\n"); - } - }); + await this.editor.edit( + (editBuilder) => { + const lineCount = this.editor.document.lineCount; + if (index >= lineCount) { + // Append to end of file + editBuilder.insert( + new vscode.Position( + lineCount, + this.editor.document.lineAt(lineCount - 1).text.length, + ), + "\n" + text, + ); + } else { + editBuilder.insert(new vscode.Position(index, 0), text + "\n"); + } + }, + { + undoStopAfter: false, + undoStopBefore: false, + }, + ); } private async insertLineAboveIndex(index: number, line: string) { @@ -146,11 +167,17 @@ export class VerticalPerLineDiffHandler { private async deleteLinesAt(index: number, numLines: number = 1) { const startLine = new vscode.Position(index, 0); - await this.editor.edit((editBuilder) => { - editBuilder.delete( - new vscode.Range(startLine, startLine.translate(numLines)), - ); - }); + await this.editor.edit( + (editBuilder) => { + editBuilder.delete( + new vscode.Range(startLine, startLine.translate(numLines)), + ); + }, + { + undoStopAfter: false, + undoStopBefore: false, + }, + ); } private updateIndexLineDecorations() { @@ -195,25 +222,64 @@ export class VerticalPerLineDiffHandler { this.editorToVerticalDiffCodeLens.delete(this.filepath); - this.editor.edit((editBuilder) => { - for (const range of rangesToDelete) { - editBuilder.delete( - new vscode.Range( - range.start, - new vscode.Position(range.end.line + 1, 0), - ), - ); - } - }); + this.editor.edit( + (editBuilder) => { + for (const range of rangesToDelete) { + editBuilder.delete( + new vscode.Range( + range.start, + new vscode.Position(range.end.line + 1, 0), + ), + ); + } + }, + { + undoStopAfter: false, + undoStopBefore: false, + }, + ); this.cancelled = true; + this.refreshCodeLens(); } get isCancelled() { return this.cancelled; } - async handleDiffLine(diffLine: DiffLine) { + private _diffLinesQueue: DiffLine[] = []; + private _queueLock = false; + + async queueDiffLine(diffLine: DiffLine | undefined) { + if (diffLine) { + this._diffLinesQueue.push(diffLine); + } + + if (this._queueLock || this.editor !== vscode.window.activeTextEditor) { + return; + } + + this._queueLock = true; + + while (this._diffLinesQueue.length) { + const line = this._diffLinesQueue.shift(); + if (!line) { + break; + } + + try { + await this._handleDiffLine(line); + } catch (e) { + // If editor is switched between calling _handleDiffLine and the edit actually being executed + this._diffLinesQueue.push(line); + break; + } + } + + this._queueLock = false; + } + + private async _handleDiffLine(diffLine: DiffLine) { switch (diffLine.type) { case "same": await this.insertDeletionBuffer(); @@ -241,7 +307,7 @@ export class VerticalPerLineDiffHandler { if (this.isCancelled) { return; } - await this.handleDiffLine(diffLine); + await this.queueDiffLine(diffLine); } // Clear deletion buffer @@ -303,5 +369,7 @@ export class VerticalPerLineDiffHandler { return x; }) || []; this.editorToVerticalDiffCodeLens.set(this.filepath, blocks); + + this.refreshCodeLens(); } } diff --git a/extensions/vscode/src/diff/verticalPerLine/manager.ts b/extensions/vscode/src/diff/verticalPerLine/manager.ts index 7d10ff8f1..4c0fabf06 100644 --- a/extensions/vscode/src/diff/verticalPerLine/manager.ts +++ b/extensions/vscode/src/diff/verticalPerLine/manager.ts @@ -12,10 +12,12 @@ export interface VerticalDiffCodeLens { } export class VerticalPerLineDiffManager { - private filepathToEditorMap: Map = + public refreshCodeLens: () => void = () => {}; + + private filepathToHandler: Map = new Map(); - editorToVerticalDiffCodeLens: Map = new Map(); + filepathToCodeLens: Map = new Map(); constructor(private readonly configHandler: ConfigHandler) {} @@ -25,9 +27,9 @@ export class VerticalPerLineDiffManager { endLine: number, input: string, ) { - if (this.filepathToEditorMap.has(filepath)) { - this.filepathToEditorMap.get(filepath)?.clear(false); - this.filepathToEditorMap.delete(filepath); + if (this.filepathToHandler.has(filepath)) { + this.filepathToHandler.get(filepath)?.clear(false); + this.filepathToHandler.delete(filepath); } const editor = vscode.window.activeTextEditor; // TODO if (editor && editor.document.uri.fsPath === filepath) { @@ -35,11 +37,12 @@ export class VerticalPerLineDiffManager { startLine, endLine, editor, - this.editorToVerticalDiffCodeLens, + this.filepathToCodeLens, this.clearForFilepath.bind(this), + this.refreshCodeLens, input, ); - this.filepathToEditorMap.set(filepath, handler); + this.filepathToHandler.set(filepath, handler); return handler; } else { return undefined; @@ -51,8 +54,8 @@ export class VerticalPerLineDiffManager { startLine: number, endLine: number, ) { - if (this.filepathToEditorMap.has(filepath)) { - return this.filepathToEditorMap.get(filepath)!; + if (this.filepathToHandler.has(filepath)) { + return this.filepathToHandler.get(filepath)!; } else { const editor = vscode.window.activeTextEditor; // TODO if (editor && editor.document.uri.fsPath === filepath) { @@ -60,10 +63,11 @@ export class VerticalPerLineDiffManager { startLine, endLine, editor, - this.editorToVerticalDiffCodeLens, + this.filepathToCodeLens, this.clearForFilepath.bind(this), + this.refreshCodeLens, ); - this.filepathToEditorMap.set(filepath, handler); + this.filepathToHandler.set(filepath, handler); return handler; } else { return undefined; @@ -72,7 +76,7 @@ export class VerticalPerLineDiffManager { } getHandlerForFile(filepath: string) { - return this.filepathToEditorMap.get(filepath); + return this.filepathToHandler.get(filepath); } clearForFilepath(filepath: string | undefined, accept: boolean) { @@ -84,11 +88,13 @@ export class VerticalPerLineDiffManager { filepath = activeEditor.document.uri.fsPath; } - const handler = this.filepathToEditorMap.get(filepath); + const handler = this.filepathToHandler.get(filepath); if (handler) { handler.clear(accept); - this.filepathToEditorMap.delete(filepath); + this.filepathToHandler.delete(filepath); } + + vscode.commands.executeCommand("setContext", "continue.diffVisible", false); } acceptRejectVerticalDiffBlock( @@ -108,7 +114,7 @@ export class VerticalPerLineDiffManager { index = 0; } - let blocks = this.editorToVerticalDiffCodeLens.get(filepath); + let blocks = this.filepathToCodeLens.get(filepath); const block = blocks?.[index]; if (!blocks || !block) { return; @@ -126,9 +132,15 @@ export class VerticalPerLineDiffManager { block.numGreen, block.numRed, ); + + if (blocks.length === 1) { + this.clearForFilepath(filepath, true); + } } async streamEdit(input: string, modelTitle: string | undefined) { + vscode.commands.executeCommand("setContext", "continue.diffVisible", true); + const editor = vscode.window.activeTextEditor; if (!editor) { return; @@ -153,13 +165,26 @@ export class VerticalPerLineDiffManager { return; } - const selectedRange = - existingHandler?.range ?? - new vscode.Range( + let selectedRange = existingHandler?.range ?? editor.selection; + + // Only if the selection is empty, use exact prefix/suffix instead of by line + if (!selectedRange.isEmpty) { + selectedRange = new vscode.Range( editor.selection.start.with(undefined, 0), editor.selection.end.with(undefined, Number.MAX_SAFE_INTEGER), ); + } + const rangeContent = editor.document.getText(selectedRange); + const prefix = editor.document.getText( + new vscode.Range(new vscode.Position(0, 0), selectedRange.start), + ); + const suffix = editor.document.getText( + new vscode.Range( + selectedRange.end, + new vscode.Position(editor.document.lineCount, 0), + ), + ); const llm = await this.configHandler.llmFromTitle(modelTitle); // Unselect the range @@ -174,14 +199,6 @@ export class VerticalPerLineDiffManager { true, ); - if (existingHandler?.input) { - if (existingHandler.input.startsWith("Original request: ")) { - existingHandler.input = existingHandler.input.substring( - "Original request: ".length, - ); - } - input = `Original request: ${existingHandler.input}\nUpdated request: ${input}`; - } try { Telemetry.capture("inlineEdit", { model: llm.model, @@ -189,7 +206,9 @@ export class VerticalPerLineDiffManager { }); await diffHandler.run( streamDiffLines( + prefix, rangeContent, + suffix, llm, input, getMarkdownLanguageTagForFile(filepath), diff --git a/extensions/vscode/src/extension/vscodeExtension.ts b/extensions/vscode/src/extension/vscodeExtension.ts index 83cffbb43..d16c1635e 100644 --- a/extensions/vscode/src/extension/vscodeExtension.ts +++ b/extensions/vscode/src/extension/vscodeExtension.ts @@ -143,11 +143,13 @@ export class VsCodeExtension { } // CodeLens - registerAllCodeLensProviders( + const verticalDiffCodeLens = registerAllCodeLensProviders( context, this.diffManager, - this.verticalDiffManager.editorToVerticalDiffCodeLens, + this.verticalDiffManager.filepathToCodeLens, ); + this.verticalDiffManager.refreshCodeLens = + verticalDiffCodeLens.refresh.bind(verticalDiffCodeLens); // Tab autocomplete const config = vscode.workspace.getConfiguration("continue"); diff --git a/extensions/vscode/src/lang-server/codeLens.ts b/extensions/vscode/src/lang-server/codeLens.ts index d2a2686a9..3589f7ba4 100644 --- a/extensions/vscode/src/lang-server/codeLens.ts +++ b/extensions/vscode/src/lang-server/codeLens.ts @@ -4,10 +4,18 @@ import * as vscode from "vscode"; import { DIFF_DIRECTORY, DiffManager } from "../diff/horizontal"; import { VerticalDiffCodeLens } from "../diff/verticalPerLine/manager"; import { editorSuggestionsLocked, editorToSuggestions } from "../suggestions"; -import { getMetaKeyLabel } from "../util/util"; +import { getAltOrOption, getMetaKeyLabel } from "../util/util"; import { getExtensionUri } from "../util/vscode"; class VerticalPerLineCodeLensProvider implements vscode.CodeLensProvider { + private _eventEmitter: vscode.EventEmitter = + new vscode.EventEmitter(); + onDidChangeCodeLenses: vscode.Event = this._eventEmitter.event; + + public refresh(): void { + this._eventEmitter.fire(); + } + constructor( private readonly editorToVerticalDiffCodeLens: Map< string, @@ -33,22 +41,44 @@ class VerticalPerLineCodeLensProvider implements vscode.CodeLensProvider { start, start.translate(block.numGreen + block.numRed), ); + if (codeLenses.length === 0) { + codeLenses.push( + new vscode.CodeLens(range, { + title: `Accept All (${getMetaKeyLabel()}โ‡งโ†ฉ)`, + command: "continue.acceptVerticalDiffBlock", + arguments: [filepath, i], + }), + new vscode.CodeLens(range, { + title: `Reject All (${getMetaKeyLabel()}โ‡งโŒซ)`, + command: "continue.rejectVerticalDiffBlock", + arguments: [filepath, i], + }), + ); + } codeLenses.push( new vscode.CodeLens(range, { - title: "Accept", + title: `Accept${ + codeLenses.length === 2 + ? ` (${getAltOrOption()}${getMetaKeyLabel()}Y)` + : "" + }`, command: "continue.acceptVerticalDiffBlock", arguments: [filepath, i], }), new vscode.CodeLens(range, { - title: "Reject", + title: `Reject${ + codeLenses.length === 2 + ? ` (${getAltOrOption()}${getMetaKeyLabel()}N)` + : "" + }`, command: "continue.rejectVerticalDiffBlock", arguments: [filepath, i], }), ); - if (codeLenses.length === 2) { + if (codeLenses.length === 4) { codeLenses.push( new vscode.CodeLens(range, { - title: `(${getMetaKeyLabel()}โ‡งโ†ฉ/${getMetaKeyLabel()}โ‡งโŒซ to accept/reject all, ${getMetaKeyLabel()}I to retry)`, + title: `${getMetaKeyLabel()}I to add instructions`, command: "", }), ); @@ -341,7 +371,8 @@ class TutorialCodeLensProvider implements vscode.CodeLensProvider { } } -let verticalPerLineCodeLensProvider: vscode.Disposable | undefined = undefined; +export let verticalPerLineCodeLensProvider: vscode.Disposable | undefined = + undefined; let diffsCodeLensDisposable: vscode.Disposable | undefined = undefined; let suggestionsCodeLensDisposable: vscode.Disposable | undefined = undefined; let configPyCodeLensDisposable: vscode.Disposable | undefined = undefined; @@ -368,9 +399,12 @@ export function registerAllCodeLensProviders( tutorialCodeLensDisposable.dispose(); } + const verticalDiffCodeLens = new VerticalPerLineCodeLensProvider( + editorToVerticalDiffCodeLens, + ); verticalPerLineCodeLensProvider = vscode.languages.registerCodeLensProvider( "*", - new VerticalPerLineCodeLensProvider(editorToVerticalDiffCodeLens), + verticalDiffCodeLens, ); suggestionsCodeLensDisposable = vscode.languages.registerCodeLensProvider( "*", @@ -393,4 +427,6 @@ export function registerAllCodeLensProviders( context.subscriptions.push(diffsCodeLensDisposable); context.subscriptions.push(configPyCodeLensDisposable); context.subscriptions.push(tutorialCodeLensDisposable); + + return verticalDiffCodeLens; } diff --git a/extensions/vscode/src/util/util.ts b/extensions/vscode/src/util/util.ts index 9d13b81f7..5a2f5cbf8 100644 --- a/extensions/vscode/src/util/util.ts +++ b/extensions/vscode/src/util/util.ts @@ -79,6 +79,14 @@ export function getPlatform(): Platform { } } +export function getAltOrOption() { + if (getPlatform() === "mac") { + return "โŒฅ"; + } else { + return "โއ"; + } +} + export function getMetaKeyLabel() { const platform = getPlatform(); switch (platform) { diff --git a/gui/src/components/dialogs/KeyboardShortcuts.tsx b/gui/src/components/dialogs/KeyboardShortcuts.tsx index d4a55d030..c8d3f8397 100644 --- a/gui/src/components/dialogs/KeyboardShortcuts.tsx +++ b/gui/src/components/dialogs/KeyboardShortcuts.tsx @@ -40,6 +40,7 @@ const keyToName = { "โŽ": "Enter", "โŒซ": "Backspace", "โŒฅ": "Option", + "โއ": "Alt", }; function KeyDiv({ text }: { text: string }) { @@ -113,9 +114,19 @@ const vscodeShortcuts: KeyboardShortcutProps[] = [ windows: "โŒƒ โ‡ง โŒซ", description: "Reject Diff", }, + { + mac: "โŒฅ โŒ˜ Y", + windows: "โއ โŒƒ Y", + description: "Accept Top Change in Diff", + }, + { + mac: "โŒฅ โŒ˜ N", + windows: "โއ โŒƒ N", + description: "Reject Top Change in Diff", + }, { mac: "โŒฅ โŒ˜ L", - windows: "โŒฅ โŒƒ L", + windows: "โއ โŒƒ L", description: "Toggle Auxiliary Bar", }, { @@ -163,12 +174,12 @@ const jetbrainsShortcuts: KeyboardShortcutProps[] = [ }, { mac: "โŒฅ โ‡ง J", - windows: "โŒฅ โ‡ง J", + windows: "โއ โ‡ง J", description: "Quick Input", }, { mac: "โŒฅ โŒ˜ J", - windows: "โŒฅ โŒƒ J", + windows: "โއ โŒƒ J", description: "Toggle Sidebar", }, {