From 8a92f4312693549a1590e99c70152b843d59b119 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 21 Jun 2024 15:58:04 -0500 Subject: [PATCH 1/2] fix(gui): ctx rendering w/ renderInlineAs: "" (#1541) --- extensions/vscode/CONTRIBUTING.md | 4 ++-- gui/src/components/mainInput/resolveInput.ts | 15 ++++++++++++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/extensions/vscode/CONTRIBUTING.md b/extensions/vscode/CONTRIBUTING.md index ddeca6bcb..5cfbf3cb1 100644 --- a/extensions/vscode/CONTRIBUTING.md +++ b/extensions/vscode/CONTRIBUTING.md @@ -7,11 +7,11 @@ This is the Continue VS Code Extension. Its primary jobs are # How to run the extension -See [Environment Setup](../CONTRIBUTING.md#environment-setup) +See [Environment Setup](../../CONTRIBUTING.md#environment-setup) # How to run and debug tests -After following the setup in [Environment Setup](../CONTRIBUTING.md#environment-setup) you can run the `Extension (VSCode)` launch configuration in VS Code. +After following the setup in [Environment Setup](../../CONTRIBUTING.md#environment-setup) you can run the `Extension (VSCode)` launch configuration in VS Code. ## Notes diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index bb628f4ce..cabe66bd3 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -42,6 +42,9 @@ async function resolveEditorContent( if (foundSlashCommand && typeof slashCommand === "undefined") { slashCommand = foundSlashCommand; } + + contextItemAttrs.push(...ctxItems); + if (text === "") { continue; } @@ -51,11 +54,14 @@ async function resolveEditorContent( } else { parts.push({ type: "text", text }); } - contextItemAttrs.push(...ctxItems); } else if (p.type === "codeBlock") { if (!p.attrs.item.editing) { const text = - "```" + p.attrs.item.description + "\n" + p.attrs.item.content + "\n```"; + "```" + + p.attrs.item.description + + "\n" + + p.attrs.item.content + + "\n```"; if (parts[parts.length - 1]?.type === "text") { parts[parts.length - 1].text += "\n" + text; } else { @@ -96,7 +102,10 @@ async function resolveEditorContent( if (item.itemType === "file") { // This is a quick way to resolve @file references const basename = getBasename(item.id); - const relativeFilePath = getRelativePath(item.id, await ideMessenger.ide.getWorkspaceDirs()); + const relativeFilePath = getRelativePath( + item.id, + await ideMessenger.ide.getWorkspaceDirs(), + ); const rawContent = await ideMessenger.ide.readFile(item.id); const content = `\`\`\`${relativeFilePath}\n${rawContent}\n\`\`\`\n`; contextItemsText += content; From 851e825af63e8605894aa16a1a717fb052e6b82b Mon Sep 17 00:00:00 2001 From: Nate Sesti <33237525+sestinj@users.noreply.github.com> Date: Fri, 21 Jun 2024 14:02:29 -0700 Subject: [PATCH 2/2] =?UTF-8?q?=E2=9C=A8=20use=20and=20cache=20imports=20f?= =?UTF-8?q?or=20autocomplete=20(#1456)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ✨ use and cache imports for autocomplete * fix tsc --- binary/src/IpcIde.ts | 2 +- core/autocomplete/ImportDefinitionsService.ts | 81 +++ core/autocomplete/NearbyDefinitionsService.ts | 45 ++ core/autocomplete/completionProvider.ts | 688 +++++++++--------- core/autocomplete/constructPrompt.ts | 26 + core/index.d.ts | 12 + core/indexing/CodeSnippetsIndex.ts | 27 +- core/protocol/ide.ts | 4 + core/protocol/index.ts | 5 +- core/util/LruCache.ts | 30 + core/util/filesystem.ts | 9 + core/util/messageIde.ts | 14 + core/util/parameters.ts | 1 + core/util/treeSitter.ts | 34 +- extensions/vscode/scripts/prepackage.js | 2 +- extensions/vscode/src/autocomplete/lsp.ts | 4 +- extensions/vscode/src/ideProtocol.ts | 22 + .../{tree-sitter-c-tags.scm => c.scm} | 0 ...ee-sitter-c_sharp-tags.scm => c_sharp.scm} | 0 .../{tree-sitter-cpp-tags.scm => cpp.scm} | 0 .../{tree-sitter-elisp-tags.scm => elisp.scm} | 0 ...tree-sitter-elixir-tags.scm => elixir.scm} | 0 .../{tree-sitter-go-tags.scm => go.scm} | 0 .../{tree-sitter-java-tags.scm => java.scm} | 0 ...ter-javascript-tags.scm => javascript.scm} | 0 .../{tree-sitter-ocaml-tags.scm => ocaml.scm} | 0 .../{tree-sitter-php-tags.scm => php.scm} | 0 ...tree-sitter-python-tags.scm => python.scm} | 0 .../{tree-sitter-ql-tags.scm => ql.scm} | 0 .../{tree-sitter-ruby-tags.scm => ruby.scm} | 0 .../{tree-sitter-rust-tags.scm => rust.scm} | 0 ...ter-typescript-tags.scm => typescript.scm} | 0 .../tree-sitter/import-queries/typescript.scm | 9 + gui/src/context/IdeMessenger.ts | 2 +- 34 files changed, 639 insertions(+), 378 deletions(-) create mode 100644 core/autocomplete/ImportDefinitionsService.ts create mode 100644 core/autocomplete/NearbyDefinitionsService.ts create mode 100644 core/util/LruCache.ts rename extensions/vscode/tree-sitter/code-snippet-queries/{tree-sitter-c-tags.scm => c.scm} (100%) rename extensions/vscode/tree-sitter/code-snippet-queries/{tree-sitter-c_sharp-tags.scm => c_sharp.scm} (100%) rename extensions/vscode/tree-sitter/code-snippet-queries/{tree-sitter-cpp-tags.scm => cpp.scm} (100%) rename extensions/vscode/tree-sitter/code-snippet-queries/{tree-sitter-elisp-tags.scm => elisp.scm} (100%) rename extensions/vscode/tree-sitter/code-snippet-queries/{tree-sitter-elixir-tags.scm => elixir.scm} (100%) rename extensions/vscode/tree-sitter/code-snippet-queries/{tree-sitter-go-tags.scm => go.scm} (100%) rename extensions/vscode/tree-sitter/code-snippet-queries/{tree-sitter-java-tags.scm => java.scm} (100%) rename extensions/vscode/tree-sitter/code-snippet-queries/{tree-sitter-javascript-tags.scm => javascript.scm} (100%) rename extensions/vscode/tree-sitter/code-snippet-queries/{tree-sitter-ocaml-tags.scm => ocaml.scm} (100%) rename extensions/vscode/tree-sitter/code-snippet-queries/{tree-sitter-php-tags.scm => php.scm} (100%) rename extensions/vscode/tree-sitter/code-snippet-queries/{tree-sitter-python-tags.scm => python.scm} (100%) rename extensions/vscode/tree-sitter/code-snippet-queries/{tree-sitter-ql-tags.scm => ql.scm} (100%) rename extensions/vscode/tree-sitter/code-snippet-queries/{tree-sitter-ruby-tags.scm => ruby.scm} (100%) rename extensions/vscode/tree-sitter/code-snippet-queries/{tree-sitter-rust-tags.scm => rust.scm} (100%) rename extensions/vscode/tree-sitter/code-snippet-queries/{tree-sitter-typescript-tags.scm => typescript.scm} (100%) create mode 100644 extensions/vscode/tree-sitter/import-queries/typescript.scm diff --git a/binary/src/IpcIde.ts b/binary/src/IpcIde.ts index 2be3bd354..ee2649c36 100644 --- a/binary/src/IpcIde.ts +++ b/binary/src/IpcIde.ts @@ -3,6 +3,6 @@ import { MessageIde } from "core/util/messageIde"; export class IpcIde extends MessageIde { constructor(messenger: TODO) { - super(messenger.request.bind(messenger)); + super(messenger.request.bind(messenger), messenger.on.bind(messenger)); } } diff --git a/core/autocomplete/ImportDefinitionsService.ts b/core/autocomplete/ImportDefinitionsService.ts new file mode 100644 index 000000000..19287bf81 --- /dev/null +++ b/core/autocomplete/ImportDefinitionsService.ts @@ -0,0 +1,81 @@ +import { IDE } from ".."; +import { RangeInFileWithContents } from "../commands/util"; +import { PrecalculatedLruCache } from "../util/LruCache"; +import { + TSQueryType, + getParserForFile, + getQueryForFile, +} from "../util/treeSitter"; + +interface FileInfo { + imports: { [key: string]: RangeInFileWithContents[] }; +} + +export class ImportDefinitionsService { + static N = 10; + + private cache: PrecalculatedLruCache = + new PrecalculatedLruCache( + this._getFileInfo.bind(this), + ImportDefinitionsService.N, + ); + + constructor(private readonly ide: IDE) { + ide.onDidChangeActiveTextEditor((filepath) => { + this.cache.initKey(filepath); + }); + } + + get(filepath: string): FileInfo | undefined { + return this.cache.get(filepath); + } + + private async _getFileInfo(filepath: string): Promise { + const parser = await getParserForFile(filepath); + if (!parser) { + return { + imports: {}, + }; + } + const ast = parser.parse(await this.ide.readFile(filepath), undefined, { + includedRanges: [ + { + startIndex: 0, + endIndex: 10_000, + startPosition: { row: 0, column: 0 }, + endPosition: { row: 100, column: 0 }, + }, + ], + }); + const query = await getQueryForFile(filepath, TSQueryType.Imports); + if (!query) { + return { + imports: {}, + }; + } + + const matches = query?.matches(ast.rootNode); + + const fileInfo: FileInfo = { + imports: {}, + }; + for (const match of matches) { + const startPosition = match.captures[0].node.startPosition; + const defs = await this.ide.gotoDefinition({ + filepath, + position: { + line: startPosition.row, + character: startPosition.column, + }, + }); + fileInfo.imports[match.captures[0].node.text] = await Promise.all( + defs.map(async (def) => ({ + ...def, + contents: await this.ide.readRangeInFile(def.filepath, def.range), + })), + ); + } + + return fileInfo; + } +} diff --git a/core/autocomplete/NearbyDefinitionsService.ts b/core/autocomplete/NearbyDefinitionsService.ts new file mode 100644 index 000000000..79cd0af0a --- /dev/null +++ b/core/autocomplete/NearbyDefinitionsService.ts @@ -0,0 +1,45 @@ +import { IDE, Location } from ".."; +import { LANGUAGES } from "./languages"; +import { getSymbolsForSnippet } from "./ranking"; + +interface FileInfo { + filepath: string; +} + +export class NearbyDefinitionsService { + static N = 10; + + constructor(private readonly ide: IDE) {} + + async getDefinitionsForLine(filepath: string, line: number) { + const lineContent = await this.ide.readRangeInFile(filepath, { + start: { + line, + character: 0, + }, + end: { + line: line + 1, + character: 0, + }, + }); + + // Remove keywords + const lang = LANGUAGES[filepath.split(".").slice(-1)[0]]; + const symbols = Array.from(getSymbolsForSnippet(lineContent)) + .filter((s) => s.length > 0) + .filter((s) => !(lang && lang?.stopWords?.includes(s))); + + return Promise.all( + symbols.map((s) => { + const character = lineContent.indexOf(s); + const pos: Location = { + filepath, + position: { + line, + character, + }, + }; + }), + ); + } +} diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 873515bf5..f1cdfb165 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -1,5 +1,5 @@ -import Handlebars from "handlebars"; import ignore from "ignore"; +import OpenAI from "openai"; import path from "path"; import { v4 as uuidv4 } from "uuid"; import { RangeInFileWithContents } from "../commands/util.js"; @@ -14,7 +14,6 @@ import { Range, TabAutocompleteOptions, } from "../index.js"; -import OpenAI from "../llm/llms/OpenAI.js"; import { logDevData } from "../util/devdata.js"; import { getBasename, getLastNPathParts } from "../util/index.js"; import { @@ -23,6 +22,7 @@ import { } from "../util/parameters.js"; import { Telemetry } from "../util/posthog.js"; import { getRangeInString } from "../util/ranges.js"; +import { ImportDefinitionsService } from "./ImportDefinitionsService.js"; import { BracketMatchingService } from "./brackets.js"; import AutocompleteLruCache from "./cache.js"; import { @@ -138,342 +138,6 @@ export type GetLspDefinitionsFunction = ( lang: AutocompleteLanguageInfo, ) => Promise; -export async function getTabCompletion( - token: AbortSignal, - options: TabAutocompleteOptions, - llm: ILLM, - ide: IDE, - generatorReuseManager: GeneratorReuseManager, - input: AutocompleteInput, - getDefinitionsFromLsp: GetLspDefinitionsFunction, - bracketMatchingService: BracketMatchingService, -): Promise { - const startTime = Date.now(); - - const { - filepath, - pos, - recentlyEditedFiles, - recentlyEditedRanges, - clipboardText, - manuallyPassFileContents, - manuallyPassPrefix, - } = input; - const fileContents = - manuallyPassFileContents ?? (await ide.readFile(filepath)); - const fileLines = fileContents.split("\n"); - - // Filter - const lang = languageForFilepath(filepath); - const line = fileLines[pos.line] ?? ""; - for (const endOfLine of lang.endOfLine) { - if (line.endsWith(endOfLine) && pos.character >= line.length) { - return undefined; - } - } - - // Model - if (!llm) { - return; - } - if (llm instanceof OpenAI) { - llm.useLegacyCompletionsEndpoint = true; - } else if ( - llm.providerName === "free-trial" && - llm.model !== TRIAL_FIM_MODEL - ) { - llm.model = TRIAL_FIM_MODEL; - } - - if ( - !shownGptClaudeWarning && - nonAutocompleteModels.some((model) => llm.model.includes(model)) && - !llm.model.includes("deepseek") - ) { - shownGptClaudeWarning = true; - throw new Error( - `Warning: ${llm.model} is not trained for tab-autocomplete, and will result in low-quality suggestions. See the docs to learn more about why: https://docs.continue.dev/walkthroughs/tab-autocomplete#i-want-better-completions-should-i-use-gpt-4`, - ); - } - - // Prompt - let fullPrefix = - getRangeInString(fileContents, { - start: { line: 0, character: 0 }, - end: input.selectedCompletionInfo?.range.start ?? pos, - }) + (input.selectedCompletionInfo?.text ?? ""); - - if (input.injectDetails) { - const lines = fullPrefix.split("\n"); - fullPrefix = `${lines.slice(0, -1).join("\n")}\n${ - lang.singleLineComment - } ${input.injectDetails.split("\n").join(`\n${lang.singleLineComment} `)}\n${ - lines[lines.length - 1] - }`; - } - - const fullSuffix = getRangeInString(fileContents, { - start: pos, - end: { line: fileLines.length - 1, character: Number.MAX_SAFE_INTEGER }, - }); - - // First non-whitespace line below the cursor - let lineBelowCursor = ""; - let i = 1; - while ( - lineBelowCursor.trim() === "" && - pos.line + i <= fileLines.length - 1 - ) { - lineBelowCursor = fileLines[Math.min(pos.line + i, fileLines.length - 1)]; - i++; - } - - let extrasSnippets = options.useOtherFiles - ? ((await Promise.race([ - getDefinitionsFromLsp( - filepath, - fullPrefix + fullSuffix, - fullPrefix.length, - ide, - lang, - ), - new Promise((resolve) => { - setTimeout(() => resolve([]), 100); - }), - ])) as AutocompleteSnippet[]) - : []; - - const workspaceDirs = await ide.getWorkspaceDirs(); - if (options.onlyMyCode) { - extrasSnippets = extrasSnippets.filter((snippet) => { - return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)); - }); - } - - let { prefix, suffix, completeMultiline, snippets } = - await constructAutocompletePrompt( - filepath, - pos.line, - fullPrefix, - fullSuffix, - clipboardText, - lang, - options, - recentlyEditedRanges, - recentlyEditedFiles, - llm.model, - extrasSnippets, - ); - - // If prefix is manually passed - if (manuallyPassPrefix) { - prefix = manuallyPassPrefix; - suffix = ""; - } - - // Template prompt - const { - template, - completionOptions, - compilePrefixSuffix = undefined, - } = options.template - ? { template: options.template, completionOptions: {} } - : getTemplateForModel(llm.model); - - let prompt: string; - const filename = getBasename(filepath); - const reponame = getBasename(workspaceDirs[0] ?? "myproject"); - - // Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix - // into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint - if (compilePrefixSuffix) { - [prefix, suffix] = compilePrefixSuffix( - prefix, - suffix, - filepath, - reponame, - snippets, - ); - } - - if (typeof template === "string") { - const compiledTemplate = Handlebars.compile(template); - - // Format snippets as comments and prepend to prefix - const formattedSnippets = snippets - .map((snippet) => - formatExternalSnippet(snippet.filepath, snippet.contents, lang), - ) - .join("\n"); - if (formattedSnippets.length > 0) { - prefix = `${formattedSnippets}\n\n${prefix}`; - } else if (prefix.trim().length === 0 && suffix.trim().length === 0) { - // If it's an empty file, include the file name as a comment - prefix = `${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n${prefix}`; - } - - prompt = compiledTemplate({ - prefix, - suffix, - filename, - reponame, - }); - } else { - // Let the template function format snippets - prompt = template(prefix, suffix, filepath, reponame, snippets); - } - - // Completion - let completion = ""; - - const cache = await autocompleteCache; - const cachedCompletion = options.useCache - ? await cache.get(prefix) - : undefined; - let cacheHit = false; - if (cachedCompletion) { - // Cache - cacheHit = true; - completion = cachedCompletion; - } else { - const stop = [ - ...(completionOptions?.stop || []), - ...multilineStops, - ...commonStops, - ...(llm.model.toLowerCase().includes("starcoder2") - ? STARCODER2_T_ARTIFACTS - : []), - ...(lang.stopWords ?? []), - ...lang.topLevelKeywords.map((word) => `\n${word}`), - ]; - - let langMultilineDecision = lang.useMultiline?.({ prefix, suffix }); - let multiline: boolean = false; - if (langMultilineDecision) { - multiline = langMultilineDecision; - } else { - multiline = - !input.selectedCompletionInfo && // Only ever single-line if using intellisense selected value - options.multilineCompletions !== "never" && - (options.multilineCompletions === "always" || completeMultiline); - } - - // Try to reuse pending requests if what the user typed matches start of completion - const generator = generatorReuseManager.getGenerator( - prefix, - () => - llm.supportsFim() - ? llm.streamFim(prefix, suffix, { - ...completionOptions, - stop, - }) - : llm.streamComplete(prompt, { - ...completionOptions, - raw: true, - stop, - }), - multiline, - ); - - // Full stop means to stop the LLM's generation, instead of just truncating the displayed completion - const fullStop = () => generatorReuseManager.currentGenerator?.cancel(); - - // LLM - let cancelled = false; - const generatorWithCancellation = async function* () { - for await (const update of generator) { - if (token.aborted) { - cancelled = true; - return; - } - yield update; - } - }; - let charGenerator = generatorWithCancellation(); - charGenerator = noFirstCharNewline(charGenerator); - charGenerator = onlyWhitespaceAfterEndOfLine( - charGenerator, - lang.endOfLine, - fullStop, - ); - charGenerator = bracketMatchingService.stopOnUnmatchedClosingBracket( - charGenerator, - prefix, - suffix, - filepath, - multiline, - ); - - let lineGenerator = streamLines(charGenerator); - lineGenerator = stopAtLines(lineGenerator, fullStop); - lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); - lineGenerator = avoidPathLine(lineGenerator, lang.singleLineComment); - lineGenerator = skipPrefixes(lineGenerator); - lineGenerator = noTopLevelKeywordsMidline( - lineGenerator, - lang.topLevelKeywords, - fullStop, - ); - - for (const lineFilter of lang.lineFilters ?? []) { - lineGenerator = lineFilter({ lines: lineGenerator, fullStop }); - } - - lineGenerator = streamWithNewLines(lineGenerator); - - const finalGenerator = stopAtSimilarLine( - lineGenerator, - lineBelowCursor, - fullStop, - ); - - try { - for await (const update of finalGenerator) { - completion += update; - } - } catch (e: any) { - if (ERRORS_TO_IGNORE.some((err) => e.includes(err))) { - return undefined; - } - throw e; - } - - if (cancelled) { - return undefined; - } - - const processedCompletion = postprocessCompletion({ - completion, - prefix, - suffix, - llm, - }); - - if (!processedCompletion) { - return undefined; - } - completion = processedCompletion; - } - - const time = Date.now() - startTime; - return { - time, - completion, - prefix, - suffix, - prompt, - modelProvider: llm.providerName, - modelName: llm.model, - completionOptions, - cacheHit, - filepath: input.filepath, - completionId: input.completionId, - gitRepo: await ide.getRepoName(input.filepath), - uniqueId: await ide.getUniqueId(), - ...options, - }; -} - export class CompletionProvider { private static debounceTimeout: NodeJS.Timeout | undefined = undefined; private static debouncing = false; @@ -489,12 +153,15 @@ export class CompletionProvider { this.generatorReuseManager = new GeneratorReuseManager( this.onError.bind(this), ); + this.importDefinitionsService = new ImportDefinitionsService(this.ide); } + private importDefinitionsService: ImportDefinitionsService; private generatorReuseManager: GeneratorReuseManager; private autocompleteCache = AutocompleteLruCache.get(); public errorsShown: Set = new Set(); private bracketMatchingService = new BracketMatchingService(); + // private nearbyDefinitionsService = new NearbyDefinitionsService(); private onError(e: any) { console.warn("Error generating autocompletion: ", e); @@ -654,16 +321,7 @@ export class CompletionProvider { options.maxPromptTokens = 500; } - const outcome = await getTabCompletion( - token, - options, - llm, - this.ide, - this.generatorReuseManager, - input, - this.getDefinitionsFromLsp, - this.bracketMatchingService, - ); + const outcome = await this.getTabCompletion(token, options, llm, input); if (!outcome?.completion) { return undefined; @@ -735,4 +393,338 @@ export class CompletionProvider { displayedAt: now, }; } + + async getTabCompletion( + token: AbortSignal, + options: TabAutocompleteOptions, + llm: ILLM, + input: AutocompleteInput, + ): Promise { + const startTime = Date.now(); + + const { + filepath, + pos, + recentlyEditedFiles, + recentlyEditedRanges, + clipboardText, + manuallyPassFileContents, + manuallyPassPrefix, + } = input; + const fileContents = + manuallyPassFileContents ?? (await this.ide.readFile(filepath)); + const fileLines = fileContents.split("\n"); + + // Filter + const lang = languageForFilepath(filepath); + const line = fileLines[pos.line] ?? ""; + for (const endOfLine of lang.endOfLine) { + if (line.endsWith(endOfLine) && pos.character >= line.length) { + return undefined; + } + } + + // Model + if (!llm) { + return; + } + if (llm instanceof OpenAI) { + llm.useLegacyCompletionsEndpoint = true; + } else if ( + llm.providerName === "free-trial" && + llm.model !== TRIAL_FIM_MODEL + ) { + llm.model = TRIAL_FIM_MODEL; + } + + if ( + !shownGptClaudeWarning && + nonAutocompleteModels.some((model) => llm.model.includes(model)) && + !llm.model.includes("deepseek") + ) { + shownGptClaudeWarning = true; + throw new Error( + `Warning: ${llm.model} is not trained for tab-autocomplete, and will result in low-quality suggestions. See the docs to learn more about why: https://docs.continue.dev/walkthroughs/tab-autocomplete#i-want-better-completions-should-i-use-gpt-4`, + ); + } + + // Prompt + let fullPrefix = + getRangeInString(fileContents, { + start: { line: 0, character: 0 }, + end: input.selectedCompletionInfo?.range.start ?? pos, + }) + (input.selectedCompletionInfo?.text ?? ""); + + if (input.injectDetails) { + const lines = fullPrefix.split("\n"); + fullPrefix = `${lines.slice(0, -1).join("\n")}\n${ + lang.singleLineComment + } ${input.injectDetails.split("\n").join(`\n${lang.singleLineComment} `)}\n${ + lines[lines.length - 1] + }`; + } + + const fullSuffix = getRangeInString(fileContents, { + start: pos, + end: { line: fileLines.length - 1, character: Number.MAX_SAFE_INTEGER }, + }); + + // First non-whitespace line below the cursor + let lineBelowCursor = ""; + let i = 1; + while ( + lineBelowCursor.trim() === "" && + pos.line + i <= fileLines.length - 1 + ) { + lineBelowCursor = fileLines[Math.min(pos.line + i, fileLines.length - 1)]; + i++; + } + + let extrasSnippets = options.useOtherFiles + ? ((await Promise.race([ + this.getDefinitionsFromLsp( + filepath, + fullPrefix + fullSuffix, + fullPrefix.length, + this.ide, + lang, + ), + new Promise((resolve) => { + setTimeout(() => resolve([]), 100); + }), + ])) as AutocompleteSnippet[]) + : []; + + const workspaceDirs = await this.ide.getWorkspaceDirs(); + if (options.onlyMyCode) { + extrasSnippets = extrasSnippets.filter((snippet) => { + return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)); + }); + } + + let { prefix, suffix, completeMultiline, snippets } = + await constructAutocompletePrompt( + filepath, + pos.line, + fullPrefix, + fullSuffix, + clipboardText, + lang, + options, + recentlyEditedRanges, + recentlyEditedFiles, + llm.model, + extrasSnippets, + this.importDefinitionsService, + ); + + // If prefix is manually passed + if (manuallyPassPrefix) { + prefix = manuallyPassPrefix; + suffix = ""; + } + + // Template prompt + const { + template, + completionOptions, + compilePrefixSuffix = undefined, + } = options.template + ? { template: options.template, completionOptions: {} } + : getTemplateForModel(llm.model); + + let prompt: string; + const filename = getBasename(filepath); + const reponame = getBasename(workspaceDirs[0] ?? "myproject"); + + // Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix + // into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint + if (compilePrefixSuffix) { + [prefix, suffix] = compilePrefixSuffix( + prefix, + suffix, + filepath, + reponame, + snippets, + ); + } + + if (typeof template === "string") { + const compiledTemplate = Handlebars.compile(template); + + // Format snippets as comments and prepend to prefix + const formattedSnippets = snippets + .map((snippet) => + formatExternalSnippet(snippet.filepath, snippet.contents, lang), + ) + .join("\n"); + if (formattedSnippets.length > 0) { + prefix = `${formattedSnippets}\n\n${prefix}`; + } else if (prefix.trim().length === 0 && suffix.trim().length === 0) { + // If it's an empty file, include the file name as a comment + prefix = `${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n${prefix}`; + } + + prompt = compiledTemplate({ + prefix, + suffix, + filename, + reponame, + }); + } else { + // Let the template function format snippets + prompt = template(prefix, suffix, filepath, reponame, snippets); + } + + // Completion + let completion = ""; + + const cache = await autocompleteCache; + const cachedCompletion = options.useCache + ? await cache.get(prefix) + : undefined; + let cacheHit = false; + if (cachedCompletion) { + // Cache + cacheHit = true; + completion = cachedCompletion; + } else { + const stop = [ + ...(completionOptions?.stop || []), + ...multilineStops, + ...commonStops, + ...(llm.model.toLowerCase().includes("starcoder2") + ? STARCODER2_T_ARTIFACTS + : []), + ...(lang.stopWords ?? []), + ...lang.topLevelKeywords.map((word) => `\n${word}`), + ]; + + let langMultilineDecision = lang.useMultiline?.({ prefix, suffix }); + let multiline: boolean = false; + if (langMultilineDecision) { + multiline = langMultilineDecision; + } else { + multiline = + !input.selectedCompletionInfo && // Only ever single-line if using intellisense selected value + options.multilineCompletions !== "never" && + (options.multilineCompletions === "always" || completeMultiline); + } + + // Try to reuse pending requests if what the user typed matches start of completion + const generator = this.generatorReuseManager.getGenerator( + prefix, + () => + llm.supportsFim() + ? llm.streamFim(prefix, suffix, { + ...completionOptions, + stop, + }) + : llm.streamComplete(prompt, { + ...completionOptions, + raw: true, + stop, + }), + multiline, + ); + + // Full stop means to stop the LLM's generation, instead of just truncating the displayed completion + const fullStop = () => + this.generatorReuseManager.currentGenerator?.cancel(); + + // LLM + let cancelled = false; + const generatorWithCancellation = async function* () { + for await (const update of generator) { + if (token.aborted) { + cancelled = true; + return; + } + yield update; + } + }; + let charGenerator = generatorWithCancellation(); + charGenerator = noFirstCharNewline(charGenerator); + charGenerator = onlyWhitespaceAfterEndOfLine( + charGenerator, + lang.endOfLine, + fullStop, + ); + charGenerator = this.bracketMatchingService.stopOnUnmatchedClosingBracket( + charGenerator, + prefix, + suffix, + filepath, + multiline, + ); + + let lineGenerator = streamLines(charGenerator); + lineGenerator = stopAtLines(lineGenerator, fullStop); + lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); + lineGenerator = avoidPathLine(lineGenerator, lang.singleLineComment); + lineGenerator = skipPrefixes(lineGenerator); + lineGenerator = noTopLevelKeywordsMidline( + lineGenerator, + lang.topLevelKeywords, + fullStop, + ); + + for (const lineFilter of lang.lineFilters ?? []) { + lineGenerator = lineFilter({ lines: lineGenerator, fullStop }); + } + + lineGenerator = streamWithNewLines(lineGenerator); + + const finalGenerator = stopAtSimilarLine( + lineGenerator, + lineBelowCursor, + fullStop, + ); + + try { + for await (const update of finalGenerator) { + completion += update; + } + } catch (e: any) { + if (ERRORS_TO_IGNORE.some((err) => e.includes(err))) { + return undefined; + } + throw e; + } + + if (cancelled) { + return undefined; + } + + const processedCompletion = postprocessCompletion({ + completion, + prefix, + suffix, + llm, + }); + + if (!processedCompletion) { + return undefined; + } + completion = processedCompletion; + } + + const time = Date.now() - startTime; + return { + time, + completion, + prefix, + suffix, + prompt, + modelProvider: llm.providerName, + modelName: llm.model, + completionOptions, + cacheHit, + filepath: input.filepath, + completionId: input.completionId, + gitRepo: await this.ide.getRepoName(input.filepath), + uniqueId: await this.ide.getUniqueId(), + ...options, + }; + } } diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 6f97e75ac..78770a0d5 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -7,6 +7,7 @@ import { pruneLinesFromBottom, pruneLinesFromTop, } from "../llm/countTokens.js"; +import { ImportDefinitionsService } from "./ImportDefinitionsService.js"; import { getAst, getTreePathAtCursor } from "./ast.js"; import { AutocompleteLanguageInfo, @@ -15,6 +16,7 @@ import { } from "./languages.js"; import { fillPromptWithSnippets, + getSymbolsForSnippet, rankSnippets, removeRangeFromSnippets, type AutocompleteSnippet, @@ -124,6 +126,7 @@ export async function constructAutocompletePrompt( recentlyEditedFiles: RangeInFileWithContents[], modelName: string, extraSnippets: AutocompleteSnippet[], + importDefinitionsService: ImportDefinitionsService, ): Promise<{ prefix: string; suffix: string; @@ -189,6 +192,29 @@ export async function constructAutocompletePrompt( } } + // Use imports + if (options.useImports) { + const importSnippets = []; + const fileInfo = importDefinitionsService.get(filepath); + if (fileInfo) { + const { imports } = fileInfo; + // Look for imports of any symbols around the current range + const textAroundCursor = + fullPrefix.split("\n").slice(-5).join("\n") + + fullSuffix.split("\n").slice(0, 3).join("\n"); + const symbols = Array.from( + getSymbolsForSnippet(textAroundCursor), + ).filter((symbol) => !language.topLevelKeywords.includes(symbol)); + for (const symbol of symbols) { + const rifs = imports[symbol]; + if (rifs) { + importSnippets.push(...rifs); + } + } + } + snippets.push(...importSnippets); + } + // Filter out empty snippets and ones that are already in the prefix/suffix snippets = snippets .map((snippet) => ({ ...snippet })) diff --git a/core/index.d.ts b/core/index.d.ts index b5f40c322..658f5c980 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -201,6 +201,11 @@ export interface RangeInFile { range: Range; } +export interface Location { + filepath: string; + position: Position; +} + export interface FileWithContents { filepath: string; contents: string; @@ -462,6 +467,12 @@ export interface IDE { listDir(dir: string): Promise<[string, FileType][]>; getLastModified(files: string[]): Promise<{ [path: string]: number }>; getGitHubAuthToken(): Promise; + + // LSP + gotoDefinition(location: Location): Promise; + + // Callbacks + onDidChangeActiveTextEditor(callback: (filepath: string) => void): void; } // Slash Commands @@ -756,6 +767,7 @@ export interface TabAutocompleteOptions { useRecentlyEdited: boolean; recentLinePrefixMatchMinLength: number; disableInFiles?: string[]; + useImports?: boolean; } export interface ContinueUIConfig { diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 11a6a01bb..23dd5f535 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -1,5 +1,3 @@ -import fs from "node:fs"; -import path from "node:path"; import type { ChunkWithoutID, ContextItem, @@ -10,9 +8,9 @@ import type { } from "../index.js"; import { getBasename, getLastNPathParts } from "../util/index.js"; import { - getLanguageForFile, + TSQueryType, getParserForFile, - supportedLanguages, + getQueryForFile, } from "../util/treeSitter.js"; import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; import { @@ -46,35 +44,16 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { )`); } - private getQuerySource(filepath: string) { - const fullLangName = supportedLanguages[filepath.split(".").pop() ?? ""]; - const sourcePath = path.join( - __dirname, - "..", - "tree-sitter", - "code-snippet-queries", - `tree-sitter-${fullLangName}-tags.scm`, - ); - if (!fs.existsSync(sourcePath)) { - return ""; - } - return fs.readFileSync(sourcePath).toString(); - } - async getSnippetsInFile( filepath: string, contents: string, ): Promise<(ChunkWithoutID & { title: string })[]> { - const lang = await getLanguageForFile(filepath); - if (!lang) { - return []; - } const parser = await getParserForFile(filepath); if (!parser) { return []; } const ast = parser.parse(contents); - const query = lang?.query(this.getQuerySource(filepath)); + const query = await getQueryForFile(filepath, TSQueryType.CodeSnippets); const matches = query?.matches(ast.rootNode); return ( diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index ab32f52aa..31308ad4d 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -5,8 +5,10 @@ import type { IdeInfo, IdeSettings, IndexTag, + Location, Problem, Range, + RangeInFile, Thread, } from ".."; @@ -73,5 +75,7 @@ export type ToIdeFromWebviewOrCoreProtocol = { listDir: [{ dir: string }, [string, FileType][]]; getLastModified: [{ files: string[] }, { [path: string]: number }]; + gotoDefinition: [{ location: Location }, RangeInFile[]]; + getGitHubAuthToken: [undefined, string | undefined]; }; diff --git a/core/protocol/index.ts b/core/protocol/index.ts index 36c73e0b0..ac89c3b42 100644 --- a/core/protocol/index.ts +++ b/core/protocol/index.ts @@ -12,7 +12,10 @@ export type IProtocol = Record; // IDE export type ToIdeProtocol = ToIdeFromWebviewProtocol & ToIdeFromCoreProtocol; -export type FromIdeProtocol = ToWebviewFromIdeProtocol & ToCoreFromIdeProtocol; +export type FromIdeProtocol = ToWebviewFromIdeProtocol & + ToCoreFromIdeProtocol & { + didChangeActiveTextEditor: [{ filepath: string }, void]; + }; // Webview export type ToWebviewProtocol = ToWebviewFromIdeProtocol & diff --git a/core/util/LruCache.ts b/core/util/LruCache.ts new file mode 100644 index 000000000..f6d923fed --- /dev/null +++ b/core/util/LruCache.ts @@ -0,0 +1,30 @@ +export class PrecalculatedLruCache { + private items: [string, V][] = []; + constructor( + private readonly calculateValue: (key: string) => Promise, + private readonly N: number, + ) {} + + async initKey(key: string) { + // Maintain LRU + const index = this.items.findIndex((item) => item[0] === key); + + if (index < 0) { + // Calculate info for new file + const value: V = await this.calculateValue(key); + + this.items.push([key, value]); + if (this.items.length > this.N) { + this.items.shift(); + } + } else { + // Move to end of array, since it was recently used + const [item] = this.items.splice(index, 1); + this.items.push(item); + } + } + + get(key: string): V | undefined { + return this.items.find((item) => item[0] === key)?.[1]; + } +} diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 20373eebd..9745d1628 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -6,8 +6,10 @@ import { IdeInfo, IdeSettings, IndexTag, + Location, Problem, Range, + RangeInFile, Thread, } from "../index.d.js"; @@ -20,6 +22,13 @@ class FileSystemIde implements IDE { fs.mkdirSync(FileSystemIde.workspaceDir, { recursive: true }); } + gotoDefinition(location: Location): Promise { + throw new Error("Method not implemented."); + } + onDidChangeActiveTextEditor(callback: (filepath: string) => void): void { + throw new Error("Method not implemented."); + } + async getIdeSettings(): Promise { return { remoteConfigServerUrl: undefined, diff --git a/core/util/messageIde.ts b/core/util/messageIde.ts index 4523babba..d74a0ebe4 100644 --- a/core/util/messageIde.ts +++ b/core/util/messageIde.ts @@ -5,11 +5,14 @@ import type { IdeInfo, IdeSettings, IndexTag, + Location, Problem, Range, + RangeInFile, Thread, } from "../index.js"; import { ToIdeFromWebviewOrCoreProtocol } from "../protocol/ide.js"; +import { FromIdeProtocol } from "../protocol/index.js"; export class MessageIde implements IDE { constructor( @@ -17,7 +20,18 @@ export class MessageIde implements IDE { messageType: T, data: ToIdeFromWebviewOrCoreProtocol[T][0], ) => Promise, + private readonly on: ( + messageType: T, + callback: (data: FromIdeProtocol[T][0]) => FromIdeProtocol[T][1], + ) => void, ) {} + async gotoDefinition(location: Location): Promise { + return this.request("gotoDefinition", { location }); + } + onDidChangeActiveTextEditor(callback: (filepath: string) => void): void { + this.on("didChangeActiveTextEditor", (data) => callback(data.filepath)); + } + getIdeSettings(): Promise { return this.request("getIdeSettings", undefined); } diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 83b77046d..8909af6f4 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -19,6 +19,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { useRecentlyEdited: true, recentLinePrefixMatchMinLength: 7, disableInFiles: undefined, + useImports: true, }; export const COUNT_COMPLETION_REJECTED_AFTER = 10_000; diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 967f5d979..95a7a10ce 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -1,4 +1,5 @@ -import * as path from "path"; +import fs from "node:fs"; +import path from "node:path"; import Parser, { Language } from "web-tree-sitter"; export const supportedLanguages: { [key: string]: string } = { @@ -115,3 +116,34 @@ export async function getLanguageForFile( return undefined; } } + +export enum TSQueryType { + CodeSnippets = "code-snippet-queries", + Imports = "import-queries", +} + +export async function getQueryForFile( + filepath: string, + queryType: TSQueryType, +): Promise { + const language = await getLanguageForFile(filepath); + if (!language) { + return undefined; + } + + const fullLangName = supportedLanguages[filepath.split(".").pop() ?? ""]; + const sourcePath = path.join( + __dirname, + "..", + "tree-sitter", + queryType, + `${fullLangName}.scm`, + ); + if (!fs.existsSync(sourcePath)) { + return undefined; + } + const querySource = fs.readFileSync(sourcePath).toString(); + + const query = language.query(querySource); + return query; +} diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index d5a8b0c0d..71ff48e4e 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -470,7 +470,7 @@ const exe = os === "win32" ? ".exe" : ""; // Validate the all of the necessary files are present validateFilesPresent([ // Queries used to create the index for @code context provider - "tree-sitter/code-snippet-queries/tree-sitter-c_sharp-tags.scm", + "tree-sitter/code-snippet-queries/c_sharp.scm", // Queries used for @outline and @highlights context providers "tag-qry/tree-sitter-c_sharp-tags.scm", diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index 02441e965..8ac365826 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -32,7 +32,9 @@ function gotoInputKey(input: GotoInput) { const MAX_CACHE_SIZE = 50; const gotoCache = new Map(); -async function executeGotoProvider(input: GotoInput): Promise { +export async function executeGotoProvider( + input: GotoInput, +): Promise { const cacheKey = gotoInputKey(input); const cached = gotoCache.get(cacheKey); if (cached) { diff --git a/extensions/vscode/src/ideProtocol.ts b/extensions/vscode/src/ideProtocol.ts index d584d0615..a608b1757 100644 --- a/extensions/vscode/src/ideProtocol.ts +++ b/extensions/vscode/src/ideProtocol.ts @@ -9,7 +9,9 @@ import type { IdeInfo, IdeSettings, IndexTag, + Location, Problem, + RangeInFile, Thread, } from "core"; import { Range } from "core"; @@ -20,6 +22,7 @@ import { getContinueGlobalPath, } from "core/util/paths"; import * as vscode from "vscode"; +import { executeGotoProvider } from "./autocomplete/lsp"; import { DiffManager } from "./diff/horizontal"; import { Repository } from "./otherExtensions/git"; import { VsCodeIdeUtils } from "./util/ideUtils"; @@ -41,6 +44,25 @@ class VsCodeIde implements IDE { this.ideUtils = new VsCodeIdeUtils(); } + async gotoDefinition(location: Location): Promise { + const result = await executeGotoProvider({ + uri: location.filepath, + line: location.position.line, + character: location.position.character, + name: "vscode.executeDefinitionProvider", + }); + + return result; + } + + onDidChangeActiveTextEditor(callback: (filepath: string) => void): void { + vscode.window.onDidChangeActiveTextEditor((editor) => { + if (editor) { + callback(editor.document.uri.fsPath); + } + }); + } + private authToken: string | undefined; private askedForAuth = false; diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-c-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/c.scm similarity index 100% rename from extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-c-tags.scm rename to extensions/vscode/tree-sitter/code-snippet-queries/c.scm diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-c_sharp-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/c_sharp.scm similarity index 100% rename from extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-c_sharp-tags.scm rename to extensions/vscode/tree-sitter/code-snippet-queries/c_sharp.scm diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-cpp-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/cpp.scm similarity index 100% rename from extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-cpp-tags.scm rename to extensions/vscode/tree-sitter/code-snippet-queries/cpp.scm diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-elisp-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/elisp.scm similarity index 100% rename from extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-elisp-tags.scm rename to extensions/vscode/tree-sitter/code-snippet-queries/elisp.scm diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-elixir-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/elixir.scm similarity index 100% rename from extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-elixir-tags.scm rename to extensions/vscode/tree-sitter/code-snippet-queries/elixir.scm diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-go-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/go.scm similarity index 100% rename from extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-go-tags.scm rename to extensions/vscode/tree-sitter/code-snippet-queries/go.scm diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-java-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/java.scm similarity index 100% rename from extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-java-tags.scm rename to extensions/vscode/tree-sitter/code-snippet-queries/java.scm diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-javascript-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/javascript.scm similarity index 100% rename from extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-javascript-tags.scm rename to extensions/vscode/tree-sitter/code-snippet-queries/javascript.scm diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-ocaml-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/ocaml.scm similarity index 100% rename from extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-ocaml-tags.scm rename to extensions/vscode/tree-sitter/code-snippet-queries/ocaml.scm diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-php-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/php.scm similarity index 100% rename from extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-php-tags.scm rename to extensions/vscode/tree-sitter/code-snippet-queries/php.scm diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-python-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/python.scm similarity index 100% rename from extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-python-tags.scm rename to extensions/vscode/tree-sitter/code-snippet-queries/python.scm diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-ql-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/ql.scm similarity index 100% rename from extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-ql-tags.scm rename to extensions/vscode/tree-sitter/code-snippet-queries/ql.scm diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-ruby-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/ruby.scm similarity index 100% rename from extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-ruby-tags.scm rename to extensions/vscode/tree-sitter/code-snippet-queries/ruby.scm diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-rust-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/rust.scm similarity index 100% rename from extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-rust-tags.scm rename to extensions/vscode/tree-sitter/code-snippet-queries/rust.scm diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-typescript-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/typescript.scm similarity index 100% rename from extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-typescript-tags.scm rename to extensions/vscode/tree-sitter/code-snippet-queries/typescript.scm diff --git a/extensions/vscode/tree-sitter/import-queries/typescript.scm b/extensions/vscode/tree-sitter/import-queries/typescript.scm new file mode 100644 index 000000000..19a4d024a --- /dev/null +++ b/extensions/vscode/tree-sitter/import-queries/typescript.scm @@ -0,0 +1,9 @@ +(import_statement + (import_clause + (named_imports + (import_specifier + (identifier) @import)))) + +(import_statement + (import_clause + (identifier) @import )) \ No newline at end of file diff --git a/gui/src/context/IdeMessenger.ts b/gui/src/context/IdeMessenger.ts index 81d2201f9..7534d59b6 100644 --- a/gui/src/context/IdeMessenger.ts +++ b/gui/src/context/IdeMessenger.ts @@ -54,7 +54,7 @@ export class IdeMessenger implements IIdeMessenger { ide: IDE; constructor() { - this.ide = new MessageIde(this.request.bind(this)); + this.ide = new MessageIde(this.request.bind(this), () => {}); } private _postToIde(messageType: string, data: any, messageId?: string) {