🔥 Improved Ctrl/Cmd+I (#1023)

* ⚡️ 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
This commit is contained in:
Nate Sesti 2024-03-26 15:55:32 -07:00 • committed by GitHub
parent 898506b492
commit 98affeaa81
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 382 additions and 130 deletions

View file

@ -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;

View file

@ -14,6 +14,8 @@ export async function* streamDiff(
newLines: LineStream,
): AsyncGenerator<DiffLine> {
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();

View file

@ -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() &&

View file

@ -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}}<FILL>{{fileSuffix}}";

View file

@ -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<DiffLine> {
// 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;

View file

@ -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()

View file

@ -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",

View file

@ -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<vscode.QuickPickItem[]> = 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);
}
}
},

View file

@ -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 {

View file

@ -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) {

View file

@ -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();
}
}

View file

@ -12,10 +12,12 @@ export interface VerticalDiffCodeLens {
}
export class VerticalPerLineDiffManager {
private filepathToEditorMap: Map<string, VerticalPerLineDiffHandler> =
public refreshCodeLens: () => void = () => {};
private filepathToHandler: Map<string, VerticalPerLineDiffHandler> =
new Map();
editorToVerticalDiffCodeLens: Map<string, VerticalDiffCodeLens[]> = new Map();
filepathToCodeLens: Map<string, VerticalDiffCodeLens[]> = 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),

View file

@ -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");

View file

@ -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<void> =
new vscode.EventEmitter<void>();
onDidChangeCodeLenses: vscode.Event<void> = 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;
}

View file

@ -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) {

View file

@ -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",
},
{