Skip to content

Commit a20557b

Browse files
claude: Add class-based engine selection with scoring
Add support for extracting the first class from code block attributes (e.g., {python .marimo}) and passing it to engine's claimsLanguage method. Changes: - Add languagesWithClasses() function returning Map<language, class|undefined> - Update languagesInMarkdown() to use languagesWithClasses internally - Update claimsLanguage signature to accept optional firstClass parameter and return boolean | number for priority-based selection - Update markdownExecutionEngine to use scoring: highest score wins, first engine wins ties (backwards compatible) - Expose getLanguagesWithClasses in the markdownRegex API namespace Backwards compatibility: - Old engines returning true -> score 1 - Old engines returning false -> score 0 - New engines can return numbers > 1 to override 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1 parent 7c4c84f commit a20557b

11 files changed

Lines changed: 202 additions & 17 deletions

File tree

‎packages/quarto-types/dist/index.d.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -831,6 +831,13 @@ export interface QuartoAPI {
831831
* @returns Set of language identifiers found in fenced code blocks
832832
*/
833833
getLanguages: (markdown: string) => Set<string>;
834+
/**
835+
* Extract programming languages and their first class from code blocks
836+
*
837+
* @param markdown - Markdown content to analyze
838+
* @returns Map of language identifiers to their first class (or undefined)
839+
*/
840+
getLanguagesWithClasses: (markdown: string) => Map<string, string | undefined>;
834841
/**
835842
* Break Quarto markdown into cells
836843
*
@@ -1566,8 +1573,12 @@ export interface ExecutionEngineDiscovery {
15661573
claimsFile: (file: string, ext: string) => boolean;
15671574
/**
15681575
* Whether this engine can handle the given language
1576+
*
1577+
* @param language - The language identifier (e.g., "python", "r", "julia")
1578+
* @param firstClass - Optional first class from code block attributes (e.g., "marimo" from {python .marimo})
1579+
* @returns boolean for simple claim, or number for priority (higher wins, 0 = no claim, 1 = standard claim)
15691580
*/
1570-
claimsLanguage: (language: string) => boolean;
1581+
claimsLanguage: (language: string, firstClass?: string) => boolean | number;
15711582
/**
15721583
* Whether this engine supports freezing
15731584
*/

‎packages/quarto-types/src/execution-engine.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,12 @@ export interface ExecutionEngineDiscovery {
9595

9696
/**
9797
* Whether this engine can handle the given language
98+
*
99+
* @param language - The language identifier (e.g., "python", "r", "julia")
100+
* @param firstClass - Optional first class from code block attributes (e.g., "marimo" from {python .marimo})
101+
* @returns boolean for simple claim, or number for priority (higher wins, 0 = no claim, 1 = standard claim)
98102
*/
99-
claimsLanguage: (language: string) => boolean;
103+
claimsLanguage: (language: string, firstClass?: string) => boolean | number;
100104

101105
/**
102106
* Whether this engine supports freezing

‎packages/quarto-types/src/quarto-api.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,14 @@ export interface QuartoAPI {
6666
*/
6767
getLanguages: (markdown: string) => Set<string>;
6868

69+
/**
70+
* Extract programming languages and their first class from code blocks
71+
*
72+
* @param markdown - Markdown content to analyze
73+
* @returns Map of language identifiers to their first class (or undefined)
74+
*/
75+
getLanguagesWithClasses: (markdown: string) => Map<string, string | undefined>;
76+
6977
/**
7078
* Break Quarto markdown into cells
7179
*

‎src/core/api/markdown-regex.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import type { MarkdownRegexNamespace } from "./types.ts";
77
import { readYamlFromMarkdown } from "../yaml.ts";
88
import {
99
languagesInMarkdown,
10+
languagesWithClasses,
1011
partitionMarkdown,
1112
} from "../pandoc/pandoc-partition.ts";
1213
import { breakQuartoMd } from "../lib/break-quarto-md.ts";
@@ -17,6 +18,7 @@ globalRegistry.register("markdownRegex", (): MarkdownRegexNamespace => {
1718
extractYaml: readYamlFromMarkdown,
1819
partition: partitionMarkdown,
1920
getLanguages: languagesInMarkdown,
21+
getLanguagesWithClasses: languagesWithClasses,
2022
breakQuartoMd,
2123
};
2224
});

‎src/core/api/types.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@ export interface MarkdownRegexNamespace {
3838
extractYaml: (markdown: string) => Metadata;
3939
partition: (markdown: string) => PartitionedMarkdown;
4040
getLanguages: (markdown: string) => Set<string>;
41+
getLanguagesWithClasses: (
42+
markdown: string,
43+
) => Map<string, string | undefined>;
4144
breakQuartoMd: (
4245
src: string | MappedString,
4346
validate?: boolean,

‎src/core/pandoc/pandoc-partition.ts‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -114,19 +114,29 @@ export function languagesInMarkdownFile(file: string) {
114114
return languagesInMarkdown(Deno.readTextFileSync(file));
115115
}
116116

117-
export function languagesInMarkdown(markdown: string) {
118-
// see if there are any code chunks in the file
119-
const languages = new Set<string>();
120-
const kChunkRegex = /^[\t >]*```+\s*\{([a-zA-Z0-9_]+)( *[ ,].*)?\}\s*$/gm;
117+
export function languagesWithClasses(
118+
markdown: string,
119+
): Map<string, string | undefined> {
120+
const result = new Map<string, string | undefined>();
121+
// Capture language and everything after it (including dot-joined classes like {python.marimo})
122+
const kChunkRegex = /^[\t >]*```+\s*\{([a-zA-Z0-9_]+)([^}]*)?\}\s*$/gm;
121123
kChunkRegex.lastIndex = 0;
122124
let match = kChunkRegex.exec(markdown);
123125
while (match) {
124126
const language = match[1].toLowerCase();
125-
if (!languages.has(language)) {
126-
languages.add(language);
127+
if (!result.has(language)) {
128+
// Extract first class from attrs (group 2)
129+
// Handles {python.marimo}, {python .marimo}, {python #id .marimo}, etc.
130+
const attrs = match[2];
131+
const firstClass = attrs?.match(/\.([a-zA-Z][a-zA-Z0-9_-]*)/)?.[1];
132+
result.set(language, firstClass);
127133
}
128134
match = kChunkRegex.exec(markdown);
129135
}
130136
kChunkRegex.lastIndex = 0;
131-
return languages;
137+
return result;
138+
}
139+
140+
export function languagesInMarkdown(markdown: string): Set<string> {
141+
return new Set(languagesWithClasses(markdown).keys());
132142
}

‎src/execute/engine.ts‎

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,10 @@ import {
2727
ExecutionTarget,
2828
kQmdExtensions,
2929
} from "./types.ts";
30-
import { languagesInMarkdown } from "../core/pandoc/pandoc-partition.ts";
30+
import {
31+
languagesInMarkdown,
32+
languagesWithClasses,
33+
} from "../core/pandoc/pandoc-partition.ts";
3134
import { languages as handlerLanguages } from "../core/handlers/base.ts";
3235
import { RenderContext, RenderFlags } from "../command/render/types.ts";
3336
import { mergeConfigs } from "../core/config.ts";
@@ -168,20 +171,31 @@ export function markdownExecutionEngine(
168171
}
169172

170173
// if there are languages see if any engines want to claim them
171-
const languages = languagesInMarkdown(markdown);
174+
const languagesWithClassesMap = languagesWithClasses(markdown);
175+
176+
// see if there is an engine that claims this language (highest score wins)
177+
for (const [language, firstClass] of languagesWithClassesMap) {
178+
let bestEngine: ExecutionEngineDiscovery | undefined;
179+
let bestScore = 0;
172180

173-
// see if there is an engine that claims this language
174-
for (const language of languages) {
175181
for (const [_, engine] of reorderedEngines) {
176-
if (engine.claimsLanguage(language)) {
177-
return engine.launch(engineProjectContext(project));
182+
const claim = engine.claimsLanguage(language, firstClass);
183+
// Convert boolean to number for backwards compatibility
184+
const score = typeof claim === "boolean" ? (claim ? 1 : 0) : claim;
185+
if (score > bestScore) {
186+
bestScore = score;
187+
bestEngine = engine;
178188
}
179189
}
190+
191+
if (bestEngine) {
192+
return bestEngine.launch(engineProjectContext(project));
193+
}
180194
}
181195

182196
const handlerLanguagesVal = handlerLanguages();
183197
// if there is a non-cell handler language then this must be jupyter
184-
for (const language of languages) {
198+
for (const language of languagesWithClassesMap.keys()) {
185199
if (language !== "ojs" && !handlerLanguagesVal.includes(language)) {
186200
return jupyterEngineDiscovery.launch(engineProjectContext(project));
187201
}

‎src/execute/types.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,14 @@ export interface ExecutionEngineDiscovery {
4646
defaultContent: (kernel?: string) => string[];
4747
validExtensions: () => string[];
4848
claimsFile: (file: string, ext: string) => boolean;
49-
claimsLanguage: (language: string) => boolean;
49+
/**
50+
* Whether this engine can handle the given language
51+
*
52+
* @param language - The language identifier (e.g., "python", "r", "julia")
53+
* @param firstClass - Optional first class from code block attributes (e.g., "marimo" from {python .marimo})
54+
* @returns boolean for simple claim, or number for priority (higher wins, 0 = no claim, 1 = standard claim)
55+
*/
56+
claimsLanguage: (language: string, firstClass?: string) => boolean | number;
5057
canFreeze: boolean;
5158
generatesFigures: boolean;
5259
ignoreDirs?: () => string[] | undefined;
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
title: Foo Engine
2+
author: Quarto Dev Team
3+
version: 1.0.0
4+
quarto-required: ">=1.9.17"
5+
contributes:
6+
engines:
7+
- path: foo-engine.js
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
// Minimal engine to test class-based engine override
2+
// Claims {python.foo} blocks with priority 2 (higher than Jupyter's 1)
3+
4+
let quarto;
5+
6+
const fooEngineDiscovery = {
7+
init: (quartoAPI) => {
8+
quarto = quartoAPI;
9+
},
10+
11+
name: "foo",
12+
defaultExt: ".qmd",
13+
defaultYaml: () => ["engine: foo"],
14+
defaultContent: () => ["# Foo Engine Document"],
15+
validExtensions: () => [".qmd"],
16+
17+
claimsFile: (_file, _ext) => false,
18+
19+
claimsLanguage: (language, firstClass) => {
20+
// Claim python.foo with priority 2 (overrides Jupyter's 1)
21+
if (language === "python" && firstClass === "foo") {
22+
return 2;
23+
}
24+
return 0;
25+
},
26+
27+
canFreeze: false,
28+
generatesFigures: false,
29+
30+
launch: (context) => {
31+
return {
32+
name: "foo",
33+
canFreeze: false,
34+
35+
markdownForFile: async (file) => {
36+
return quarto.mappedString.fromFile(file);
37+
},
38+
39+
target: async (file, _quiet, markdown) => {
40+
if (!markdown) {
41+
markdown = quarto.mappedString.fromFile(file);
42+
}
43+
const metadata = quarto.markdownRegex.extractYaml(markdown.value);
44+
return {
45+
source: file,
46+
input: file,
47+
markdown,
48+
metadata,
49+
};
50+
},
51+
52+
partitionedMarkdown: async (file) => {
53+
const markdown = quarto.mappedString.fromFile(file);
54+
return quarto.markdownRegex.partition(markdown.value);
55+
},
56+
57+
execute: async (options) => {
58+
// Replace python.foo code blocks with a marker div showing we processed them
59+
let markdown = options.target.markdown.value;
60+
61+
// Find and replace {python.foo} blocks with our marker output
62+
const codeBlockRegex = /```\{python\.foo[^}]*\}\n([\s\S]*?)```/g;
63+
markdown = markdown.replace(codeBlockRegex, (match, code) => {
64+
return `
65+
::: {#foo-engine-marker .foo-engine-output}
66+
**FOO ENGINE PROCESSED THIS BLOCK**
67+
68+
Original code:
69+
\`\`\`python
70+
${code.trim()}
71+
\`\`\`
72+
:::
73+
`;
74+
});
75+
76+
return {
77+
markdown: markdown,
78+
supporting: [],
79+
filters: [],
80+
};
81+
},
82+
83+
dependencies: async (_options) => {
84+
return { includes: {} };
85+
},
86+
87+
postprocess: async (_options) => {},
88+
};
89+
},
90+
};
91+
92+
export default fooEngineDiscovery;

0 commit comments

Comments
 (0)