cook.md

Cooklang API

Cook Editor exposes its Cooklang features to plugins as commands. Call them with vscode.commands.executeCommand(id, args). They run the same Rust code as the editor, so your plugin gets the same results as the built-in features.

Conventions

  • Each command takes one JSON object and returns JSON.
  • Paths are relative to the open recipe folder, e.g. "Dinner/Carbonara.cook". Absolute paths (including Windows paths like C:\Recipes\Bread.cook) and file:// URIs inside the folder also work, and relative paths may use \ or /.
  • Arguments are checked strictly: paths must be non-empty strings, scales and multipliers positive numbers, and paths and ingredient names must not contain control characters such as newlines.
  • Errors reject the promise with a readable message: No workspace is open., Recipe not found: …, Path is outside the workspace: …, Invalid arguments: ….
  • The commands don't appear in the command palette.

Version

CommandArgumentsReturns
cooklang.api.version—1

Check it when your plugin activates. The same number is available to when clauses as the context key cooklang.apiVersion, e.g. "when": "cooklang.apiVersion == 1". Version 1 only grows: new commands and optional fields may appear, nothing is removed or renamed.

Shopping lists

CommandArgumentsReturns
cooklang.api.generateShoppingList { recipes: [{ path, scale? }] } { categories: [{ name, items: [{ name, quantities }] }], other: { name, items }, pantryItems: [name] }
Categories follow config/aisle.conf; items in config/pantry.conf are moved to pantryItems. Recipes that can't be found are skipped. Pass every recipe you want counted — sub-recipes are not expanded here (use resolveRecipeReferences).
const list = await vscode.commands.executeCommand('cooklang.api.generateShoppingList', {
  recipes: [{ path: 'Dinner/Carbonara.cook', scale: 2 }, { path: 'Bread.cook' }],
});

Recipe references

CommandArgumentsReturns
cooklang.api.resolveRecipeReferences { path } — a .cook or .menu [{ path, scale, children? }] — the @recipe references, followed recursively. scale is a multiplier relative to the recipe holding the reference; {4%servings} and yield units are already converted. A reference cycle is skipped.

The shopping-list files

.shopping-list and .shopping-checked are the files CookCLI and the Shopping List plugin share. Use these commands to read and write them instead of parsing the text yourself.

CommandArgumentsReturns
cooklang.api.parseShoppingList{ text }{ items: [{ type: 'recipe', path, multiplier?, children }] }
cooklang.api.writeShoppingList{ list } (that shape; children may be left out)file text
cooklang.api.parseShoppingChecked{ text }[{ type: 'checked' | 'unchecked', name }] — later entries win
cooklang.api.writeShoppingChecked{ entries }file text, one line per entry (append it to the file)
cooklang.api.compactShoppingChecked{ entries, ingredients: [name] }the entries whose ingredient is still in ingredients

The pantry file

config/pantry.conf is the pantry CookCLI, the Shopping List and the Pantry plugin share. These commands work on its text: read the file with vscode.workspace.fs, pass the text in, and write back what editPantry returns. Edits keep comments and formatting and touch only the item you name.

CommandArgumentsReturns
cooklang.api.parsePantry { text } { sections: [{ name, items: [{ name, quantity?, bought?, expire?, low?, isLow, isOutOfStock, expireDate?, boughtDate? }] }] }
Attributes are the text as written ("500%g") and left out when absent. expireDate/boughtDate are the dates as YYYY-MM-DD, left out when they can't be read. Items above the first [section] are in the section general.
cooklang.api.editPantry { text, edit }, where edit is one of:
{ op: 'add', section, name, quantity?, bought?, expire?, low? }
{ op: 'update', section, name, fields: { quantity?, bought?, expire?, low? } }
{ op: 'remove', section, name }
The new file text.
On update, a field you leave out is unchanged and "" removes it. Adding creates the section if needed; removing a section's last item removes the section. Unknown keys are rejected. The promise rejects with a readable message for a missing section or item, a duplicate name (case-insensitive), or anything the editor can't change without rewriting parts of the file you didn't ask to touch.
const uri = vscode.Uri.joinPath(folder.uri, 'config/pantry.conf');
const text = new TextDecoder().decode(await vscode.workspace.fs.readFile(uri));
const updated = await vscode.commands.executeCommand('cooklang.api.editPantry', {
  text,
  edit: { op: 'update', section: 'fridge', name: 'milk', fields: { quantity: '2%L', expire: '' } },
});
await vscode.workspace.fs.writeFile(uri, new TextEncoder().encode(updated));

