From 7c5c8cb71bb3304fe0ec543d09f3a7e5cc547cec Mon Sep 17 00:00:00 2001 From: Michael Mayer Date: Thu, 19 Nov 2026 09:44:13 +0000 Subject: [PATCH 1/3] Run cells of any language with a Positron runtime In Positron, only R, Python, Julia and C# cells ran in the console. Cells for runtimes that other extensions register, such as {sas} from the SAS extension, got no Run Cell lens, and the run commands did nothing on them. Track the languages of registered Positron runtimes and treat them as executable, running their cells with the same executor as the built-in languages. Co-Authored-By: Claude Opus 5.5 --- apps/vscode/CHANGELOG.md | 1 + apps/vscode/src/host/positron.ts | 258 ++++++++++++-------- apps/vscode/src/providers/cell/executors.ts | 4 +- 3 files changed, 156 insertions(+), 107 deletions(-) diff --git a/apps/vscode/CHANGELOG.md b/apps/vscode/CHANGELOG.md index 345642bdb..294b87b6e 100644 --- a/apps/vscode/CHANGELOG.md +++ b/apps/vscode/CHANGELOG.md @@ -2,6 +2,7 @@ ## 1.140.0 (Unreleased) +- In Positron, cells in any language that has a Positron runtime now run in its console, with **Run Cell**, **Run Above**, **Run Next Cell** and the usual shortcuts. Before, only R, Python, Julia and C# cells could run, so cells for runtimes that extensions add, such as `{sas}` with the SAS extension, could not (). - Fixed a bug where hovering over any text after a citation on the same line showed that citation's reference. The hover now shows only over the `@` and the citation key (). - In the visual editor, code cells show completions and snippets automatically again while you type. Previously, they did not show when `editor.quickSuggestions` used its new default value, `offWhenInlineCompletions` (). - Fixed a bug where the language server could hang when hovering over text on a line that contains single-line display math such as `$$x$$` (). diff --git a/apps/vscode/src/host/positron.ts b/apps/vscode/src/host/positron.ts index 5cddb16fa..86440ffe1 100644 --- a/apps/vscode/src/host/positron.ts +++ b/apps/vscode/src/host/positron.ts @@ -72,11 +72,156 @@ function isConfigurationSet( ); } +/** + * Languages with a registered Positron runtime, such as SAS from the SAS + * extension. Cached because the checks for whether a cell can run are + * synchronous; kept current as extensions register runtimes. + */ +const runtimeLanguages = new Set(); +let trackingRuntimes = false; + +function trackRuntimeLanguages() { + const runtime = tryAcquirePositronApi()?.runtime; + if (trackingRuntimes || runtime === undefined) { + return; + } + trackingRuntimes = true; + runtime.getRegisteredRuntimes().then( + (runtimes) => runtimes.forEach((metadata) => runtimeLanguages.add(metadata.languageId)), + () => { } + ); + // lives as long as the extension host + runtime.onDidRegisterRuntime((metadata) => runtimeLanguages.add(metadata.languageId)); +} + +/** + * Whether Positron has a runtime for the language, so its cells can run in + * the console. + */ +export function hasPositronRuntime(language: string): boolean { + return runtimeLanguages.has(language); +} + +/** + * Cell executor that runs code in the Positron console of the language. + */ +function positronRuntimeExecutor( + language: string, + document: vscode.TextDocument, + engine: MarkdownEngine, + outputChannel?: vscode.LogOutputChannel +): CellExecutor { + return { + execute: async (blocks: string[], editorUri?: vscode.Uri, executionMetadata?: Record[]): Promise => { + const runtime = tryAcquirePositronApi()?.runtime; + + if (runtime === undefined) { + // Can't do anything without a runtime + return; + } + + let executionLanguage = language; + if ( + language === "python" && + isKnitrDocument(document, engine) && + vscode.workspace.getConfiguration("quarto").get("cells.useReticulate", true) + ) { + executionLanguage = "r"; + blocks = blocks.map(pythonWithReticulate); + } + + // Our callback executes each block sequentially + const callback = async () => { + for (let i = 0; i < blocks.length; i++) { + const metadata = executionMetadata?.[i]; + + // Track whether the runtime itself reported the failure. A + // failure of the running code (a runtime error or syntax + // error in the cell), an interrupt, or the session exiting are + // all delivered through the execution observer's `onFailed` + // callback before `executeCode` rejects. These are already + // surfaced in the console, so we don't want to surface them + // again. A rejection *without* `onFailed` having fired means + // the code couldn't be submitted to the runtime at all (e.g. + // no runtime is registered for the language), which is a + // genuine problem worth reporting. + let runtimeFailure = false; + + try { + await runtime.executeCode( + executionLanguage, // The language ID + blocks[i], // The code string to execute + false, // Whether to focus the console + true, // Whether to allow incomplete code to run + undefined, // The execution mode + undefined, // The error behavior + { onFailed: () => { runtimeFailure = true; } }, // An execution observer + undefined, // The specific session ID in which to execute + editorUri, // The document URI + metadata + ); + } catch (err) { + const message = err instanceof Error ? err.message : JSON.stringify(err); + + if (!runtimeFailure) { + // The code couldn't be submitted to the runtime. Log it + // and let it propagate so the user finds out. + outputChannel?.error(`Failed to execute ${executionLanguage} cell: ${message}`); + throw err; + } + + // The executed code raised an error (or was interrupted). + // It's already reported in the console, so log it for the + // record but don't let it propagate to the command handler, + // which would surface it again as a notification popup. + // https://github.com/posit-dev/positron/issues/9845 + outputChannel?.debug(`Error executing ${executionLanguage} cell: ${message}`); + + // Stop executing any subsequent blocks since one failed. + break; + } + } + }; + + await ExecuteQueue.instance.add(executionLanguage, callback); + }, + executeSelection: async (): Promise => { + await vscode.commands.executeCommand('workbench.action.positronConsole.executeCode', { languageId: language }); + }, + executeAtPosition: async (uri: Uri, position: Position): Promise => { + try { + return await vscode.commands.executeCommand( + 'positron.executeCodeFromPosition', + language, + uri, + position + ) as Position; + } catch { + // an error can happen, we think, if the statementRangeProvider errors + console.error('error when using `positron.executeCodeFromPosition`'); + } + return position; + }, + executeInlineCells: async (documentUri: vscode.Uri, cellRanges: Range[], executionMetadata?: Record[]): Promise => { + const runtime = tryAcquirePositronApi()?.runtime; + + if (runtime === undefined) { + // Can't do anything without a runtime + return; + } + + await runtime.executeInlineCell(documentUri, cellRanges, executionMetadata); + } + }; +} + export function positronExtensionHost(outputChannel?: vscode.LogOutputChannel): ExtensionHost { + trackRuntimeLanguages(); return { // supported executable languages (we delegate to the default for langugaes - // w/o runtimes so we support all languages) - executableLanguages, + // w/o runtimes so we support all languages), plus any language with a + // registered Positron runtime + executableLanguages: () => [...new Set([...executableLanguages(), ...runtimeLanguages])], cellExecutorForLanguage: async (language: string, document: vscode.TextDocument, engine: MarkdownEngine, silent?: boolean) : Promise => { @@ -86,111 +231,14 @@ export function positronExtensionHost(outputChannel?: vscode.LogOutputChannel): case "python": case "csharp": case "r": - return { - execute: async (blocks: string[], editorUri?: vscode.Uri, executionMetadata?: Record[]): Promise => { - const runtime = tryAcquirePositronApi()?.runtime; - - if (runtime === undefined) { - // Can't do anything without a runtime - return; - } - - let executionLanguage = language; - if ( - language === "python" && - isKnitrDocument(document, engine) && - vscode.workspace.getConfiguration("quarto").get("cells.useReticulate", true) - ) { - executionLanguage = "r"; - blocks = blocks.map(pythonWithReticulate); - } - - // Our callback executes each block sequentially - const callback = async () => { - for (let i = 0; i < blocks.length; i++) { - const metadata = executionMetadata?.[i]; - - // Track whether the runtime itself reported the failure. A - // failure of the running code (a runtime error or syntax - // error in the cell), an interrupt, or the session exiting are - // all delivered through the execution observer's `onFailed` - // callback before `executeCode` rejects. These are already - // surfaced in the console, so we don't want to surface them - // again. A rejection *without* `onFailed` having fired means - // the code couldn't be submitted to the runtime at all (e.g. - // no runtime is registered for the language), which is a - // genuine problem worth reporting. - let runtimeFailure = false; - - try { - await runtime.executeCode( - executionLanguage, // The language ID - blocks[i], // The code string to execute - false, // Whether to focus the console - true, // Whether to allow incomplete code to run - undefined, // The execution mode - undefined, // The error behavior - { onFailed: () => { runtimeFailure = true; } }, // An execution observer - undefined, // The specific session ID in which to execute - editorUri, // The document URI - metadata - ); - } catch (err) { - const message = err instanceof Error ? err.message : JSON.stringify(err); - - if (!runtimeFailure) { - // The code couldn't be submitted to the runtime. Log it - // and let it propagate so the user finds out. - outputChannel?.error(`Failed to execute ${executionLanguage} cell: ${message}`); - throw err; - } - - // The executed code raised an error (or was interrupted). - // It's already reported in the console, so log it for the - // record but don't let it propagate to the command handler, - // which would surface it again as a notification popup. - // https://github.com/posit-dev/positron/issues/9845 - outputChannel?.debug(`Error executing ${executionLanguage} cell: ${message}`); - - // Stop executing any subsequent blocks since one failed. - break; - } - } - }; - - await ExecuteQueue.instance.add(executionLanguage, callback); - }, - executeSelection: async (): Promise => { - await vscode.commands.executeCommand('workbench.action.positronConsole.executeCode', { languageId: language }); - }, - executeAtPosition: async (uri: Uri, position: Position): Promise => { - try { - return await vscode.commands.executeCommand( - 'positron.executeCodeFromPosition', - language, - uri, - position - ) as Position; - } catch { - // an error can happen, we think, if the statementRangeProvider errors - console.error('error when using `positron.executeCodeFromPosition`'); - } - return position; - }, - executeInlineCells: async (documentUri: vscode.Uri, cellRanges: Range[], executionMetadata?: Record[]): Promise => { - const runtime = tryAcquirePositronApi()?.runtime; - - if (runtime === undefined) { - // Can't do anything without a runtime - return; - } - - await runtime.executeInlineCell(documentUri, cellRanges, executionMetadata); - } - }; + return positronRuntimeExecutor(language, document, engine, outputChannel); - // delegate for other languages + // use positron api for any other language with a registered runtime + // (e.g. SAS from an extension), and delegate the rest default: + if (hasPositronRuntime(language)) { + return positronRuntimeExecutor(language, document, engine, outputChannel); + } return cellExecutorForLanguage(language, document, engine, silent); } }, diff --git a/apps/vscode/src/providers/cell/executors.ts b/apps/vscode/src/providers/cell/executors.ts index cd1479de9..3d0e22af0 100644 --- a/apps/vscode/src/providers/cell/executors.ts +++ b/apps/vscode/src/providers/cell/executors.ts @@ -25,13 +25,13 @@ import { cellOptionsForToken, kExecuteEval } from "./options"; import { CellExecutor, ExtensionHost } from "../../host"; import { executableLanguages } from "../../host/executors"; -import { isInlineOutputEnabled } from "../../host/positron"; +import { hasPositronRuntime, isInlineOutputEnabled } from "../../host/positron"; import { Position } from "vscode"; import { Uri } from "vscode"; export function hasExecutor(_host: ExtensionHost, language: string) { - return executableLanguages().includes(language); + return executableLanguages().includes(language) || hasPositronRuntime(language); } export function blockHasExecutor(host: ExtensionHost, token?: Token): token is TokenMath | TokenCodeBlock { From f8899234ce09d6e045b68af13fddc0095393f312 Mon Sep 17 00:00:00 2001 From: Michael Mayer Date: Thu, 19 Nov 2026 09:45:05 +0000 Subject: [PATCH 2/3] Link the changelog entry to its PR Co-Authored-By: Claude Opus 5.5 --- apps/vscode/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/vscode/CHANGELOG.md b/apps/vscode/CHANGELOG.md index 294b87b6e..2af7da109 100644 --- a/apps/vscode/CHANGELOG.md +++ b/apps/vscode/CHANGELOG.md @@ -2,7 +2,7 @@ ## 1.140.0 (Unreleased) -- In Positron, cells in any language that has a Positron runtime now run in its console, with **Run Cell**, **Run Above**, **Run Next Cell** and the usual shortcuts. Before, only R, Python, Julia and C# cells could run, so cells for runtimes that extensions add, such as `{sas}` with the SAS extension, could not (). +- In Positron, cells in any language that has a Positron runtime now run in its console, with **Run Cell**, **Run Above**, **Run Next Cell** and the usual shortcuts. Before, only R, Python, Julia and C# cells could run, so cells for runtimes that extensions add, such as `{sas}` with the SAS extension, could not (). - Fixed a bug where hovering over any text after a citation on the same line showed that citation's reference. The hover now shows only over the `@` and the citation key (). - In the visual editor, code cells show completions and snippets automatically again while you type. Previously, they did not show when `editor.quickSuggestions` used its new default value, `offWhenInlineCompletions` (). - Fixed a bug where the language server could hang when hovering over text on a line that contains single-line display math such as `$$x$$` (). From c75a7a4e96d4c10547363f813741f5ff362b858b Mon Sep 17 00:00:00 2001 From: Michael Mayer Date: Thu, 19 Nov 2026 20:34:08 +0000 Subject: [PATCH 3/3] Read runnable languages from languageRuntimes contributions Use the `languageRuntimes` contributions in the extensions' package.json as the main source of languages whose cells run in a Positron console, as Positron does for inline output (`hasLanguageRuntimeProvider`), and keep the registered runtimes as a second source. The contributions are known before the extensions activate or discover a runtime, so e.g. `{sas}` cells are runnable before a SAS connection profile exists, and both modes agree on which cells can run. Strip the leading option lines of these languages before sending the code to the console, using each language's own comment characters (`#|` for ggsql, where `#` isn't a comment, and `*| ...;` for sas). The matching is shared with cellOptions(). Co-Authored-By: Claude Opus 5.5 --- apps/vscode/CHANGELOG.md | 2 +- apps/vscode/src/host/positron.ts | 73 +++++++++++++++++---- apps/vscode/src/providers/cell/executors.ts | 15 ++++- apps/vscode/src/providers/cell/options.ts | 57 +++++++++------- apps/vscode/src/test/cellExecutors.test.ts | 62 ++++++++++++++++- 5 files changed, 167 insertions(+), 42 deletions(-) diff --git a/apps/vscode/CHANGELOG.md b/apps/vscode/CHANGELOG.md index 2af7da109..3029699ec 100644 --- a/apps/vscode/CHANGELOG.md +++ b/apps/vscode/CHANGELOG.md @@ -2,7 +2,7 @@ ## 1.140.0 (Unreleased) -- In Positron, cells in any language that has a Positron runtime now run in its console, with **Run Cell**, **Run Above**, **Run Next Cell** and the usual shortcuts. Before, only R, Python, Julia and C# cells could run, so cells for runtimes that extensions add, such as `{sas}` with the SAS extension, could not (). +- In Positron with inline output off, cells in any language that has a Positron runtime now run in its console, with **Run Cell**, **Run Above**, **Run Next Cell** and the usual shortcuts. Before, only R, Python, Julia and C# cells could run, so cells for runtimes that extensions add, such as `{ggsql}` and `{sas}`, could not. A language counts when an extension declares it in the `languageRuntimes` contribution of its `package.json`, as Positron decides for inline output, or registers a runtime for it. The cell option lines of these languages are not sent to the console (). - Fixed a bug where hovering over any text after a citation on the same line showed that citation's reference. The hover now shows only over the `@` and the citation key (). - In the visual editor, code cells show completions and snippets automatically again while you type. Previously, they did not show when `editor.quickSuggestions` used its new default value, `offWhenInlineCompletions` (). - Fixed a bug where the language server could hang when hovering over text on a line that contains single-line display math such as `$$x$$` (). diff --git a/apps/vscode/src/host/positron.ts b/apps/vscode/src/host/positron.ts index 86440ffe1..2fa6cb136 100644 --- a/apps/vscode/src/host/positron.ts +++ b/apps/vscode/src/host/positron.ts @@ -73,11 +73,49 @@ function isConfigurationSet( } /** - * Languages with a registered Positron runtime, such as SAS from the SAS - * extension. Cached because the checks for whether a cell can run are - * synchronous; kept current as extensions register runtimes. + * The languages that extensions declare runtimes for in the `languageRuntimes` + * contribution of their `package.json`, e.g. `sas` from the SAS extension or + * `ggsql` from the ggsql extension. */ -const runtimeLanguages = new Set(); +export function contributedRuntimeLanguages( + extensions: readonly { packageJSON: unknown }[] +): Set { + const languages = new Set(); + for (const extension of extensions) { + const packageJSON = extension.packageJSON as + { contributes?: { languageRuntimes?: unknown } } | undefined; + const contributions = packageJSON?.contributes?.languageRuntimes; + if (!Array.isArray(contributions)) { + continue; + } + for (const contribution of contributions) { + const languageId = (contribution as { languageId?: unknown } | undefined)?.languageId; + if (typeof languageId === "string" && languageId.length > 0) { + languages.add(languageId); + } + } + } + return languages; +} + +/** + * Languages whose cells can run in a Positron console. They come from two + * sources, as in Positron's own check for inline output + * (`hasLanguageRuntimeProvider`): + * + * - the `languageRuntimes` contributions of the installed extensions, which + * are known before those extensions activate or discover any runtime, and + * - the registered runtimes, for an extension that registers a runtime + * without declaring the contribution. + * + * Both are cached because the checks for whether a cell can run are + * synchronous. They are tracked only in Positron, so nothing changes in + * VS Code even when such extensions are installed. + * + * See also https://github.com/posit-dev/positron/issues/17432 + */ +let contributedLanguages = new Set(); +const registeredLanguages = new Set(); let trackingRuntimes = false; function trackRuntimeLanguages() { @@ -86,12 +124,19 @@ function trackRuntimeLanguages() { return; } trackingRuntimes = true; + + // the contributions are read synchronously, so they are known right away; + // the subscriptions below live as long as the extension host + contributedLanguages = contributedRuntimeLanguages(vscode.extensions.all); + vscode.extensions.onDidChange(() => { + contributedLanguages = contributedRuntimeLanguages(vscode.extensions.all); + }); + runtime.getRegisteredRuntimes().then( - (runtimes) => runtimes.forEach((metadata) => runtimeLanguages.add(metadata.languageId)), + (runtimes) => runtimes.forEach((metadata) => registeredLanguages.add(metadata.languageId)), () => { } ); - // lives as long as the extension host - runtime.onDidRegisterRuntime((metadata) => runtimeLanguages.add(metadata.languageId)); + runtime.onDidRegisterRuntime((metadata) => registeredLanguages.add(metadata.languageId)); } /** @@ -99,7 +144,11 @@ function trackRuntimeLanguages() { * the console. */ export function hasPositronRuntime(language: string): boolean { - return runtimeLanguages.has(language); + return contributedLanguages.has(language) || registeredLanguages.has(language); +} + +function positronRuntimeLanguages(): string[] { + return [...new Set([...contributedLanguages, ...registeredLanguages])]; } /** @@ -220,8 +269,8 @@ export function positronExtensionHost(outputChannel?: vscode.LogOutputChannel): return { // supported executable languages (we delegate to the default for langugaes // w/o runtimes so we support all languages), plus any language with a - // registered Positron runtime - executableLanguages: () => [...new Set([...executableLanguages(), ...runtimeLanguages])], + // Positron runtime + executableLanguages: () => [...new Set([...executableLanguages(), ...positronRuntimeLanguages()])], cellExecutorForLanguage: async (language: string, document: vscode.TextDocument, engine: MarkdownEngine, silent?: boolean) : Promise => { @@ -233,8 +282,8 @@ export function positronExtensionHost(outputChannel?: vscode.LogOutputChannel): case "r": return positronRuntimeExecutor(language, document, engine, outputChannel); - // use positron api for any other language with a registered runtime - // (e.g. SAS from an extension), and delegate the rest + // use positron api for any other language with a Positron runtime + // (e.g. SAS or ggsql from an extension), and delegate the rest default: if (hasPositronRuntime(language)) { return positronRuntimeExecutor(language, document, engine, outputChannel); diff --git a/apps/vscode/src/providers/cell/executors.ts b/apps/vscode/src/providers/cell/executors.ts index 3d0e22af0..7bcc57356 100644 --- a/apps/vscode/src/providers/cell/executors.ts +++ b/apps/vscode/src/providers/cell/executors.ts @@ -21,7 +21,7 @@ import { import { lines } from "core"; -import { cellOptionsForToken, kExecuteEval } from "./options"; +import { cellOptionsForToken, kExecuteEval, leadingOptionYaml } from "./options"; import { CellExecutor, ExtensionHost } from "../../host"; import { executableLanguages } from "../../host/executors"; @@ -60,7 +60,10 @@ export function cellMetadataForBlock(token: TokenMath | TokenCodeBlock): Record< } // skip yaml options for execution -export function codeWithoutOptionsFromBlock(token: TokenMath | TokenCodeBlock) { +export function codeWithoutOptionsFromBlock( + token: TokenMath | TokenCodeBlock, + hasRuntime: (language: string) => boolean = hasPositronRuntime +) { if (isExecutableLanguageBlock(token)) { const language = languageNameFromBlock(token); if (hasYamlHashOptions(language)) { @@ -73,6 +76,14 @@ export function codeWithoutOptionsFromBlock(token: TokenMath | TokenCodeBlock) { } else { return ""; } + } else if (hasRuntime(language)) { + // a language that a Positron runtime runs in the console (e.g. sas or + // ggsql): skip its option lines, written with its own comment + // characters (`*| ... ;` for sas, `#|` for languages without an entry + // in kLangCommentChars, such as ggsql, where `#` isn't a comment) + const blockLines = lines(codeForExecutableLanguageBlock(token)); + const optionLines = leadingOptionYaml(language, blockLines).length; + return blockLines.slice(optionLines).join("\n"); } else { return codeForExecutableLanguageBlock(token); } diff --git a/apps/vscode/src/providers/cell/options.ts b/apps/vscode/src/providers/cell/options.ts index 688253226..6cfe0f34f 100644 --- a/apps/vscode/src/providers/cell/options.ts +++ b/apps/vscode/src/providers/cell/options.ts @@ -28,12 +28,42 @@ export function cellOptionsForToken(token: Token): Record { export function cellOptions(language: string, source: string[]): Record { + // find the yaml lines + const yamlLines = leadingOptionYaml(language, source); + + // parse the yaml + if (yamlLines.length > 0) { + try { + const options = loadYaml(yamlLines.join("\n")); + if ( + typeof options === "object" && + !Array.isArray(options) && + options !== null + ) { + return options as Record; + } else { + return {}; + } + } catch (_e) { + // ignore for invalid yaml + return {}; + } + } else { + return {}; + } +} + +/** + * The YAML of the option lines at the start of a cell's source, with their + * comment characters removed (e.g. `#| echo: false` gives `echo: false`, and + * `*| echo: false;` for sas gives the same). The number of entries is the + * number of option lines. + */ +export function leadingOptionYaml(language: string, source: string[]): string[] { const commentChars = langCommentChars(language); const optionPattern = optionCommentPattern(commentChars[0]); const optionSuffix = commentChars[1] || ""; - // find the yaml lines - const optionsSource: string[] = []; const yamlLines: string[] = []; for (const line of source) { const optionMatch = line.match(optionPattern); @@ -48,31 +78,10 @@ export function cellOptions(language: string, source: string[]): Record 0) { - try { - const options = loadYaml(yamlLines.join("\n")); - if ( - typeof options === "object" && - !Array.isArray(options) && - options !== null - ) { - return options as Record; - } else { - return {}; - } - } catch (_e) { - // ignore for invalid yaml - return {}; - } - } else { - return {}; - } + return yamlLines; } diff --git a/apps/vscode/src/test/cellExecutors.test.ts b/apps/vscode/src/test/cellExecutors.test.ts index 7e8bba5bd..de0951c69 100644 --- a/apps/vscode/src/test/cellExecutors.test.ts +++ b/apps/vscode/src/test/cellExecutors.test.ts @@ -4,6 +4,7 @@ import * as assert from "assert"; import { isExecutableLanguageBlock, TokenCodeBlock, TokenMath } from "quarto-core"; import { MarkdownEngine } from "../markdown/engine"; import { codeWithoutOptionsFromBlock } from "../providers/cell/executors"; +import { contributedRuntimeLanguages } from "../host/positron"; suite("Code sent for execution", function () { const engine = new MarkdownEngine(); @@ -11,18 +12,52 @@ suite("Code sent for execution", function () { /** * Parses `content` as an in-memory Quarto document and returns the code of * its single executable cell, as it would be sent to an executor (without - * the trailing newline, which isn't what's under test here). + * the trailing newline, which isn't what's under test here). `runtimes` are + * the languages that count as having a Positron runtime. */ - async function executedCode(content: string): Promise { + async function executedCode(content: string, runtimes: string[] = []): Promise { const doc = await vscode.workspace.openTextDocument({ language: "quarto", content, }); const blocks = engine.parse(doc).filter(isExecutableLanguageBlock); assert.strictEqual(blocks.length, 1, "expected exactly one executable cell"); - return codeWithoutOptionsFromBlock(blocks[0] as TokenMath | TokenCodeBlock).trimEnd(); + return codeWithoutOptionsFromBlock( + blocks[0] as TokenMath | TokenCodeBlock, + (language) => runtimes.includes(language) + ).trimEnd(); } + test("strips *| options from a sas cell that a Positron runtime runs", async function () { + assert.strictEqual( + await executedCode("```{sas}\n*| label: a;\n*| echo: false;\nproc print data=sashelp.class; run;\n```", ["sas"]), + "proc print data=sashelp.class; run;" + ); + }); + + test("strips #| options from a ggsql cell that a Positron runtime runs", async function () { + // ggsql has no entry in kLangCommentChars, so its options are `#|` + // lines, and `#` isn't a comment in ggsql + assert.strictEqual( + await executedCode("```{ggsql}\n#| label: a\n#| error: true\nVISUALISE x, y FROM df DRAW point\n```", ["ggsql"]), + "VISUALISE x, y FROM df DRAW point" + ); + }); + + test("keeps the options of a language without a Positron runtime", async function () { + assert.strictEqual( + await executedCode("```{sas}\n*| label: a;\nproc print; run;\n```"), + "*| label: a;\nproc print; run;" + ); + }); + + test("keeps option-like lines after the code of a runtime cell", async function () { + assert.strictEqual( + await executedCode("```{ggsql}\n#| label: a\nSELECT 1\n#| not an option\n```", ["ggsql"]), + "SELECT 1\n#| not an option" + ); + }); + test("strips #| options from a Python cell", async function () { assert.strictEqual( await executedCode("```{python}\n#| label: a\n#| echo: false\nx = 1\n```"), @@ -46,3 +81,24 @@ suite("Code sent for execution", function () { ); }); }); + +suite("Languages with a Positron runtime", function () { + test("reads the languageRuntimes contributions of extensions", function () { + const languages = contributedRuntimeLanguages([ + { packageJSON: { contributes: { languageRuntimes: [{ languageId: "sas" }] } } }, + { packageJSON: { contributes: { languageRuntimes: [{ languageId: "ggsql" }, { languageId: "sas" }] } } }, + { packageJSON: { contributes: { languages: [{ id: "markdown" }] } } }, + { packageJSON: {} }, + { packageJSON: undefined }, + ]); + assert.deepStrictEqual([...languages].sort(), ["ggsql", "sas"]); + }); + + test("ignores malformed languageRuntimes contributions", function () { + const languages = contributedRuntimeLanguages([ + { packageJSON: { contributes: { languageRuntimes: { languageId: "sas" } } } }, + { packageJSON: { contributes: { languageRuntimes: [null, {}, { languageId: 1 }, { languageId: "" }] } } }, + ]); + assert.deepStrictEqual([...languages], []); + }); +});