diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index b2cfbd9d9..b329dd0a1 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -5,17 +5,16 @@ import OpenAI from "../llm/llms/OpenAI.js"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; -import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js"; -import { aggregateSnippets } from "./aggregateSnippets"; +import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; // @prettier-ignore -import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; -import { AutocompleteSnippet } from "./context/ranking/index.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { CompletionStreamer } from "./generation/CompletionStreamer.js"; import { postprocessCompletion } from "./postprocessing/index.js"; import { shouldPrefilter } from "./prefiltering/index.js"; +import { getAllSnippets } from "./snippets/index.js"; import { renderPrompt } from "./templating/index.js"; +import { GetLspDefinitionsFunction } from "./types.js"; import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js"; import { AutocompleteLoggingService } from "./util/AutocompleteLoggingService.js"; import AutocompleteLruCache from "./util/AutocompleteLruCache.js"; @@ -32,14 +31,6 @@ const ERRORS_TO_IGNORE = [ "operation was aborted", ]; -export type GetLspDefinitionsFunction = ( - filepath: string, - contents: string, - cursorIndex: number, - ide: IDE, - lang: AutocompleteLanguageInfo, -) => Promise; - export class CompletionProvider { private autocompleteCache = AutocompleteLruCache.get(); public errorsShown: Set = new Set(); @@ -171,26 +162,22 @@ export class CompletionProvider { token = controller.signal; } - ////////// - - // Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems, - // or they might separately track recently edited ranges) - const extraSnippets = await this._getExtraSnippets(helper); - - const [snippets, diff, clipboardContent, workspaceDirs] = - await Promise.all([ - aggregateSnippets( - helper, - extraSnippets, - this.contextRetrievalService, - ), - this.ide.getDiff(true), - this.ide.getClipboardContent(), - this.ide.getWorkspaceDirs(), - ]); + const [ + { snippets, diff, clipboardContent, payload: snippetPayload }, + workspaceDirs, + ] = await Promise.all([ + getAllSnippets({ + helper, + ide: this.ide, + getDefinitionsFromLsp: this.getDefinitionsFromLsp, + contextRetrievalService: this.contextRetrievalService, + }), + this.ide.getWorkspaceDirs(), + ]); const { prompt, prefix, suffix, completionOptions } = renderPrompt({ snippets, + snippetPayload, diff, clipboardContent, workspaceDirs, @@ -288,32 +275,4 @@ export class CompletionProvider { this.loggingService.deleteAbortController(input.completionId); } } - - private async _getExtraSnippets( - helper: HelperVars, - ): Promise { - let extraSnippets = helper.options.useOtherFiles - ? ((await Promise.race([ - this.getDefinitionsFromLsp( - helper.input.filepath, - helper.fullPrefix + helper.fullSuffix, - helper.fullPrefix.length, - this.ide, - helper.lang, - ), - new Promise((resolve) => { - setTimeout(() => resolve([]), 100); - }), - ])) as AutocompleteSnippet[]) - : []; - - const workspaceDirs = await this.ide.getWorkspaceDirs(); - if (helper.options.onlyMyCode) { - extraSnippets = extraSnippets.filter((snippet) => { - return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)); - }); - } - - return extraSnippets; - } } diff --git a/core/autocomplete/README.md b/core/autocomplete/README.md index 9baf9cd4b..627ca1206 100644 --- a/core/autocomplete/README.md +++ b/core/autocomplete/README.md @@ -87,7 +87,6 @@ This is just another object like the ones in the `"models"` array of `config.jso This object allows you to customize the behavior of tab-autocomplete. The available options are: -- `useCopyBuffer`: Determines whether the copy buffer will be considered when constructing the prompt. (Boolean) - `useFileSuffix`: Determines whether to use the file suffix in the prompt. (Boolean) - `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number) - `debounceDelay`: The delay in milliseconds before triggering autocomplete after a keystroke. (Number) @@ -107,7 +106,6 @@ This object allows you to customize the behavior of tab-autocomplete. The availa "apiBase": "https://" }, "tabAutocompleteOptions": { - "useCopyBuffer": false, "maxPromptTokens": 400, "prefixPercentage": 0.5 } diff --git a/core/autocomplete/aggregateSnippets.ts b/core/autocomplete/aggregateSnippets.ts deleted file mode 100644 index f47b9021f..000000000 --- a/core/autocomplete/aggregateSnippets.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; -import { - fillPromptWithSnippets, - rankAndOrderSnippets, - type AutocompleteSnippet, -} from "./context/ranking/index.js"; -import { HelperVars } from "./util/HelperVars.js"; - -function filterSnippetsAlreadyInCaretWindow( - snippets: AutocompleteSnippet[], - caretWindow: string, -): AutocompleteSnippet[] { - return snippets - .map((snippet) => ({ ...snippet })) - .filter( - (s) => - s.contents.trim() !== "" && !caretWindow.includes(s.contents.trim()), - ); -} - -export async function aggregateSnippets( - helper: HelperVars, - extraSnippets: AutocompleteSnippet[], - contextRetrievalService: ContextRetrievalService, -): Promise { - let snippets = await contextRetrievalService.retrieveCandidateSnippets( - helper, - extraSnippets, - ); - - snippets = filterSnippetsAlreadyInCaretWindow( - snippets, - helper.prunedCaretWindow, - ); - - const scoredSnippets = rankAndOrderSnippets(snippets, helper); - - const finalSnippets = fillPromptWithSnippets( - scoredSnippets, - helper.maxSnippetTokens, - helper.modelName, - ); - - return finalSnippets; -} diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts index 24f6e9182..72e061fed 100644 --- a/core/autocomplete/context/ContextRetrievalService.ts +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -1,9 +1,12 @@ import { IDE } from "../.."; +import { + AutocompleteCodeSnippet, + AutocompleteSnippetType, +} from "../snippets/types"; import { HelperVars } from "../util/HelperVars"; -import { RecentlyEditedRange } from "../util/types"; import { ImportDefinitionsService } from "./ImportDefinitionsService"; -import { AutocompleteSnippet, getSymbolsForSnippet } from "./ranking"; +import { getSymbolsForSnippet } from "./ranking"; import { RootPathContextService } from "./root-path-context/RootPathContextService"; export class ContextRetrievalService { @@ -18,79 +21,14 @@ export class ContextRetrievalService { ); } - public async retrieveCandidateSnippets( + public async getSnippetsFromImportDefinitions( helper: HelperVars, - extraSnippets: AutocompleteSnippet[], - ) { - if (helper.options.useOtherFiles === false) { - return []; - } - - let snippets: AutocompleteSnippet[] = []; - - // Snippets injected by the IDE for IDE-specific reasons - snippets.push(...extraSnippets); - - // If a recently edited range has a line that is a perfect match with the start of the current line - snippets.push(...this.getSnippetsFromRecentlyEditedRanges(helper)); - - // Import definitions of any symbols in near range of the caret - snippets.push(...(await this.getSnippetsFromImportDefinitions(helper))); - - // Root path context https://blog.continue.dev/root-path-context-the-secret-ingredient-in-continues-autocomplete-prompt/ - if (helper.options.useRootPathContext && helper.treePath) { - snippets.push( - ...(await this.rootPathContextService.getContextForPath( - helper.filepath, - helper.treePath, - )), - ); - } - - return snippets; - } - - private getSnippetsFromRecentlyEditedRanges( - helper: HelperVars, - ): AutocompleteSnippet[] { - if (helper.options.useRecentlyEdited === false) { - return []; - } - - const currentLinePrefix = helper.prunedPrefix - .trim() - .split("\n") - .slice(-1)[0]; - if ( - currentLinePrefix?.length > helper.options.recentLinePrefixMatchMinLength - ) { - const matchingRange = this.findMatchingRange( - helper.input.recentlyEditedRanges, - currentLinePrefix, - ); - - if (matchingRange) { - return [ - { - ...matchingRange, - contents: matchingRange.lines.join("\n"), - score: 0.8, - }, - ]; - } - } - - return []; - } - - private async getSnippetsFromImportDefinitions( - helper: HelperVars, - ): Promise { + ): Promise { if (helper.options.useImports === false) { return []; } - const importSnippets = []; + const importSnippets: AutocompleteCodeSnippet[] = []; const fileInfo = this.importDefinitionsService.get(helper.filepath); if (fileInfo) { const { imports } = fileInfo; @@ -104,21 +42,32 @@ export class ContextRetrievalService { for (const symbol of symbols) { const rifs = imports[symbol]; if (Array.isArray(rifs)) { - importSnippets.push(...rifs); + const snippets: AutocompleteCodeSnippet[] = rifs.map((rif) => { + return { + filepath: rif.filepath, + content: rif.contents, + type: AutocompleteSnippetType.Code, + }; + }); + + importSnippets.push(...snippets); } } } + return importSnippets; } - findMatchingRange( - recentlyEditedRanges: RecentlyEditedRange[], - linePrefix: string, - ): RecentlyEditedRange | undefined { - return recentlyEditedRanges.find((recentlyEditedRange) => { - return recentlyEditedRange.lines.some((line) => - line.startsWith(linePrefix), - ); - }); + public async getRootPathSnippets( + helper: HelperVars, + ): Promise { + if (!helper.treePath) { + return []; + } + + return this.rootPathContextService.getContextForPath( + helper.filepath, + helper.treePath, + ); } } diff --git a/core/autocomplete/context/ranking/index.ts b/core/autocomplete/context/ranking/index.ts index e68763746..1064fd243 100644 --- a/core/autocomplete/context/ranking/index.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -1,11 +1,8 @@ -import { Range, RangeInFileWithContents } from "../../../"; +import { RangeInFileWithContents } from "../../../"; import { countTokens } from "../../../llm/countTokens"; +import { AutocompleteSnippetDeprecated } from "../../types"; import { HelperVars } from "../../util/HelperVars"; -export type AutocompleteSnippet = RangeInFileWithContents & { - score?: number; -}; - const rx = /[\s.,\/#!$%\^&\*;:{}=\-_`~()\[\]]/g; export function getSymbolsForSnippet(snippet: string): Set { const symbols = snippet @@ -18,7 +15,7 @@ export function getSymbolsForSnippet(snippet: string): Set { /** * Calculate similarity as number of shared symbols divided by total number of unique symbols between both. */ -export function jaccardSimilarity(a: string, b: string): number { +function jaccardSimilarity(a: string, b: string): number { const aSet = getSymbolsForSnippet(a); const bSet = getSymbolsForSnippet(b); const union = new Set([...aSet, ...bSet]).size; @@ -42,9 +39,9 @@ export function jaccardSimilarity(a: string, b: string): number { * Rank code snippets to be used in tab-autocomplete prompt. Returns a sorted version of the snippet array. */ export function rankAndOrderSnippets( - ranges: AutocompleteSnippet[], + ranges: AutocompleteSnippetDeprecated[], helper: HelperVars, -): Required[] { +): Required[] { const windowAroundCursor = helper.fullPrefix.slice( -helper.options.slidingWindowSize * @@ -55,11 +52,14 @@ export function rankAndOrderSnippets( (1 - helper.options.slidingWindowPrefixPercentage), ); - const snippets: Required[] = ranges.map((snippet) => ({ - score: - snippet.score ?? jaccardSimilarity(snippet.contents, windowAroundCursor), - ...snippet, - })); + const snippets: Required[] = ranges.map( + (snippet) => ({ + score: + snippet.score ?? + jaccardSimilarity(snippet.contents, windowAroundCursor), + ...snippet, + }), + ); const uniqueSnippets = deduplicateSnippets(snippets); return uniqueSnippets.sort((a, b) => a.score - b.score); } @@ -67,11 +67,13 @@ export function rankAndOrderSnippets( /** * Deduplicate code snippets by merging overlapping ranges into a single range. */ -export function deduplicateSnippets( - snippets: Required[], -): Required[] { +function deduplicateSnippets( + snippets: Required[], +): Required[] { // Group by file - const fileGroups: { [key: string]: Required[] } = {}; + const fileGroups: { + [key: string]: Required[]; + } = {}; for (const snippet of snippets) { if (!fileGroups[snippet.filepath]) { fileGroups[snippet.filepath] = []; @@ -88,8 +90,8 @@ export function deduplicateSnippets( } function mergeSnippetsByRange( - snippets: Required[], -): Required[] { + snippets: Required[], +): Required[] { if (snippets.length <= 1) { return snippets; } @@ -97,7 +99,7 @@ function mergeSnippetsByRange( const sorted = snippets.sort( (a, b) => a.range.start.line - b.range.start.line, ); - const merged: Required[] = []; + const merged: Required[] = []; while (sorted.length > 0) { const next = sorted.shift()!; @@ -133,12 +135,12 @@ function mergeOverlappingRangeContents( * It is assumed that the snippets are sorted by score. */ export function fillPromptWithSnippets( - snippets: Required[], + snippets: Required[], maxSnippetTokens: number, modelName: string, -): Required[] { +): Required[] { let tokensRemaining = maxSnippetTokens; - const keptSnippets: Required[] = []; + const keptSnippets: Required[] = []; for (let i = 0; i < snippets.length; i++) { const snippet = snippets[i]; const tokenCount = countTokens(snippet.contents, modelName); @@ -151,58 +153,3 @@ export function fillPromptWithSnippets( return keptSnippets; } - -/** - * Remove one range from another range, which may lead to returning two disjoint ranges - */ -function rangeDifferenceByLines(orig: Range, remove: Range): Range[] { - if ( - orig.start.line >= remove.start.line && - orig.end.line <= remove.end.line - ) { - // / | | / - return []; - } - if ( - orig.start.line <= remove.start.line && - orig.end.line >= remove.end.line - ) { - // | / / | - // Splits the range - return [ - { - start: orig.start, - end: remove.start, - }, - { - start: remove.end, - end: orig.end, - }, - ]; - } - if ( - orig.start.line >= remove.start.line && - orig.end.line >= remove.end.line - ) { - // \ | / | - return [ - { - start: remove.end, - end: orig.end, - }, - ]; - } - if ( - orig.start.line <= remove.start.line && - orig.end.line <= remove.end.line - ) { - // | / | / - return [ - { - start: orig.start, - end: remove.start, - }, - ]; - } - return [orig]; -} diff --git a/core/autocomplete/context/ranking/slidingWindow.ts b/core/autocomplete/context/ranking/slidingWindow.ts deleted file mode 100644 index 61c505c13..000000000 --- a/core/autocomplete/context/ranking/slidingWindow.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { RangeInFileWithContents } from "../../../"; - -import { AutocompleteSnippet, jaccardSimilarity } from "./"; - -function* slidingWindow( - content: string, - windowSize: number, -): Generator { - const lines = content.split("\n"); - - let charCount = 0; - let currWindowLines: string[] = []; - for (let i = 0; i < lines.length; i++) { - if (charCount + lines[i].length >= windowSize) { - yield currWindowLines.join("\n"); - currWindowLines = [lines[i]]; - charCount = 0; - } else { - currWindowLines.push(lines[i]); - } - charCount += lines[i].length; - } - - if (currWindowLines.length > 0) { - yield currWindowLines.join("\n"); - } -} - -/** - * Match by similarity over sliding windows of recent documents. - * @param recentFiles - * @param prefix - * @param suffix - */ -export async function slidingWindowMatcher( - recentFiles: RangeInFileWithContents[], - windowAroundCursor: string, - topN: number, - windowSize: number, -): Promise { - // Sorted lowest similarity to highest - const topMatches: Required[] = []; - - for (const { filepath, contents, range } of recentFiles) { - for (const window of slidingWindow(contents, windowSize)) { - const score = jaccardSimilarity(window, windowAroundCursor); - - // Insertion sort - let i = -1; - while (++i < topMatches.length && score > topMatches[i].score) {} - topMatches.splice(i + 1, 0, { filepath, contents, score, range }); - if (topMatches.length > topN) { - topMatches.shift(); - } - } - } - - // TODO: convert the arbitrary window frame to some whole AST node? - return topMatches; -} diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts index 0147df151..a94e37e38 100644 --- a/core/autocomplete/context/root-path-context/RootPathContextService.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.ts @@ -12,7 +12,11 @@ import { } from "../../../util/treeSitter"; import { AstPath } from "../../util/ast"; import { ImportDefinitionsService } from "../ImportDefinitionsService"; -import { AutocompleteSnippet } from "../ranking"; +import { AutocompleteSnippetDeprecated } from "../../types"; +import { + AutocompleteCodeSnippet, + AutocompleteSnippetType, +} from "../../snippets/types"; function getSyntaxTreeString( node: Parser.SyntaxNode, @@ -30,7 +34,7 @@ function getSyntaxTreeString( } export class RootPathContextService { - private cache = new LRUCache({ + private cache = new LRUCache({ max: 100, }); @@ -72,8 +76,8 @@ export class RootPathContextService { private async getSnippetsForNode( filepath: string, node: Parser.SyntaxNode, - ): Promise { - const snippets: AutocompleteSnippet[] = []; + ): Promise { + const snippets: AutocompleteSnippetDeprecated[] = []; const language = getFullLanguageName(filepath); let query: Parser.Query | undefined; @@ -123,7 +127,7 @@ export class RootPathContextService { filepath: string, endPosition: Parser.Point, language: LanguageName, - ): Promise { + ): Promise { const definitions = await this.ide.gotoDefinition({ filepath, position: { @@ -153,8 +157,8 @@ export class RootPathContextService { filepath: string, astPath: AstPath, // cursorIndex: number, - ): Promise { - const snippets: AutocompleteSnippet[] = []; + ): Promise { + const snippets: AutocompleteCodeSnippet[] = []; let parentKey = filepath; for (const astNode of astPath.filter((node) => @@ -167,7 +171,16 @@ export class RootPathContextService { const foundInCache = this.cache.get(key); const newSnippets = foundInCache ?? (await this.getSnippetsForNode(filepath, astNode)); - snippets.push(...newSnippets); + + const formattedSnippets: AutocompleteCodeSnippet[] = newSnippets.map( + (item) => ({ + filepath: item.filepath, + content: item.contents, + type: AutocompleteSnippetType.Code, + }), + ); + + snippets.push(...formattedSnippets); if (!foundInCache) { this.cache.set(key, newSnippets); diff --git a/core/autocomplete/filtering/test/testCases.ts b/core/autocomplete/filtering/test/testCases.ts index bde2afc08..5e708d910 100644 --- a/core/autocomplete/filtering/test/testCases.ts +++ b/core/autocomplete/filtering/test/testCases.ts @@ -1616,7 +1616,19 @@ interface User { age: number; }`, }, + { + description: "Should autocomplete TypeScript interface declarations", + filename: "autocomplete.ts", + input: `interface AutocompleteDiffSnippet extends BaseAutocompleteSnippet {} +interface AutocompleteCodeSnippet`, + llmOutput: ` extends BaseAutocompleteSnippet { + filepath: string; +}`, + expectedCompletion: ` extends BaseAutocompleteSnippet { + filepath: string; +}`, + }, { description: "Should autocomplete a TypeScript arrow function inside a variable assignment", diff --git a/core/autocomplete/filtering/test/util.ts b/core/autocomplete/filtering/test/util.ts index 8c8b8a9a2..8adaa101a 100644 --- a/core/autocomplete/filtering/test/util.ts +++ b/core/autocomplete/filtering/test/util.ts @@ -54,7 +54,6 @@ export async function testAutocompleteFiltering( const line = prefix.split("\n").length - 1; const character = prefix.split("\n")[line].length; const autocompleteInput: AutocompleteInput = { - clipboardText: "", completionId: "test-completion-id", filepath, pos: { diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts new file mode 100644 index 000000000..cf0b88253 --- /dev/null +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -0,0 +1,135 @@ +import { IDE } from "../../index"; +import { ContextRetrievalService } from "../context/ContextRetrievalService"; +import { GetLspDefinitionsFunction } from "../types"; +import { HelperVars } from "../util/HelperVars"; +import { + AutocompleteClipboardSnippet, + AutocompleteCodeSnippet, + AutocompleteDiffSnippet, + AutocompleteSnippetType, +} from "./types"; + +// Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems, +// or they might separately track recently edited ranges) +async function getIdeSnippets( + helper: HelperVars, + ide: IDE, + getDefinitionsFromLsp: GetLspDefinitionsFunction, +): Promise { + const ideSnippets = (await Promise.race([ + getDefinitionsFromLsp( + helper.input.filepath, + helper.fullPrefix + helper.fullSuffix, + helper.fullPrefix.length, + ide, + helper.lang, + ), + new Promise((resolve) => { + setTimeout(() => resolve([]), 100); + }), + ])) as AutocompleteCodeSnippet[]; + + if (helper.options.onlyMyCode) { + const workspaceDirs = await ide.getWorkspaceDirs(); + + return ideSnippets.filter((snippet) => + workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)), + ); + } + + return ideSnippets; +} + +function getSnippetsFromRecentlyEditedRanges( + helper: HelperVars, +): AutocompleteCodeSnippet[] { + if (helper.options.useRecentlyEdited === false) { + return []; + } + + return helper.input.recentlyEditedRanges.map((range) => { + return { + filepath: range.filepath, + content: range.lines.join("\n"), + type: AutocompleteSnippetType.Code, + }; + }); +} + +export interface SnippetPayload { + rootPathSnippets: AutocompleteCodeSnippet[]; + importDefinitionSnippets: AutocompleteCodeSnippet[]; + ideSnippets: AutocompleteCodeSnippet[]; + recentlyEditedRangeSnippets: AutocompleteCodeSnippet[]; + diffSnippets: AutocompleteDiffSnippet[]; + clipboardSnippets: AutocompleteClipboardSnippet[]; +} + +export type TEMP__Snippets = { + snippets: AutocompleteCodeSnippet[]; + diff: string | undefined; + clipboardContent: { + text: string; + copiedAt: string; + }; + payload: SnippetPayload; +}; + +export const getAllSnippets = async ({ + helper, + ide, + getDefinitionsFromLsp, + contextRetrievalService, +}: { + helper: HelperVars; + ide: IDE; + getDefinitionsFromLsp: GetLspDefinitionsFunction; + contextRetrievalService: ContextRetrievalService; +}): Promise => { + const recentlyEditedRangeSnippets = + getSnippetsFromRecentlyEditedRanges(helper); + + const [ + rootPathSnippets, + importDefinitionSnippets, + ideSnippets, + diff, + clipboardContent, + ] = await Promise.all([ + contextRetrievalService.getRootPathSnippets(helper), + contextRetrievalService.getSnippetsFromImportDefinitions(helper), + getIdeSnippets(helper, ide, getDefinitionsFromLsp), + ide.getDiff(true), + ide.getClipboardContent(), + ]); + + return { + snippets: [ + ...rootPathSnippets, + ...importDefinitionSnippets, + ...ideSnippets, + ...recentlyEditedRangeSnippets, + ], + diff, + clipboardContent, + payload: { + rootPathSnippets, + importDefinitionSnippets, + ideSnippets, + recentlyEditedRangeSnippets, + diffSnippets: [diff].map((item) => { + return { + content: item, + type: AutocompleteSnippetType.Diff, + }; + }), + clipboardSnippets: [clipboardContent].map((item) => { + return { + content: item.text, + copiedAt: item.copiedAt, + type: AutocompleteSnippetType.Clipboard, + }; + }), + }, + }; +}; diff --git a/core/autocomplete/snippets/index.ts b/core/autocomplete/snippets/index.ts new file mode 100644 index 000000000..2a9e1a7ce --- /dev/null +++ b/core/autocomplete/snippets/index.ts @@ -0,0 +1 @@ +export * from "./getAllSnippets"; diff --git a/core/autocomplete/snippets/types.ts b/core/autocomplete/snippets/types.ts new file mode 100644 index 000000000..e43b59862 --- /dev/null +++ b/core/autocomplete/snippets/types.ts @@ -0,0 +1,29 @@ +export enum AutocompleteSnippetType { + Code = "code", + Diff = "diff", + Clipboard = "clipboard", +} + +interface BaseAutocompleteSnippet { + content: string; + type: AutocompleteSnippetType; +} + +export interface AutocompleteCodeSnippet extends BaseAutocompleteSnippet { + filepath: string; + type: AutocompleteSnippetType.Code; +} + +export interface AutocompleteDiffSnippet extends BaseAutocompleteSnippet { + type: AutocompleteSnippetType.Diff; +} + +export interface AutocompleteClipboardSnippet extends BaseAutocompleteSnippet { + type: AutocompleteSnippetType.Clipboard; + copiedAt: string; +} + +export type AutocompleteSnippet = + | AutocompleteCodeSnippet + | AutocompleteDiffSnippet + | AutocompleteClipboardSnippet; diff --git a/core/autocomplete/templating/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts index c64eca26a..3baed912b 100644 --- a/core/autocomplete/templating/AutocompleteTemplate.ts +++ b/core/autocomplete/templating/AutocompleteTemplate.ts @@ -2,7 +2,8 @@ import { CompletionOptions } from "../../index.js"; import { getLastNPathParts, shortestRelativePaths } from "../../util/index.js"; -import { AutocompleteSnippet } from "../context/ranking/index.js"; +import { AutocompleteCodeSnippet } from "../snippets/types.js"; +import { AutocompleteSnippetDeprecated } from "../types.js"; export interface AutocompleteTemplate { compilePrefixSuffix?: ( @@ -10,7 +11,7 @@ export interface AutocompleteTemplate { suffix: string, filepath: string, reponame: string, - snippets: AutocompleteSnippet[], + snippets: AutocompleteCodeSnippet[], ) => [string, string]; template: | string @@ -20,7 +21,7 @@ export interface AutocompleteTemplate { filepath: string, reponame: string, language: string, - snippets: AutocompleteSnippet[], + snippets: AutocompleteCodeSnippet[], ) => string); completionOptions?: Partial; } @@ -73,7 +74,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { suffix: string, filepath: string, reponame: string, - snippets: AutocompleteSnippet[], + snippets: AutocompleteCodeSnippet[], ): [string, string] => { if (snippets.length === 0) { if (suffix.trim().length === 0 && prefix.trim().length === 0) { @@ -86,7 +87,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { filepath, ]); const otherFiles = snippets - .map((snippet, i) => `+++++ ${relativePaths[i]}\n${snippet.contents}`) + .map((snippet, i) => `+++++ ${relativePaths[i]}\n${snippet.content}`) .join("\n\n"); return [ `${otherFiles}\n\n+++++ ${ @@ -101,7 +102,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { filepath: string, reponame: string, language: string, - snippets: AutocompleteSnippet[], + snippets: AutocompleteCodeSnippet[], ): string => { return `[SUFFIX]${suffix}[PREFIX]${prefix}`; }, @@ -133,15 +134,14 @@ const starcoder2FimTemplate: AutocompleteTemplate = { filename: string, reponame: string, language: string, - snippets: AutocompleteSnippet[], + snippets: AutocompleteCodeSnippet[], ): string => { const otherFiles = snippets.length === 0 ? "" : `${snippets .map((snippet) => { - return snippet.contents; - // return `${getBasename(snippet.filepath)}\n${snippet.contents}`; + return snippet.content; }) .join("")}`; @@ -187,7 +187,7 @@ const codegeexFimTemplate: AutocompleteTemplate = { filepath: string, reponame: string, language: string, - snippets: AutocompleteSnippet[], + snippets: AutocompleteCodeSnippet[], ): string => { const relativePaths = shortestRelativePaths([ ...snippets.map((snippet) => snippet.filepath), @@ -200,7 +200,7 @@ const codegeexFimTemplate: AutocompleteTemplate = { return `<|user|>\n${baseTemplate}<|assistant|>\n`; } const references = `###REFERENCE:\n${snippets - .map((snippet, i) => `###PATH:${relativePaths[i]}\n${snippet.contents}\n`) + .map((snippet, i) => `###PATH:${relativePaths[i]}\n${snippet.content}\n`) .join("###REFERENCE:\n")}`; const prompt = `<|user|>\n${references}\n${baseTemplate}<|assistant|>\n`; return prompt; @@ -233,7 +233,7 @@ const holeFillerTemplate: AutocompleteTemplate = { filename: string, reponame: string, language: string, - snippets: AutocompleteSnippet[], + snippets: AutocompleteCodeSnippet[], ) => { // From https://github.com/VictorTaelin/AI-scripts const SYSTEM_MSG = `You are a HOLE FILLER. You are provided with a file containing holes, formatted as '{{HOLE_NAME}}'. Your TASK is to complete with a string to replace this hole with, inside a XML tag, including context-aware indentation, if needed. All completions MUST be truthful, accurate, well-written and correct. diff --git a/core/autocomplete/templating/filtering.ts b/core/autocomplete/templating/filtering.ts new file mode 100644 index 000000000..bc85fb909 --- /dev/null +++ b/core/autocomplete/templating/filtering.ts @@ -0,0 +1,75 @@ +import { countTokens } from "../../llm/countTokens"; +import { SnippetPayload } from "../snippets"; +import { + AutocompleteCodeSnippet, + AutocompleteSnippet, +} from "../snippets/types"; +import { HelperVars } from "../util/HelperVars"; +import { isValidSnippet } from "./validation"; + +const getRemainingTokenCount = (helper: HelperVars): number => { + const tokenCount = countTokens(helper.prunedCaretWindow, helper.modelName); + + return helper.options.maxPromptTokens - tokenCount; +}; + +const TOKEN_BUFFER = 10; // We may need extra tokens for snippet description etc. + +/** + * Shuffles an array in place using the Fisher-Yates algorithm. + * @param array The array to shuffle. + * @returns The shuffled array. + */ +const shuffleArray = (array: T[]): T[] => { + for (let i = array.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [array[i], array[j]] = [array[j], array[i]]; + } + return array; +}; + +function filterSnippetsAlreadyInCaretWindow( + snippets: AutocompleteCodeSnippet[], + caretWindow: string, +): AutocompleteCodeSnippet[] { + return snippets.filter( + (s) => s.content.trim() !== "" && !caretWindow.includes(s.content.trim()), + ); +} + +export const getSnippets = ( + helper: HelperVars, + payload: SnippetPayload, +): AutocompleteSnippet[] => { + const snippets = [ + ...payload.diffSnippets, + ...payload.clipboardSnippets, + ...shuffleArray( + filterSnippetsAlreadyInCaretWindow( + [...payload.rootPathSnippets], + helper.prunedCaretWindow, + ), + ), + ]; + + const finalSnippets = []; + + let remainingTokenCount = getRemainingTokenCount(helper); + + while (remainingTokenCount > 0 && snippets.length > 0) { + const snippet = snippets.shift(); + if (!snippet || !isValidSnippet(snippet)) { + continue; + } + + const snippetSize = + countTokens(snippet.content, helper.modelName) + TOKEN_BUFFER; + + if (remainingTokenCount >= snippetSize) { + finalSnippets.push(snippet); + remainingTokenCount -= snippetSize; + } + } + + return finalSnippets; +}; diff --git a/core/autocomplete/templating/formatting.ts b/core/autocomplete/templating/formatting.ts new file mode 100644 index 000000000..6554de26d --- /dev/null +++ b/core/autocomplete/templating/formatting.ts @@ -0,0 +1,107 @@ +import { getLastNPathParts } from "../../util"; +import { + AutocompleteClipboardSnippet, + AutocompleteCodeSnippet, + AutocompleteDiffSnippet, + AutocompleteSnippet, + AutocompleteSnippetType, +} from "../snippets/types"; +import { HelperVars } from "../util/HelperVars"; + +const getCommentMark = (helper: HelperVars) => { + return helper.lang.singleLineComment; +}; + +const addCommentMarks = (text: string, helper: HelperVars) => { + const lines = [ + ...text + .trim() + .split("\n") + .map((line) => `${getCommentMark(helper)} ${line}`), + ]; + return lines.join("\n"); +}; + +const formatClipboardSnippet = ( + snippet: AutocompleteClipboardSnippet, +): AutocompleteCodeSnippet => { + return formatCodeSnippet({ + filepath: "Untitled.txt", + content: snippet.content, + type: AutocompleteSnippetType.Code, + }); +}; + +const formatCodeSnippet = ( + snippet: AutocompleteCodeSnippet, +): AutocompleteCodeSnippet => { + return { + ...snippet, + content: `Path: ${getLastNPathParts(snippet.filepath, 2)}\n${snippet.content}`, + }; +}; + +const formatDiffSnippet = ( + snippet: AutocompleteDiffSnippet, +): AutocompleteDiffSnippet => { + return snippet; +}; + +const getCurrentFilepath = (helper: HelperVars) => { + return getLastNPathParts(helper.filepath, 2); +}; + +const commentifySnippet = ( + helper: HelperVars, + snippet: AutocompleteSnippet, +): AutocompleteSnippet => { + return { + ...snippet, + content: addCommentMarks(snippet.content, helper), + }; +}; + +const SNIPPET_TYPES_TO_COMMENT = [ + AutocompleteSnippetType.Code, + AutocompleteSnippetType.Clipboard, +]; + +export const formatSnippets = ( + helper: HelperVars, + snippets: AutocompleteSnippet[], +): string => { + const currentFilepathComment = addCommentMarks( + getCurrentFilepath(helper), + helper, + ); + + return ( + snippets + .map((snippet) => { + switch (snippet.type) { + case AutocompleteSnippetType.Code: + return formatCodeSnippet(snippet); + case AutocompleteSnippetType.Diff: + return formatDiffSnippet(snippet); + case AutocompleteSnippetType.Clipboard: + return formatClipboardSnippet(snippet); + } + }) + .map((item) => { + if (SNIPPET_TYPES_TO_COMMENT.includes(item.type)) { + return commentifySnippet(helper, item); + } + + return item; + }) + .map((item) => { + if (SNIPPET_TYPES_TO_COMMENT.includes(item.type)) { + const commentMark = getCommentMark(helper); + return item.content + `\n${commentMark}\n${commentMark}`; + } + + return item.content + "\n\n"; + }) + .join("\n") + `\n${currentFilepathComment}` + ); +}; diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 6f95923d1..364c9114c 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -1,9 +1,8 @@ import Handlebars from "handlebars"; import { CompletionOptions } from "../.."; -import { getBasename, getLastNPathParts } from "../../util"; +import { getBasename } from "../../util"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; -import { AutocompleteSnippet } from "../context/ranking"; import { HelperVars } from "../util/HelperVars"; import { @@ -11,51 +10,10 @@ import { getTemplateForModel, } from "./AutocompleteTemplate"; import { getStopTokens } from "./getStopTokens"; -import { countTokens } from "../../llm/countTokens"; - -const addCommentMarks = (text: string, language: AutocompleteLanguageInfo) => { - const comment = language.singleLineComment; - const lines = [ - ...text - .trim() - .split("\n") - .map((line) => `${comment} ${line}`), - ]; - return lines.join("\n"); -}; - -export function formatExternalSnippet( - filepath: string, - snippet: string, - language: AutocompleteLanguageInfo, -) { - const filePathString = `Path: ${getBasename(filepath)}\n`; - return addCommentMarks(`${filePathString}${snippet}`, language); -} - -function getContextComments( - snippets: AutocompleteSnippet[], - lang: AutocompleteLanguageInfo, - filepath: string, -) { - if (snippets.length === 0) { - return ""; - } - - const headerSnipper = `\n\n${lang.singleLineComment} Related code:\n`; - const fileNameSnippet = `\n\n${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n\n`; - - const formattedSnippets = - headerSnipper + - snippets - .map((snippet) => - formatExternalSnippet(snippet.filepath, snippet.contents, lang), - ) - .join("\n") + - fileNameSnippet; - - return formattedSnippets; -} +import { AutocompleteCodeSnippet } from "../snippets/types"; +import { SnippetPayload } from "../snippets"; +import { formatSnippets } from "./formatting"; +import { getSnippets } from "./filtering"; function getTemplate(helper: HelperVars): AutocompleteTemplate { if (helper.options.template) { @@ -88,56 +46,14 @@ function renderStringTemplate( }); } -const formatDiff = (helper: HelperVars, diff?: string) => { - if (!diff) return ""; - - const tokenCount = countTokens(diff, helper.modelName); - - if (tokenCount > helper.maxDiffTokens) { - return ""; - } - - return `${diff}\n\n`; -}; - -const MAX_CLIPBOARD_AGE = 5 * 60 * 1000; - -const formatClipboardContent = ( - helper: HelperVars, - { text, copiedAt }: { text: string; copiedAt: string }, -) => { - const currDate = new Date(); - - const isTooOld = - currDate.getTime() - new Date(copiedAt).getTime() > MAX_CLIPBOARD_AGE; - - if (isTooOld) { - return ""; - } - - const tokenCount = countTokens(text, helper.modelName); - const isTooLong = tokenCount > helper.maxClipboardTokens; - - if (isTooLong) { - return ""; - } - - return ( - addCommentMarks( - `Recently copied by user:${text.includes("\n") ? "\n" : ""} ${text}`, - helper.lang, - ) + "\n" - ); -}; - export function renderPrompt({ snippets, + snippetPayload, workspaceDirs, helper, - diff, - clipboardContent, }: { - snippets: AutocompleteSnippet[]; + snippets: AutocompleteCodeSnippet[]; + snippetPayload: SnippetPayload; workspaceDirs: string[]; helper: HelperVars; diff?: string; @@ -171,17 +87,10 @@ export function renderPrompt({ snippets, ); } else { - const contextComments = getContextComments( - snippets, - helper.lang, - helper.filepath, - ); - const formattedDiff = formatDiff(helper, diff); - const formattedClipboard = formatClipboardContent(helper, clipboardContent); + const finalSnippets = getSnippets(helper, snippetPayload); + const formattedSnippets = formatSnippets(helper, finalSnippets); - prefix = [formattedClipboard, formattedDiff, contextComments, prefix].join( - "", - ); + prefix = [formattedSnippets, prefix].join("\n"); } const prompt = diff --git a/core/autocomplete/templating/validation.ts b/core/autocomplete/templating/validation.ts new file mode 100644 index 000000000..dad55dc5c --- /dev/null +++ b/core/autocomplete/templating/validation.ts @@ -0,0 +1,29 @@ +import { + AutocompleteClipboardSnippet, + AutocompleteSnippet, + AutocompleteSnippetType, +} from "../snippets/types"; + +const MAX_CLIPBOARD_AGE = 5 * 60 * 1000; + +const isValidClipboardSnippet = ( + snippet: AutocompleteClipboardSnippet, +): boolean => { + const currDate = new Date(); + + const isTooOld = + currDate.getTime() - new Date(snippet.copiedAt).getTime() > + MAX_CLIPBOARD_AGE; + + return !isTooOld; +}; + +export const isValidSnippet = (snippet: AutocompleteSnippet): boolean => { + if (snippet.content.trim() === "") return false; + + if (snippet.type === AutocompleteSnippetType.Clipboard) { + return isValidClipboardSnippet(snippet); + } + + return true; +}; diff --git a/core/autocomplete/types.ts b/core/autocomplete/types.ts new file mode 100644 index 000000000..23f762556 --- /dev/null +++ b/core/autocomplete/types.ts @@ -0,0 +1,20 @@ +import { IDE, RangeInFileWithContents } from "../index"; +import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo"; +import { AutocompleteCodeSnippet } from "./snippets/types"; + +/** + * @deprecated This type should be removed in the future or renamed. + * We have a new interface called AutocompleteSnippet which is more + * general. + */ +export type AutocompleteSnippetDeprecated = RangeInFileWithContents & { + score?: number; +}; + +export type GetLspDefinitionsFunction = ( + filepath: string, + contents: string, + cursorIndex: number, + ide: IDE, + lang: AutocompleteLanguageInfo, +) => Promise; diff --git a/core/autocomplete/util/AutocompleteLoggingService.ts b/core/autocomplete/util/AutocompleteLoggingService.ts index 96261e646..35e0ead64 100644 --- a/core/autocomplete/util/AutocompleteLoggingService.ts +++ b/core/autocomplete/util/AutocompleteLoggingService.ts @@ -112,7 +112,6 @@ export class AutocompleteLoggingService { multilineCompletions: restOfOutcome.multilineCompletions, time: restOfOutcome.time, useRecentlyEdited: restOfOutcome.useRecentlyEdited, - useRootPathContext: restOfOutcome.useRootPathContext, }, true, ); diff --git a/core/autocomplete/util/HelperVars.ts b/core/autocomplete/util/HelperVars.ts index c5429fe81..047038493 100644 --- a/core/autocomplete/util/HelperVars.ts +++ b/core/autocomplete/util/HelperVars.ts @@ -114,17 +114,6 @@ export class HelperVars { get pos() { return this.input.pos; } - get maxSnippetTokens() { - return this.options.maxPromptTokens * this.options.maxSnippetPercentage; - } - - get maxDiffTokens() { - return this.options.maxPromptTokens * this.options.maxDiffPercentage; - } - - get maxClipboardTokens() { - return this.options.maxPromptTokens * this.options.maxClipboardPercentage; - } get prunedCaretWindow() { return this.prunedPrefix + this.prunedSuffix; diff --git a/core/autocomplete/util/types.ts b/core/autocomplete/util/types.ts index 8d531d026..d54d57bd2 100644 --- a/core/autocomplete/util/types.ts +++ b/core/autocomplete/util/types.ts @@ -18,7 +18,6 @@ export interface AutocompleteInput { pos: Position; recentlyEditedFiles: RangeInFileWithContents[]; recentlyEditedRanges: RecentlyEditedRange[]; - clipboardText: string; // Used for notebook files manuallyPassFileContents?: string; // Used for VS Code git commit input box diff --git a/core/config/types.ts b/core/config/types.ts index f397b1ed7..bb6c8f48c 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -825,7 +825,6 @@ declare global { export interface TabAutocompleteOptions { disable: boolean; - useCopyBuffer: boolean; useFileSuffix: boolean; maxPromptTokens: number; debounceDelay: number; @@ -835,14 +834,9 @@ declare global { multilineCompletions: "always" | "never" | "auto"; slidingWindowPrefixPercentage: number; slidingWindowSize: number; - maxSnippetPercentage: number; - maxDiffPercentage: number; - maxClipboardPercentage: number; useCache: boolean; onlyMyCode: boolean; - useOtherFiles: boolean; useRecentlyEdited: boolean; - recentLinePrefixMatchMinLength: number; disableInFiles?: string[]; useImports?: boolean; } diff --git a/core/index.d.ts b/core/index.d.ts index a71e69425..55c1e8ac7 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -968,7 +968,6 @@ export interface Reranker { export interface TabAutocompleteOptions { disable: boolean; - useCopyBuffer: boolean; useFileSuffix: boolean; maxPromptTokens: number; debounceDelay: number; @@ -979,17 +978,11 @@ export interface TabAutocompleteOptions { multilineCompletions: "always" | "never" | "auto"; slidingWindowPrefixPercentage: number; slidingWindowSize: number; - maxSnippetPercentage: number; - maxDiffPercentage: number; - maxClipboardPercentage: number; useCache: boolean; onlyMyCode: boolean; - useOtherFiles: boolean; useRecentlyEdited: boolean; - recentLinePrefixMatchMinLength: number; disableInFiles?: string[]; useImports?: boolean; - useRootPathContext?: boolean; showWhateverWeHaveAtXMs?: number; } diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 20b96ac47..24e94781c 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -2,7 +2,6 @@ import { TabAutocompleteOptions } from "../index.js"; export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { disable: false, - useCopyBuffer: false, useFileSuffix: true, maxPromptTokens: 1024, prefixPercentage: 0.85, @@ -11,17 +10,11 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { multilineCompletions: "auto", slidingWindowPrefixPercentage: 0.75, slidingWindowSize: 500, - maxSnippetPercentage: 0.5, - maxDiffPercentage: 0.5, - maxClipboardPercentage: 0.5, // yes the percentages do not add up useCache: true, onlyMyCode: true, - useOtherFiles: true, useRecentlyEdited: true, - recentLinePrefixMatchMinLength: 7, disableInFiles: undefined, useImports: true, - useRootPathContext: true, transform: true, showWhateverWeHaveAtXMs: 300, }; diff --git a/docs/docs/autocomplete/how-to-customize.md b/docs/docs/autocomplete/how-to-customize.md index dcf6ba234..ccd1dca9d 100644 --- a/docs/docs/autocomplete/how-to-customize.md +++ b/docs/docs/autocomplete/how-to-customize.md @@ -9,14 +9,12 @@ Continue offers a handful of parameters in [`config.json`](../reference.md) that ```json title="config.json" "tabAutocompleteOptions": { - "useCopyBuffer": false, "maxPromptTokens": 400, "prefixPercentage": 0.5, "multilineCompletions": "always" } ``` -- `useCopyBuffer`: Determines if the clipboard content should be considered in prompt construction. - `maxPromptTokens`: Sets the maximum number of tokens for the prompt, balancing context and speed. - `prefixPercentage`: Defines the proportion of the prompt dedicated to the code before the cursor. - `multilineCompletions`: Controls whether suggestions can span multiple lines ("always", "never", or "auto"). diff --git a/docs/docs/customize/deep-dives/autocomplete.md b/docs/docs/customize/deep-dives/autocomplete.md index 9e03aa756..35789710c 100644 --- a/docs/docs/customize/deep-dives/autocomplete.md +++ b/docs/docs/customize/deep-dives/autocomplete.md @@ -60,7 +60,6 @@ This object allows you to customize the behavior of tab-autocomplete. The availa - `disable`: Disable autocomplete (can also be done from IDE settings) - `template`: An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables. (String) -- `useCopyBuffer`: Determines whether the copy buffer will be considered when constructing the prompt. (Boolean) - `useFileSuffix`: Determines whether to use the file suffix in the prompt. (Boolean) - `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number) - `prefixPercentage`: The percentage of the input that should be dedicated to the prefix. (Number) @@ -68,7 +67,6 @@ This object allows you to customize the behavior of tab-autocomplete. The availa - `debounceDelay`: The delay in milliseconds before triggering autocomplete after a keystroke. (Number) - `multilineCompletions`: Whether to enable multiline completions ("always", "never", or "auto"). Defaults to "auto". - `useCache`: Whether to cache and reuse completions when the prompt is the same as a previous one. May be useful to disable for testing purposes. -- `useOtherFiles`: Whether to include context from files outside of the current one. Turning this off should be expected to reduce the accuracy of completions, but might be good for testing. - `disableInFiles`: A list of glob patterns for files in which you want to disable tab autocomplete. ### Full example diff --git a/docs/docs/reference.md b/docs/docs/reference.md index f39e68998..5fc3218df 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -83,7 +83,6 @@ Specifies options for tab autocompletion behavior. **Properties:** - `disable`: If `true`, disables tab autocomplete (default: `false`). -- `useCopyBuffer`: If `true`, includes the copy buffer in the prompt. - `useFileSuffix`: If `true`, includes file suffix in the prompt. - `maxPromptTokens`: Maximum number of tokens for the prompt. - `debounceDelay`: Delay (in ms) before triggering autocomplete. @@ -93,7 +92,6 @@ Specifies options for tab autocompletion behavior. - `multilineCompletions`: Controls multiline completions (`"always"`, `"never"`, or `"auto"`). - `useCache`: If `true`, caches completions. - `onlyMyCode`: If `true`, only includes code within the repository. -- `useOtherFiles`: If `true`, includes snippets from other files (default: `true`). - `disableInFiles`: Array of glob patterns for files where autocomplete is disabled. Example diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md index aa2a04d5f..143645591 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md @@ -9,14 +9,12 @@ Continue 在 [`config.json`](../reference.md) 提供少量的参数,对于你 ```json title="config.json" "tabAutocompleteOptions": { - "useCopyBuffer": false, "maxPromptTokens": 400, "prefixPercentage": 0.5, "multilineCompletions": "always" } ``` -- `useCopyBuffer`: 决定剪贴板的内容是否包含在提示词构建中 - `maxPromptTokens`: 设置提示词的最大 token 数,平衡上下文和速度 - `prefixPercentage`: 决定提示词使用光标前代码的比例 - `multilineCompletions`: 控制建议是否可以跨多行 ("always", "never" 或 "auto") diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md index b85cfe323..15cb94c4d 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md @@ -60,7 +60,6 @@ ollama run starcoder2:3b - `disable`: 禁用自动补全(也可以在 IDE 配置中完成) - `template`: 一个用来自动补全的可选的模板字符串。它使用 Mustache 模板语言渲染,并且传递 'prefix' 和 'suffix' 变量。(字符串) -- `useCopyBuffer`: 决定 copy buffer 是否考虑为构建提示词。(布尔型) - `useFileSuffix`: 决定是否使用文件后缀在提示词中。(布尔型) - `maxPromptTokens`: 提示词使用的 token 的最大数量。一个较小的数字生成较快的补全,但是较少的上下文。(数字) - `prefixPercentage`: 输入专注于前缀的百分比。(数字) @@ -69,7 +68,6 @@ ollama run starcoder2:3b - `debounceDelay`: 在按键之后触发自动补全的毫秒延迟。(数字) - `multilineCompletions`: 是否启用多行补全 ("always", "never" 或 "auto") 。默认情况下是 "auto" 。 - `useCache`: 是否缓存和重新使用补全,当提示词与前一个相同时。对于测试的目的可能是有用的。 -- `useOtherFiles`: 是否包含当前文件之外的文件的上下文。关闭这个预期会减少补全的准确性,但是对于测试可能是有用的。 - `disableInFiles`: 一个你想要禁用 tab 自动补全的 glob 模式的文件列表。 ### 完整示例 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md index 09dd150a6..a224cf8a8 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md @@ -83,7 +83,6 @@ Specifies options for tab autocompletion behavior. **Properties:** - `disable`: If `true`, disables tab autocomplete (default: `false`). -- `useCopyBuffer`: If `true`, includes the copy buffer in the prompt. - `useFileSuffix`: If `true`, includes file suffix in the prompt. - `maxPromptTokens`: Maximum number of tokens for the prompt. - `debounceDelay`: Delay (in ms) before triggering autocomplete. @@ -93,7 +92,6 @@ Specifies options for tab autocompletion behavior. - `multilineCompletions`: Controls multiline completions (`"always"`, `"never"`, or `"auto"`). - `useCache`: If `true`, caches completions. - `onlyMyCode`: If `true`, only includes code within the repository. -- `useOtherFiles`: If `true`, includes snippets from other files (default: `true`). - `disableInFiles`: Array of glob patterns for files where autocomplete is disabled. Example diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 7edceced4..3a274c8b0 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -2791,10 +2791,6 @@ "description": "Disable tab autocomplete. This can also be done from the IDE settings.", "default": false }, - "useCopyBuffer": { - "type": "boolean", - "description": "Determines whether the copy buffer will be considered when contructing the prompt." - }, "useFileSuffix": { "type": "boolean", "description": "Determines whether to use the file suffix in the prompt." @@ -2835,10 +2831,6 @@ "type": "boolean", "description": "If set to true, Continue will not include any snippets from go to definition unless they are within your repository" }, - "useOtherFiles": { - "type": "boolean", - "description": "Defaults to true. If set to false, Continue will not attempt to include snippets from other files." - }, "disableInFiles": { "description": "A list of files / glob patterns in which to disable tab autocomplete. For example, *.csv if you'd like to disable autocomplete in .csv files.", "type": "array", diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 0df8e58b1..ffe69a2c4 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -42,7 +42,7 @@ export class ContinueCompletionProvider e.message, this.configHandler.reloadConfig.bind(this.configHandler), () => { - void this.webviewProtocol.request("openOnboardingCard", undefined) + void this.webviewProtocol.request("openOnboardingCard", undefined); }, ); return; @@ -153,12 +153,6 @@ export class ContinueCompletionProvider const signal = abortController.signal; token.onCancellationRequested(() => abortController.abort()); - const config = await this.configHandler.loadConfig(); - let clipboardText = ""; - if (config.tabAutocompleteOptions?.useCopyBuffer === true) { - clipboardText = await vscode.env.clipboard.readText(); - } - // Handle notebook cells const pos = { line: position.line, @@ -194,12 +188,6 @@ export class ContinueCompletionProvider } // Handle commit message input box let manuallyPassPrefix: string | undefined = undefined; - if (document.uri.scheme === "vscode-scm") { - return null; - // let diff = await this.ide.getDiff(); - // diff = diff.split("\n").splice(-150).join("\n"); - // manuallyPassPrefix = `${diff}\n\nCommit message: `; - } const input: AutocompleteInput = { completionId: uuidv4(), @@ -208,7 +196,6 @@ export class ContinueCompletionProvider recentlyEditedFiles: [], recentlyEditedRanges: await this.recentlyEditedTracker.getRecentlyEditedRanges(), - clipboardText: clipboardText, manuallyPassFileContents, manuallyPassPrefix, selectedCompletionInfo, diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index 90b034a2e..08b16ace7 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -1,6 +1,4 @@ -import { GetLspDefinitionsFunction } from "core/autocomplete/CompletionProvider"; import { AutocompleteLanguageInfo } from "core/autocomplete/constants/AutocompleteLanguageInfo"; -import { AutocompleteSnippet } from "core/autocomplete/context/ranking"; import { getAst, getTreePathAtCursor } from "core/autocomplete/util/ast"; import { FUNCTION_BLOCK_NODE_TYPES, @@ -11,6 +9,14 @@ import * as vscode from "vscode"; import type { IDE, Range, RangeInFile, RangeInFileWithContents } from "core"; import type Parser from "web-tree-sitter"; +import { + AutocompleteSnippetDeprecated, + GetLspDefinitionsFunction, +} from "core/autocomplete/types"; +import { + AutocompleteCodeSnippet, + AutocompleteSnippetType, +} from "core/autocomplete/snippets/types"; type GotoProviderName = | "vscode.executeDefinitionProvider" @@ -341,7 +347,7 @@ export const getDefinitionsFromLsp: GetLspDefinitionsFunction = async ( cursorIndex: number, ide: IDE, lang: AutocompleteLanguageInfo, -): Promise => { +): Promise => { try { const ast = await getAst(filepath, contents); if (!ast) { @@ -365,8 +371,9 @@ export const getDefinitionsFromLsp: GetLspDefinitionsFunction = async ( } return results.map((result) => ({ - ...result, - score: 0.8, + filepath: result.filepath, + content: result.contents, + type: AutocompleteSnippetType.Code, })); } catch (e) { console.warn("Error getting definitions from LSP: ", e); diff --git a/packages/config-types/src/index.ts b/packages/config-types/src/index.ts index 876115d11..2170a116b 100644 --- a/packages/config-types/src/index.ts +++ b/packages/config-types/src/index.ts @@ -130,7 +130,6 @@ export type UiOptions = z.infer; export const tabAutocompleteOptionsSchema = z.object({ disable: z.boolean(), - useCopyBuffer: z.boolean(), useFileSuffix: z.boolean(), maxPromptTokens: z.number(), debounceDelay: z.number(), @@ -141,14 +140,9 @@ export const tabAutocompleteOptionsSchema = z.object({ multilineCompletions: z.enum(["always", "never", "auto"]), slidingWindowPrefixPercentage: z.number(), slidingWindowSize: z.number(), - maxSnippetPercentage: z.number(), - maxDiffPercentage: z.number(), - maxClipboardPercentage: z.number(), useCache: z.boolean(), onlyMyCode: z.boolean(), - useOtherFiles: z.boolean(), useRecentlyEdited: z.boolean(), - recentLinePrefixMatchMinLength: z.number(), disableInFiles: z.array(z.string()).optional(), useImports: z.boolean().optional(), });