These commands were added to version 1 after it first shipped. Check that they exist with (await vscode.commands.getCommands(true)).includes('cooklang.api.editPantry') and ask users on an older Cook Editor to update.

PDF export and recipe photos

These two commands let a plugin build a document from recipes and save it as a PDF, the way the Cookbook plugin does.

CommandArgumentsReturns
cooklang.api.exportPdf { html, defaultFileName, pageSize?, pageNumbers? } { saved, path?, error? }
Turns a complete HTML document into a PDF and shows the save dialog, the same way a report's Export PDF button does. JavaScript is off while the page renders, so pass finished HTML with its CSS inline and photos as data: URIs. html may be up to 104,857,600 characters (100 MiB). defaultFileName fills in the dialog: up to 200 characters (an emoji counts as one), no /, \ or control characters such as line breaks, and .pdf is added for you. pageSize is 'A4' or 'Letter'. Leave it out and you get Letter. CSS @page { size } is ignored, so set the size here. @page margins do work. Internal links (<a href="#id">) are kept as PDF links. With pageNumbers: true every page gets its number in the bottom margin (leave about 12 mm), and each empty <span data-page-ref="id"></span> is filled with the page the element id="id" starts on, which is how you number a table of contents. IDs may use letters, digits, - and _, up to 64 characters. The document is rendered twice to work the numbers out.
You get { saved: false } when the user cancels and { saved: false, error } when the export fails. The editor doesn't show a message, so tell the user yourself.
cooklang.api.recipeImages { uri }: an absolute .cook URI, e.g. uri.toString() { title?, steps: { [section]: { [step]: uri } } }
The photos the recipe preview shows. title is the metadata image (or images, picture, pictures). If there is none, it's Recipe.jpg from the recipe's folder. Step photos are Recipe.N.jpg (step N, counted across the whole recipe) and Recipe.S.N.jpg (section S, step N). Keys are zero-based strings. Recipe.2.4.jpg is steps["1"]["3"], and Recipe.3.jpg is steps["0"]["2"]. To find step j of section s, use steps[s]?.[j] ?? steps["0"]?.[k], where k counts steps across all sections.
Local photos come back as absolute file: URIs (jpg, jpeg, png or webp); read them with vscode.workspace.fs.readFile. http(s) image URLs in metadata come back as written. The editor reads recipes from disk, so it won't see unsaved edits. For a recipe from another file system, such as the Recipe Hub, you only get its https metadata image.
const IMAGE_TYPES = { jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', webp: 'image/webp' };
const images = await vscode.commands.executeCommand('cooklang.api.recipeImages', { uri: recipeUri.toString() });
let hero = '';
if (images.title?.startsWith('file:')) {
  const ext = images.title.split('.').pop().toLowerCase();
  const bytes = await vscode.workspace.fs.readFile(vscode.Uri.parse(images.title));
  hero = `<img src="data:${IMAGE_TYPES[ext]};base64,${Buffer.from(bytes).toString('base64')}">`;
}
const html = `<!doctype html><html><head><meta charset="utf-8"></head><body><h1>My book</h1>${hero}</body></html>`;
const result = await vscode.commands.executeCommand('cooklang.api.exportPdf', {
  html, defaultFileName: 'My book', pageSize: 'A4', pageNumbers: true,
});
if (result.error) {
  vscode.window.showErrorMessage(`Export failed: ${result.error}`);
} else if (result.saved) {
  vscode.window.showInformationMessage(`Saved ${result.path}`);
}

Added in Cook Editor 0.1.0-alpha.53. Check that they exist with (await vscode.commands.getCommands(true)).includes('cooklang.api.exportPdf') and ask users on an older Cook Editor to update.